blob: 9145a0e2579be7b5cd22e7639e80a715927352db [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>
37
38// NBAIO implementations
39#include <media/nbaio/AudioStreamOutSink.h>
40#include <media/nbaio/MonoPipe.h>
41#include <media/nbaio/MonoPipeReader.h>
42#include <media/nbaio/Pipe.h>
43#include <media/nbaio/PipeReader.h>
44#include <media/nbaio/SourceAudioBufferProvider.h>
45
46#include <powermanager/PowerManager.h>
47
48#include <common_time/cc_helper.h>
49#include <common_time/local_clock.h>
50
51#include "AudioFlinger.h"
52#include "AudioMixer.h"
53#include "FastMixer.h"
54#include "ServiceUtilities.h"
55#include "SchedulingPolicyService.h"
56
Eric Laurent81784c32012-11-19 14:55:58 -080057#ifdef ADD_BATTERY_DATA
58#include <media/IMediaPlayerService.h>
59#include <media/IMediaDeathNotifier.h>
60#endif
61
Eric Laurent81784c32012-11-19 14:55:58 -080062#ifdef DEBUG_CPU_USAGE
63#include <cpustats/CentralTendencyStatistics.h>
64#include <cpustats/ThreadCpuUsage.h>
65#endif
66
67// ----------------------------------------------------------------------------
68
69// Note: the following macro is used for extremely verbose logging message. In
70// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
71// 0; but one side effect of this is to turn all LOGV's as well. Some messages
72// are so verbose that we want to suppress them even when we have ALOG_ASSERT
73// turned on. Do not uncomment the #def below unless you really know what you
74// are doing and want to see all of the extremely verbose messages.
75//#define VERY_VERY_VERBOSE_LOGGING
76#ifdef VERY_VERY_VERBOSE_LOGGING
77#define ALOGVV ALOGV
78#else
79#define ALOGVV(a...) do { } while(0)
80#endif
81
82namespace android {
83
84// retry counts for buffer fill timeout
85// 50 * ~20msecs = 1 second
86static const int8_t kMaxTrackRetries = 50;
87static const int8_t kMaxTrackStartupRetries = 50;
88// allow less retry attempts on direct output thread.
89// direct outputs can be a scarce resource in audio hardware and should
90// be released as quickly as possible.
91static const int8_t kMaxTrackRetriesDirect = 2;
92
93// don't warn about blocked writes or record buffer overflows more often than this
94static const nsecs_t kWarningThrottleNs = seconds(5);
95
96// RecordThread loop sleep time upon application overrun or audio HAL read error
97static const int kRecordThreadSleepUs = 5000;
98
99// maximum time to wait for setParameters to complete
100static const nsecs_t kSetParametersTimeoutNs = seconds(2);
101
102// minimum sleep time for the mixer thread loop when tracks are active but in underrun
103static const uint32_t kMinThreadSleepTimeUs = 5000;
104// maximum divider applied to the active sleep time in the mixer thread loop
105static const uint32_t kMaxThreadSleepTimeShift = 2;
106
107// minimum normal mix buffer size, expressed in milliseconds rather than frames
108static const uint32_t kMinNormalMixBufferSizeMs = 20;
109// maximum normal mix buffer size
110static const uint32_t kMaxNormalMixBufferSizeMs = 24;
111
Eric Laurent972a1732013-09-04 09:42:59 -0700112// Offloaded output thread standby delay: allows track transition without going to standby
113static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
114
Eric Laurent81784c32012-11-19 14:55:58 -0800115// Whether to use fast mixer
116static const enum {
117 FastMixer_Never, // never initialize or use: for debugging only
118 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
119 // normal mixer multiplier is 1
120 FastMixer_Static, // initialize if needed, then use all the time if initialized,
121 // multiplier is calculated based on min & max normal mixer buffer size
122 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
123 // multiplier is calculated based on min & max normal mixer buffer size
124 // FIXME for FastMixer_Dynamic:
125 // Supporting this option will require fixing HALs that can't handle large writes.
126 // For example, one HAL implementation returns an error from a large write,
127 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
128 // We could either fix the HAL implementations, or provide a wrapper that breaks
129 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
130} kUseFastMixer = FastMixer_Static;
131
132// Priorities for requestPriority
133static const int kPriorityAudioApp = 2;
134static const int kPriorityFastMixer = 3;
135
136// IAudioFlinger::createTrack() reports back to client the total size of shared memory area
137// for the track. The client then sub-divides this into smaller buffers for its use.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800138// Currently the client uses N-buffering by default, but doesn't tell us about the value of N.
139// So for now we just assume that client is double-buffered for fast tracks.
140// FIXME It would be better for client to tell AudioFlinger the value of N,
141// so AudioFlinger could allocate the right amount of memory.
Eric Laurent81784c32012-11-19 14:55:58 -0800142// See the client's minBufCount and mNotificationFramesAct calculations for details.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800143static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800144
145// ----------------------------------------------------------------------------
146
147#ifdef ADD_BATTERY_DATA
148// To collect the amplifier usage
149static void addBatteryData(uint32_t params) {
150 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
151 if (service == NULL) {
152 // it already logged
153 return;
154 }
155
156 service->addBatteryData(params);
157}
158#endif
159
160
161// ----------------------------------------------------------------------------
162// CPU Stats
163// ----------------------------------------------------------------------------
164
165class CpuStats {
166public:
167 CpuStats();
168 void sample(const String8 &title);
169#ifdef DEBUG_CPU_USAGE
170private:
171 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
172 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
173
174 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
175
176 int mCpuNum; // thread's current CPU number
177 int mCpukHz; // frequency of thread's current CPU in kHz
178#endif
179};
180
181CpuStats::CpuStats()
182#ifdef DEBUG_CPU_USAGE
183 : mCpuNum(-1), mCpukHz(-1)
184#endif
185{
186}
187
Glenn Kasten0f11b512014-01-31 16:18:54 -0800188void CpuStats::sample(const String8 &title
189#ifndef DEBUG_CPU_USAGE
190 __unused
191#endif
192 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800193#ifdef DEBUG_CPU_USAGE
194 // get current thread's delta CPU time in wall clock ns
195 double wcNs;
196 bool valid = mCpuUsage.sampleAndEnable(wcNs);
197
198 // record sample for wall clock statistics
199 if (valid) {
200 mWcStats.sample(wcNs);
201 }
202
203 // get the current CPU number
204 int cpuNum = sched_getcpu();
205
206 // get the current CPU frequency in kHz
207 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
208
209 // check if either CPU number or frequency changed
210 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
211 mCpuNum = cpuNum;
212 mCpukHz = cpukHz;
213 // ignore sample for purposes of cycles
214 valid = false;
215 }
216
217 // if no change in CPU number or frequency, then record sample for cycle statistics
218 if (valid && mCpukHz > 0) {
219 double cycles = wcNs * cpukHz * 0.000001;
220 mHzStats.sample(cycles);
221 }
222
223 unsigned n = mWcStats.n();
224 // mCpuUsage.elapsed() is expensive, so don't call it every loop
225 if ((n & 127) == 1) {
226 long long elapsed = mCpuUsage.elapsed();
227 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
228 double perLoop = elapsed / (double) n;
229 double perLoop100 = perLoop * 0.01;
230 double perLoop1k = perLoop * 0.001;
231 double mean = mWcStats.mean();
232 double stddev = mWcStats.stddev();
233 double minimum = mWcStats.minimum();
234 double maximum = mWcStats.maximum();
235 double meanCycles = mHzStats.mean();
236 double stddevCycles = mHzStats.stddev();
237 double minCycles = mHzStats.minimum();
238 double maxCycles = mHzStats.maximum();
239 mCpuUsage.resetElapsed();
240 mWcStats.reset();
241 mHzStats.reset();
242 ALOGD("CPU usage for %s over past %.1f secs\n"
243 " (%u mixer loops at %.1f mean ms per loop):\n"
244 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
245 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
246 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
247 title.string(),
248 elapsed * .000000001, n, perLoop * .000001,
249 mean * .001,
250 stddev * .001,
251 minimum * .001,
252 maximum * .001,
253 mean / perLoop100,
254 stddev / perLoop100,
255 minimum / perLoop100,
256 maximum / perLoop100,
257 meanCycles / perLoop1k,
258 stddevCycles / perLoop1k,
259 minCycles / perLoop1k,
260 maxCycles / perLoop1k);
261
262 }
263 }
264#endif
265};
266
267// ----------------------------------------------------------------------------
268// ThreadBase
269// ----------------------------------------------------------------------------
270
271AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
272 audio_devices_t outDevice, audio_devices_t inDevice, type_t type)
273 : Thread(false /*canCallJava*/),
274 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700275 mAudioFlinger(audioFlinger),
Glenn Kasten70949c42013-08-06 07:40:12 -0700276 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800277 // are set by PlaybackThread::readOutputParameters_l() or
278 // RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -0800279 mParamStatus(NO_ERROR),
Eric Laurentfd477972013-10-25 18:10:40 -0700280 //FIXME: mStandby should be true here. Is this some kind of hack?
Eric Laurent81784c32012-11-19 14:55:58 -0800281 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
282 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
283 // mName will be set by concrete (non-virtual) subclass
284 mDeathRecipient(new PMDeathRecipient(this))
285{
286}
287
288AudioFlinger::ThreadBase::~ThreadBase()
289{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700290 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
291 for (size_t i = 0; i < mConfigEvents.size(); i++) {
292 delete mConfigEvents[i];
293 }
294 mConfigEvents.clear();
295
Eric Laurent81784c32012-11-19 14:55:58 -0800296 mParamCond.broadcast();
297 // do not lock the mutex in destructor
298 releaseWakeLock_l();
299 if (mPowerManager != 0) {
300 sp<IBinder> binder = mPowerManager->asBinder();
301 binder->unlinkToDeath(mDeathRecipient);
302 }
303}
304
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700305status_t AudioFlinger::ThreadBase::readyToRun()
306{
307 status_t status = initCheck();
308 if (status == NO_ERROR) {
309 ALOGI("AudioFlinger's thread %p ready to run", this);
310 } else {
311 ALOGE("No working audio driver found.");
312 }
313 return status;
314}
315
Eric Laurent81784c32012-11-19 14:55:58 -0800316void AudioFlinger::ThreadBase::exit()
317{
318 ALOGV("ThreadBase::exit");
319 // do any cleanup required for exit to succeed
320 preExit();
321 {
322 // This lock prevents the following race in thread (uniprocessor for illustration):
323 // if (!exitPending()) {
324 // // context switch from here to exit()
325 // // exit() calls requestExit(), what exitPending() observes
326 // // exit() calls signal(), which is dropped since no waiters
327 // // context switch back from exit() to here
328 // mWaitWorkCV.wait(...);
329 // // now thread is hung
330 // }
331 AutoMutex lock(mLock);
332 requestExit();
333 mWaitWorkCV.broadcast();
334 }
335 // When Thread::requestExitAndWait is made virtual and this method is renamed to
336 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
337 requestExitAndWait();
338}
339
340status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
341{
342 status_t status;
343
344 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
345 Mutex::Autolock _l(mLock);
346
347 mNewParameters.add(keyValuePairs);
348 mWaitWorkCV.signal();
349 // wait condition with timeout in case the thread loop has exited
350 // before the request could be processed
351 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
352 status = mParamStatus;
353 mWaitWorkCV.signal();
354 } else {
355 status = TIMED_OUT;
356 }
357 return status;
358}
359
360void AudioFlinger::ThreadBase::sendIoConfigEvent(int event, int param)
361{
362 Mutex::Autolock _l(mLock);
363 sendIoConfigEvent_l(event, param);
364}
365
366// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
367void AudioFlinger::ThreadBase::sendIoConfigEvent_l(int event, int param)
368{
369 IoConfigEvent *ioEvent = new IoConfigEvent(event, param);
370 mConfigEvents.add(static_cast<ConfigEvent *>(ioEvent));
371 ALOGV("sendIoConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event,
372 param);
373 mWaitWorkCV.signal();
374}
375
376// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
377void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
378{
379 PrioConfigEvent *prioEvent = new PrioConfigEvent(pid, tid, prio);
380 mConfigEvents.add(static_cast<ConfigEvent *>(prioEvent));
381 ALOGV("sendPrioConfigEvent_l() num events %d pid %d, tid %d prio %d",
382 mConfigEvents.size(), pid, tid, prio);
383 mWaitWorkCV.signal();
384}
385
386void AudioFlinger::ThreadBase::processConfigEvents()
387{
Glenn Kastenf7773312013-08-13 16:00:42 -0700388 Mutex::Autolock _l(mLock);
389 processConfigEvents_l();
390}
391
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700392// post condition: mConfigEvents.isEmpty()
Glenn Kastenf7773312013-08-13 16:00:42 -0700393void AudioFlinger::ThreadBase::processConfigEvents_l()
394{
Eric Laurent81784c32012-11-19 14:55:58 -0800395 while (!mConfigEvents.isEmpty()) {
396 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
397 ConfigEvent *event = mConfigEvents[0];
398 mConfigEvents.removeAt(0);
399 // release mLock before locking AudioFlinger mLock: lock order is always
400 // AudioFlinger then ThreadBase to avoid cross deadlock
401 mLock.unlock();
Glenn Kastene198c362013-08-13 09:13:36 -0700402 switch (event->type()) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700403 case CFG_EVENT_PRIO: {
404 PrioConfigEvent *prioEvent = static_cast<PrioConfigEvent *>(event);
405 // FIXME Need to understand why this has be done asynchronously
406 int err = requestPriority(prioEvent->pid(), prioEvent->tid(), prioEvent->prio(),
407 true /*asynchronous*/);
408 if (err != 0) {
409 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
410 prioEvent->prio(), prioEvent->pid(), prioEvent->tid(), err);
411 }
412 } break;
413 case CFG_EVENT_IO: {
414 IoConfigEvent *ioEvent = static_cast<IoConfigEvent *>(event);
Glenn Kastend5418eb2013-08-14 13:11:06 -0700415 {
416 Mutex::Autolock _l(mAudioFlinger->mLock);
417 audioConfigChanged_l(ioEvent->event(), ioEvent->param());
418 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700419 } break;
420 default:
421 ALOGE("processConfigEvents() unknown event type %d", event->type());
422 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800423 }
424 delete event;
425 mLock.lock();
426 }
Eric Laurent81784c32012-11-19 14:55:58 -0800427}
428
Marco Nelissenb2208842014-02-07 14:00:50 -0800429String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
430 String8 s;
431 if (output) {
432 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
433 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
434 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
435 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
436 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
437 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
438 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
439 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
440 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
441 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
442 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
443 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
444 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
445 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
446 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
447 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
448 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
449 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
450 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
451 } else {
452 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
453 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
454 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
455 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
456 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
457 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
458 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
459 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
460 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
461 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
462 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
463 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
464 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
465 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
466 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
467 }
468 int len = s.length();
469 if (s.length() > 2) {
470 char *str = s.lockBuffer(len);
471 s.unlockBuffer(len - 2);
472 }
473 return s;
474}
475
Glenn Kasten0f11b512014-01-31 16:18:54 -0800476void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800477{
478 const size_t SIZE = 256;
479 char buffer[SIZE];
480 String8 result;
481
482 bool locked = AudioFlinger::dumpTryLock(mLock);
483 if (!locked) {
Marco Nelissenb2208842014-02-07 14:00:50 -0800484 fdprintf(fd, "thread %p maybe dead locked\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -0800485 }
486
Marco Nelissenb2208842014-02-07 14:00:50 -0800487 fdprintf(fd, " I/O handle: %d\n", mId);
488 fdprintf(fd, " TID: %d\n", getTid());
489 fdprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
490 fdprintf(fd, " Sample rate: %u\n", mSampleRate);
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000491 fdprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Marco Nelissenb2208842014-02-07 14:00:50 -0800492 fdprintf(fd, " HAL buffer size: %u bytes\n", mBufferSize);
493 fdprintf(fd, " Channel Count: %u\n", mChannelCount);
494 fdprintf(fd, " Channel Mask: 0x%08x (%s)\n", mChannelMask,
495 channelMaskToString(mChannelMask, mType != RECORD).string());
496 fdprintf(fd, " Format: 0x%x (%s)\n", mFormat, formatToString(mFormat));
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000497 fdprintf(fd, " Frame size: %zu\n", mFrameSize);
Marco Nelissenb2208842014-02-07 14:00:50 -0800498 fdprintf(fd, " Pending setParameters commands:");
499 size_t numParams = mNewParameters.size();
500 if (numParams) {
501 fdprintf(fd, "\n Index Command");
502 for (size_t i = 0; i < numParams; ++i) {
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000503 fdprintf(fd, "\n %02zu ", i);
Marco Nelissenb2208842014-02-07 14:00:50 -0800504 fdprintf(fd, mNewParameters[i]);
505 }
506 fdprintf(fd, "\n");
507 } else {
508 fdprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800509 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800510 fdprintf(fd, " Pending config events:");
511 size_t numConfig = mConfigEvents.size();
512 if (numConfig) {
513 for (size_t i = 0; i < numConfig; i++) {
514 mConfigEvents[i]->dump(buffer, SIZE);
515 fdprintf(fd, "\n %s", buffer);
516 }
517 fdprintf(fd, "\n");
518 } else {
519 fdprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800520 }
Eric Laurent81784c32012-11-19 14:55:58 -0800521
522 if (locked) {
523 mLock.unlock();
524 }
525}
526
527void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
528{
529 const size_t SIZE = 256;
530 char buffer[SIZE];
531 String8 result;
532
Marco Nelissenb2208842014-02-07 14:00:50 -0800533 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000534 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800535 write(fd, buffer, strlen(buffer));
536
Marco Nelissenb2208842014-02-07 14:00:50 -0800537 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800538 sp<EffectChain> chain = mEffectChains[i];
539 if (chain != 0) {
540 chain->dump(fd, args);
541 }
542 }
543}
544
Marco Nelissene14a5d62013-10-03 08:51:24 -0700545void AudioFlinger::ThreadBase::acquireWakeLock(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800546{
547 Mutex::Autolock _l(mLock);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700548 acquireWakeLock_l(uid);
Eric Laurent81784c32012-11-19 14:55:58 -0800549}
550
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100551String16 AudioFlinger::ThreadBase::getWakeLockTag()
552{
553 switch (mType) {
554 case MIXER:
555 return String16("AudioMix");
556 case DIRECT:
557 return String16("AudioDirectOut");
558 case DUPLICATING:
559 return String16("AudioDup");
560 case RECORD:
561 return String16("AudioIn");
562 case OFFLOAD:
563 return String16("AudioOffload");
564 default:
565 ALOG_ASSERT(false);
566 return String16("AudioUnknown");
567 }
568}
569
Marco Nelissene14a5d62013-10-03 08:51:24 -0700570void AudioFlinger::ThreadBase::acquireWakeLock_l(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800571{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800572 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800573 if (mPowerManager != 0) {
574 sp<IBinder> binder = new BBinder();
Marco Nelissene14a5d62013-10-03 08:51:24 -0700575 status_t status;
576 if (uid >= 0) {
Eric Laurent547789d2013-10-04 11:46:55 -0700577 status = mPowerManager->acquireWakeLockWithUid(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700578 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100579 getWakeLockTag(),
Marco Nelissene14a5d62013-10-03 08:51:24 -0700580 String16("media"),
581 uid);
582 } else {
Eric Laurent547789d2013-10-04 11:46:55 -0700583 status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700584 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100585 getWakeLockTag(),
Marco Nelissene14a5d62013-10-03 08:51:24 -0700586 String16("media"));
587 }
Eric Laurent81784c32012-11-19 14:55:58 -0800588 if (status == NO_ERROR) {
589 mWakeLockToken = binder;
590 }
591 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
592 }
593}
594
595void AudioFlinger::ThreadBase::releaseWakeLock()
596{
597 Mutex::Autolock _l(mLock);
598 releaseWakeLock_l();
599}
600
601void AudioFlinger::ThreadBase::releaseWakeLock_l()
602{
603 if (mWakeLockToken != 0) {
604 ALOGV("releaseWakeLock_l() %s", mName);
605 if (mPowerManager != 0) {
606 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
607 }
608 mWakeLockToken.clear();
609 }
610}
611
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800612void AudioFlinger::ThreadBase::updateWakeLockUids(const SortedVector<int> &uids) {
613 Mutex::Autolock _l(mLock);
614 updateWakeLockUids_l(uids);
615}
616
617void AudioFlinger::ThreadBase::getPowerManager_l() {
618
619 if (mPowerManager == 0) {
620 // use checkService() to avoid blocking if power service is not up yet
621 sp<IBinder> binder =
622 defaultServiceManager()->checkService(String16("power"));
623 if (binder == 0) {
624 ALOGW("Thread %s cannot connect to the power manager service", mName);
625 } else {
626 mPowerManager = interface_cast<IPowerManager>(binder);
627 binder->linkToDeath(mDeathRecipient);
628 }
629 }
630}
631
632void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<int> &uids) {
633
634 getPowerManager_l();
635 if (mWakeLockToken == NULL) {
636 ALOGE("no wake lock to update!");
637 return;
638 }
639 if (mPowerManager != 0) {
640 sp<IBinder> binder = new BBinder();
641 status_t status;
642 status = mPowerManager->updateWakeLockUids(mWakeLockToken, uids.size(), uids.array());
643 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
644 }
645}
646
Eric Laurent81784c32012-11-19 14:55:58 -0800647void AudioFlinger::ThreadBase::clearPowerManager()
648{
649 Mutex::Autolock _l(mLock);
650 releaseWakeLock_l();
651 mPowerManager.clear();
652}
653
Glenn Kasten0f11b512014-01-31 16:18:54 -0800654void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800655{
656 sp<ThreadBase> thread = mThread.promote();
657 if (thread != 0) {
658 thread->clearPowerManager();
659 }
660 ALOGW("power manager service died !!!");
661}
662
663void AudioFlinger::ThreadBase::setEffectSuspended(
664 const effect_uuid_t *type, bool suspend, int sessionId)
665{
666 Mutex::Autolock _l(mLock);
667 setEffectSuspended_l(type, suspend, sessionId);
668}
669
670void AudioFlinger::ThreadBase::setEffectSuspended_l(
671 const effect_uuid_t *type, bool suspend, int sessionId)
672{
673 sp<EffectChain> chain = getEffectChain_l(sessionId);
674 if (chain != 0) {
675 if (type != NULL) {
676 chain->setEffectSuspended_l(type, suspend);
677 } else {
678 chain->setEffectSuspendedAll_l(suspend);
679 }
680 }
681
682 updateSuspendedSessions_l(type, suspend, sessionId);
683}
684
685void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
686{
687 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
688 if (index < 0) {
689 return;
690 }
691
692 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
693 mSuspendedSessions.valueAt(index);
694
695 for (size_t i = 0; i < sessionEffects.size(); i++) {
696 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
697 for (int j = 0; j < desc->mRefCount; j++) {
698 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
699 chain->setEffectSuspendedAll_l(true);
700 } else {
701 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
702 desc->mType.timeLow);
703 chain->setEffectSuspended_l(&desc->mType, true);
704 }
705 }
706 }
707}
708
709void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
710 bool suspend,
711 int sessionId)
712{
713 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
714
715 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
716
717 if (suspend) {
718 if (index >= 0) {
719 sessionEffects = mSuspendedSessions.valueAt(index);
720 } else {
721 mSuspendedSessions.add(sessionId, sessionEffects);
722 }
723 } else {
724 if (index < 0) {
725 return;
726 }
727 sessionEffects = mSuspendedSessions.valueAt(index);
728 }
729
730
731 int key = EffectChain::kKeyForSuspendAll;
732 if (type != NULL) {
733 key = type->timeLow;
734 }
735 index = sessionEffects.indexOfKey(key);
736
737 sp<SuspendedSessionDesc> desc;
738 if (suspend) {
739 if (index >= 0) {
740 desc = sessionEffects.valueAt(index);
741 } else {
742 desc = new SuspendedSessionDesc();
743 if (type != NULL) {
744 desc->mType = *type;
745 }
746 sessionEffects.add(key, desc);
747 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
748 }
749 desc->mRefCount++;
750 } else {
751 if (index < 0) {
752 return;
753 }
754 desc = sessionEffects.valueAt(index);
755 if (--desc->mRefCount == 0) {
756 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
757 sessionEffects.removeItemsAt(index);
758 if (sessionEffects.isEmpty()) {
759 ALOGV("updateSuspendedSessions_l() restore removing session %d",
760 sessionId);
761 mSuspendedSessions.removeItem(sessionId);
762 }
763 }
764 }
765 if (!sessionEffects.isEmpty()) {
766 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
767 }
768}
769
770void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
771 bool enabled,
772 int sessionId)
773{
774 Mutex::Autolock _l(mLock);
775 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
776}
777
778void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
779 bool enabled,
780 int sessionId)
781{
782 if (mType != RECORD) {
783 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
784 // another session. This gives the priority to well behaved effect control panels
785 // and applications not using global effects.
786 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
787 // global effects
788 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
789 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
790 }
791 }
792
793 sp<EffectChain> chain = getEffectChain_l(sessionId);
794 if (chain != 0) {
795 chain->checkSuspendOnEffectEnabled(effect, enabled);
796 }
797}
798
799// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
800sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
801 const sp<AudioFlinger::Client>& client,
802 const sp<IEffectClient>& effectClient,
803 int32_t priority,
804 int sessionId,
805 effect_descriptor_t *desc,
806 int *enabled,
Glenn Kasten9156ef32013-08-06 15:39:08 -0700807 status_t *status)
Eric Laurent81784c32012-11-19 14:55:58 -0800808{
809 sp<EffectModule> effect;
810 sp<EffectHandle> handle;
811 status_t lStatus;
812 sp<EffectChain> chain;
813 bool chainCreated = false;
814 bool effectCreated = false;
815 bool effectRegistered = false;
816
817 lStatus = initCheck();
818 if (lStatus != NO_ERROR) {
819 ALOGW("createEffect_l() Audio driver not initialized.");
820 goto Exit;
821 }
822
Eric Laurent5baf2af2013-09-12 17:37:00 -0700823 // Allow global effects only on offloaded and mixer threads
824 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
825 switch (mType) {
826 case MIXER:
827 case OFFLOAD:
828 break;
829 case DIRECT:
830 case DUPLICATING:
831 case RECORD:
832 default:
833 ALOGW("createEffect_l() Cannot add global effect %s on thread %s", desc->name, mName);
834 lStatus = BAD_VALUE;
835 goto Exit;
836 }
Eric Laurent81784c32012-11-19 14:55:58 -0800837 }
Eric Laurent5baf2af2013-09-12 17:37:00 -0700838
Eric Laurent81784c32012-11-19 14:55:58 -0800839 // Only Pre processor effects are allowed on input threads and only on input threads
840 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
841 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
842 desc->name, desc->flags, mType);
843 lStatus = BAD_VALUE;
844 goto Exit;
845 }
846
847 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
848
849 { // scope for mLock
850 Mutex::Autolock _l(mLock);
851
852 // check for existing effect chain with the requested audio session
853 chain = getEffectChain_l(sessionId);
854 if (chain == 0) {
855 // create a new chain for this session
856 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
857 chain = new EffectChain(this, sessionId);
858 addEffectChain_l(chain);
859 chain->setStrategy(getStrategyForSession_l(sessionId));
860 chainCreated = true;
861 } else {
862 effect = chain->getEffectFromDesc_l(desc);
863 }
864
865 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
866
867 if (effect == 0) {
868 int id = mAudioFlinger->nextUniqueId();
869 // Check CPU and memory usage
870 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
871 if (lStatus != NO_ERROR) {
872 goto Exit;
873 }
874 effectRegistered = true;
875 // create a new effect module if none present in the chain
876 effect = new EffectModule(this, chain, desc, id, sessionId);
877 lStatus = effect->status();
878 if (lStatus != NO_ERROR) {
879 goto Exit;
880 }
Eric Laurent5baf2af2013-09-12 17:37:00 -0700881 effect->setOffloaded(mType == OFFLOAD, mId);
882
Eric Laurent81784c32012-11-19 14:55:58 -0800883 lStatus = chain->addEffect_l(effect);
884 if (lStatus != NO_ERROR) {
885 goto Exit;
886 }
887 effectCreated = true;
888
889 effect->setDevice(mOutDevice);
890 effect->setDevice(mInDevice);
891 effect->setMode(mAudioFlinger->getMode());
892 effect->setAudioSource(mAudioSource);
893 }
894 // create effect handle and connect it to effect module
895 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -0800896 lStatus = handle->initCheck();
897 if (lStatus == OK) {
898 lStatus = effect->addHandle(handle.get());
899 }
Eric Laurent81784c32012-11-19 14:55:58 -0800900 if (enabled != NULL) {
901 *enabled = (int)effect->isEnabled();
902 }
903 }
904
905Exit:
906 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
907 Mutex::Autolock _l(mLock);
908 if (effectCreated) {
909 chain->removeEffect_l(effect);
910 }
911 if (effectRegistered) {
912 AudioSystem::unregisterEffect(effect->id());
913 }
914 if (chainCreated) {
915 removeEffectChain_l(chain);
916 }
917 handle.clear();
918 }
919
Glenn Kasten9156ef32013-08-06 15:39:08 -0700920 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800921 return handle;
922}
923
924sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
925{
926 Mutex::Autolock _l(mLock);
927 return getEffect_l(sessionId, effectId);
928}
929
930sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
931{
932 sp<EffectChain> chain = getEffectChain_l(sessionId);
933 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
934}
935
936// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
937// PlaybackThread::mLock held
938status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
939{
940 // check for existing effect chain with the requested audio session
941 int sessionId = effect->sessionId();
942 sp<EffectChain> chain = getEffectChain_l(sessionId);
943 bool chainCreated = false;
944
Eric Laurent5baf2af2013-09-12 17:37:00 -0700945 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
946 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
947 this, effect->desc().name, effect->desc().flags);
948
Eric Laurent81784c32012-11-19 14:55:58 -0800949 if (chain == 0) {
950 // create a new chain for this session
951 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
952 chain = new EffectChain(this, sessionId);
953 addEffectChain_l(chain);
954 chain->setStrategy(getStrategyForSession_l(sessionId));
955 chainCreated = true;
956 }
957 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
958
959 if (chain->getEffectFromId_l(effect->id()) != 0) {
960 ALOGW("addEffect_l() %p effect %s already present in chain %p",
961 this, effect->desc().name, chain.get());
962 return BAD_VALUE;
963 }
964
Eric Laurent5baf2af2013-09-12 17:37:00 -0700965 effect->setOffloaded(mType == OFFLOAD, mId);
966
Eric Laurent81784c32012-11-19 14:55:58 -0800967 status_t status = chain->addEffect_l(effect);
968 if (status != NO_ERROR) {
969 if (chainCreated) {
970 removeEffectChain_l(chain);
971 }
972 return status;
973 }
974
975 effect->setDevice(mOutDevice);
976 effect->setDevice(mInDevice);
977 effect->setMode(mAudioFlinger->getMode());
978 effect->setAudioSource(mAudioSource);
979 return NO_ERROR;
980}
981
982void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
983
984 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
985 effect_descriptor_t desc = effect->desc();
986 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
987 detachAuxEffect_l(effect->id());
988 }
989
990 sp<EffectChain> chain = effect->chain().promote();
991 if (chain != 0) {
992 // remove effect chain if removing last effect
993 if (chain->removeEffect_l(effect) == 0) {
994 removeEffectChain_l(chain);
995 }
996 } else {
997 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
998 }
999}
1000
1001void AudioFlinger::ThreadBase::lockEffectChains_l(
1002 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1003{
1004 effectChains = mEffectChains;
1005 for (size_t i = 0; i < mEffectChains.size(); i++) {
1006 mEffectChains[i]->lock();
1007 }
1008}
1009
1010void AudioFlinger::ThreadBase::unlockEffectChains(
1011 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1012{
1013 for (size_t i = 0; i < effectChains.size(); i++) {
1014 effectChains[i]->unlock();
1015 }
1016}
1017
1018sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
1019{
1020 Mutex::Autolock _l(mLock);
1021 return getEffectChain_l(sessionId);
1022}
1023
1024sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const
1025{
1026 size_t size = mEffectChains.size();
1027 for (size_t i = 0; i < size; i++) {
1028 if (mEffectChains[i]->sessionId() == sessionId) {
1029 return mEffectChains[i];
1030 }
1031 }
1032 return 0;
1033}
1034
1035void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1036{
1037 Mutex::Autolock _l(mLock);
1038 size_t size = mEffectChains.size();
1039 for (size_t i = 0; i < size; i++) {
1040 mEffectChains[i]->setMode_l(mode);
1041 }
1042}
1043
1044void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
1045 EffectHandle *handle,
1046 bool unpinIfLast) {
1047
1048 Mutex::Autolock _l(mLock);
1049 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
1050 // delete the effect module if removing last handle on it
1051 if (effect->removeHandle(handle) == 0) {
1052 if (!effect->isPinned() || unpinIfLast) {
1053 removeEffect_l(effect);
1054 AudioSystem::unregisterEffect(effect->id());
1055 }
1056 }
1057}
1058
1059// ----------------------------------------------------------------------------
1060// Playback
1061// ----------------------------------------------------------------------------
1062
1063AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1064 AudioStreamOut* output,
1065 audio_io_handle_t id,
1066 audio_devices_t device,
1067 type_t type)
1068 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type),
Glenn Kasten9b58f632013-07-16 11:37:48 -07001069 mNormalFrameCount(0), mMixBuffer(NULL),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001070 mSuspended(0), mBytesWritten(0),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001071 mActiveTracksGeneration(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001072 // mStreamTypes[] initialized in constructor body
1073 mOutput(output),
1074 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
1075 mMixerStatus(MIXER_IDLE),
1076 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
1077 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001078 mBytesRemaining(0),
1079 mCurrentWriteLength(0),
1080 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001081 mWriteAckSequence(0),
1082 mDrainSequence(0),
Eric Laurentede6c3b2013-09-19 14:37:46 -07001083 mSignalPending(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001084 mScreenState(AudioFlinger::mScreenState),
1085 // index 0 is reserved for normal mixer's submix
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001086 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1),
1087 // mLatchD, mLatchQ,
1088 mLatchDValid(false), mLatchQValid(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001089{
1090 snprintf(mName, kNameLength, "AudioOut_%X", id);
Glenn Kasten9e58b552013-01-18 15:09:48 -08001091 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mName);
Eric Laurent81784c32012-11-19 14:55:58 -08001092
1093 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1094 // it would be safer to explicitly pass initial masterVolume/masterMute as
1095 // parameter.
1096 //
1097 // If the HAL we are using has support for master volume or master mute,
1098 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1099 // and the mute set to false).
1100 mMasterVolume = audioFlinger->masterVolume_l();
1101 mMasterMute = audioFlinger->masterMute_l();
1102 if (mOutput && mOutput->audioHwDev) {
1103 if (mOutput->audioHwDev->canSetMasterVolume()) {
1104 mMasterVolume = 1.0;
1105 }
1106
1107 if (mOutput->audioHwDev->canSetMasterMute()) {
1108 mMasterMute = false;
1109 }
1110 }
1111
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001112 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001113
1114 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
1115 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1116 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1117 stream = (audio_stream_type_t) (stream + 1)) {
1118 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1119 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1120 }
1121 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1122 // because mAudioFlinger doesn't have one to copy from
1123}
1124
1125AudioFlinger::PlaybackThread::~PlaybackThread()
1126{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001127 mAudioFlinger->unregisterWriter(mNBLogWriter);
Glenn Kastenc1fac192013-08-06 07:41:36 -07001128 delete[] mMixBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08001129}
1130
1131void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1132{
1133 dumpInternals(fd, args);
1134 dumpTracks(fd, args);
1135 dumpEffectChains(fd, args);
1136}
1137
Glenn Kasten0f11b512014-01-31 16:18:54 -08001138void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001139{
1140 const size_t SIZE = 256;
1141 char buffer[SIZE];
1142 String8 result;
1143
Marco Nelissenb2208842014-02-07 14:00:50 -08001144 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001145 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1146 const stream_type_t *st = &mStreamTypes[i];
1147 if (i > 0) {
1148 result.appendFormat(", ");
1149 }
1150 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1151 if (st->mute) {
1152 result.append("M");
1153 }
1154 }
1155 result.append("\n");
1156 write(fd, result.string(), result.length());
1157 result.clear();
1158
Eric Laurent81784c32012-11-19 14:55:58 -08001159 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1160 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Marco Nelissenb2208842014-02-07 14:00:50 -08001161 fdprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001162 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001163
1164 size_t numtracks = mTracks.size();
1165 size_t numactive = mActiveTracks.size();
1166 fdprintf(fd, " %d Tracks", numtracks);
1167 size_t numactiveseen = 0;
1168 if (numtracks) {
1169 fdprintf(fd, " of which %d are active\n", numactive);
1170 Track::appendDumpHeader(result);
1171 for (size_t i = 0; i < numtracks; ++i) {
1172 sp<Track> track = mTracks[i];
1173 if (track != 0) {
1174 bool active = mActiveTracks.indexOf(track) >= 0;
1175 if (active) {
1176 numactiveseen++;
1177 }
1178 track->dump(buffer, SIZE, active);
1179 result.append(buffer);
1180 }
1181 }
1182 } else {
1183 result.append("\n");
1184 }
1185 if (numactiveseen != numactive) {
1186 // some tracks in the active list were not in the tracks list
1187 snprintf(buffer, SIZE, " The following tracks are in the active list but"
1188 " not in the track list\n");
1189 result.append(buffer);
1190 Track::appendDumpHeader(result);
1191 for (size_t i = 0; i < numactive; ++i) {
1192 sp<Track> track = mActiveTracks[i].promote();
1193 if (track != 0 && mTracks.indexOf(track) < 0) {
1194 track->dump(buffer, SIZE, true);
1195 result.append(buffer);
1196 }
1197 }
1198 }
1199
1200 write(fd, result.string(), result.size());
1201
Eric Laurent81784c32012-11-19 14:55:58 -08001202}
1203
1204void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1205{
Marco Nelissenb2208842014-02-07 14:00:50 -08001206 fdprintf(fd, "\nOutput thread %p:\n", this);
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +00001207 fdprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Marco Nelissenb2208842014-02-07 14:00:50 -08001208 fdprintf(fd, " Last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1209 fdprintf(fd, " Total writes: %d\n", mNumWrites);
1210 fdprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1211 fdprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1212 fdprintf(fd, " Suspend count: %d\n", mSuspended);
1213 fdprintf(fd, " Mix buffer : %p\n", mMixBuffer);
1214 fdprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent81784c32012-11-19 14:55:58 -08001215
1216 dumpBase(fd, args);
1217}
1218
1219// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001220
1221void AudioFlinger::PlaybackThread::onFirstRef()
1222{
1223 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
1224}
1225
1226// ThreadBase virtuals
1227void AudioFlinger::PlaybackThread::preExit()
1228{
1229 ALOGV(" preExit()");
1230 // FIXME this is using hard-coded strings but in the future, this functionality will be
1231 // converted to use audio HAL extensions required to support tunneling
1232 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1233}
1234
1235// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1236sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1237 const sp<AudioFlinger::Client>& client,
1238 audio_stream_type_t streamType,
1239 uint32_t sampleRate,
1240 audio_format_t format,
1241 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001242 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001243 const sp<IMemory>& sharedBuffer,
1244 int sessionId,
1245 IAudioFlinger::track_flags_t *flags,
1246 pid_t tid,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001247 int uid,
Eric Laurent81784c32012-11-19 14:55:58 -08001248 status_t *status)
1249{
Glenn Kasten74935e42013-12-19 08:56:45 -08001250 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001251 sp<Track> track;
1252 status_t lStatus;
1253
1254 bool isTimed = (*flags & IAudioFlinger::TRACK_TIMED) != 0;
1255
1256 // client expresses a preference for FAST, but we get the final say
1257 if (*flags & IAudioFlinger::TRACK_FAST) {
1258 if (
1259 // not timed
1260 (!isTimed) &&
1261 // either of these use cases:
1262 (
1263 // use case 1: shared buffer with any frame count
1264 (
1265 (sharedBuffer != 0)
1266 ) ||
1267 // use case 2: callback handler and frame count is default or at least as large as HAL
1268 (
1269 (tid != -1) &&
1270 ((frameCount == 0) ||
Glenn Kastenb5fed682013-12-03 09:06:43 -08001271 (frameCount >= mFrameCount))
Eric Laurent81784c32012-11-19 14:55:58 -08001272 )
1273 ) &&
1274 // PCM data
1275 audio_is_linear_pcm(format) &&
1276 // mono or stereo
1277 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
1278 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001279 // hardware sample rate
1280 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001281 // normal mixer has an associated fast mixer
1282 hasFastMixer() &&
1283 // there are sufficient fast track slots available
1284 (mFastTrackAvailMask != 0)
1285 // FIXME test that MixerThread for this fast track has a capable output HAL
1286 // FIXME add a permission test also?
1287 ) {
1288 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1289 if (frameCount == 0) {
1290 frameCount = mFrameCount * kFastTrackMultiplier;
1291 }
1292 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
1293 frameCount, mFrameCount);
1294 } else {
1295 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
1296 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
1297 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
1298 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format,
1299 audio_is_linear_pcm(format),
1300 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
1301 *flags &= ~IAudioFlinger::TRACK_FAST;
1302 // For compatibility with AudioTrack calculation, buffer depth is forced
1303 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1304 // This is probably too conservative, but legacy application code may depend on it.
1305 // If you change this calculation, also review the start threshold which is related.
1306 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1307 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1308 if (minBufCount < 2) {
1309 minBufCount = 2;
1310 }
1311 size_t minFrameCount = mNormalFrameCount * minBufCount;
1312 if (frameCount < minFrameCount) {
1313 frameCount = minFrameCount;
1314 }
1315 }
1316 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001317 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001318
1319 if (mType == DIRECT) {
1320 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1321 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001322 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1323 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001324 sampleRate, format, channelMask, mOutput, mFormat);
1325 lStatus = BAD_VALUE;
1326 goto Exit;
1327 }
1328 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001329 } else if (mType == OFFLOAD) {
1330 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001331 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1332 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001333 sampleRate, format, channelMask, mOutput, mFormat);
1334 lStatus = BAD_VALUE;
1335 goto Exit;
1336 }
Eric Laurent81784c32012-11-19 14:55:58 -08001337 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001338 if ((format & AUDIO_FORMAT_MAIN_MASK) != AUDIO_FORMAT_PCM) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001339 ALOGE("createTrack_l() Bad parameter: format %#x \""
1340 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001341 format, mOutput, mFormat);
1342 lStatus = BAD_VALUE;
1343 goto Exit;
1344 }
Eric Laurent81784c32012-11-19 14:55:58 -08001345 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1346 if (sampleRate > mSampleRate*2) {
1347 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1348 lStatus = BAD_VALUE;
1349 goto Exit;
1350 }
1351 }
1352
1353 lStatus = initCheck();
1354 if (lStatus != NO_ERROR) {
1355 ALOGE("Audio driver not initialized.");
1356 goto Exit;
1357 }
1358
1359 { // scope for mLock
1360 Mutex::Autolock _l(mLock);
1361
1362 // all tracks in same audio session must share the same routing strategy otherwise
1363 // conflicts will happen when tracks are moved from one output to another by audio policy
1364 // manager
1365 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1366 for (size_t i = 0; i < mTracks.size(); ++i) {
1367 sp<Track> t = mTracks[i];
1368 if (t != 0 && !t->isOutputTrack()) {
1369 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1370 if (sessionId == t->sessionId() && strategy != actual) {
1371 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1372 strategy, actual);
1373 lStatus = BAD_VALUE;
1374 goto Exit;
1375 }
1376 }
1377 }
1378
1379 if (!isTimed) {
1380 track = new Track(this, client, streamType, sampleRate, format,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001381 channelMask, frameCount, sharedBuffer, sessionId, uid, *flags);
Eric Laurent81784c32012-11-19 14:55:58 -08001382 } else {
1383 track = TimedTrack::create(this, client, streamType, sampleRate, format,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001384 channelMask, frameCount, sharedBuffer, sessionId, uid);
Eric Laurent81784c32012-11-19 14:55:58 -08001385 }
Glenn Kasten03003332013-08-06 15:40:54 -07001386
1387 // new Track always returns non-NULL,
1388 // but TimedTrack::create() is a factory that could fail by returning NULL
1389 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
1390 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08001391 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001392 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08001393 goto Exit;
1394 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001395
Eric Laurent81784c32012-11-19 14:55:58 -08001396 mTracks.add(track);
1397
1398 sp<EffectChain> chain = getEffectChain_l(sessionId);
1399 if (chain != 0) {
1400 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1401 track->setMainBuffer(chain->inBuffer());
1402 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1403 chain->incTrackCnt();
1404 }
1405
1406 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1407 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1408 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1409 // so ask activity manager to do this on our behalf
1410 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1411 }
1412 }
1413
1414 lStatus = NO_ERROR;
1415
1416Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001417 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001418 return track;
1419}
1420
1421uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1422{
1423 return latency;
1424}
1425
1426uint32_t AudioFlinger::PlaybackThread::latency() const
1427{
1428 Mutex::Autolock _l(mLock);
1429 return latency_l();
1430}
1431uint32_t AudioFlinger::PlaybackThread::latency_l() const
1432{
1433 if (initCheck() == NO_ERROR) {
1434 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
1435 } else {
1436 return 0;
1437 }
1438}
1439
1440void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1441{
1442 Mutex::Autolock _l(mLock);
1443 // Don't apply master volume in SW if our HAL can do it for us.
1444 if (mOutput && mOutput->audioHwDev &&
1445 mOutput->audioHwDev->canSetMasterVolume()) {
1446 mMasterVolume = 1.0;
1447 } else {
1448 mMasterVolume = value;
1449 }
1450}
1451
1452void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1453{
1454 Mutex::Autolock _l(mLock);
1455 // Don't apply master mute in SW if our HAL can do it for us.
1456 if (mOutput && mOutput->audioHwDev &&
1457 mOutput->audioHwDev->canSetMasterMute()) {
1458 mMasterMute = false;
1459 } else {
1460 mMasterMute = muted;
1461 }
1462}
1463
1464void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
1465{
1466 Mutex::Autolock _l(mLock);
1467 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001468 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001469}
1470
1471void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
1472{
1473 Mutex::Autolock _l(mLock);
1474 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001475 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001476}
1477
1478float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
1479{
1480 Mutex::Autolock _l(mLock);
1481 return mStreamTypes[stream].volume;
1482}
1483
1484// addTrack_l() must be called with ThreadBase::mLock held
1485status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1486{
1487 status_t status = ALREADY_EXISTS;
1488
1489 // set retry count for buffer fill
1490 track->mRetryCount = kMaxTrackStartupRetries;
1491 if (mActiveTracks.indexOf(track) < 0) {
1492 // the track is newly added, make sure it fills up all its
1493 // buffers before playing. This is to ensure the client will
1494 // effectively get the latency it requested.
Eric Laurentbfb1b832013-01-07 09:53:42 -08001495 if (!track->isOutputTrack()) {
1496 TrackBase::track_state state = track->mState;
1497 mLock.unlock();
1498 status = AudioSystem::startOutput(mId, track->streamType(), track->sessionId());
1499 mLock.lock();
1500 // abort track was stopped/paused while we released the lock
1501 if (state != track->mState) {
1502 if (status == NO_ERROR) {
1503 mLock.unlock();
1504 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
1505 mLock.lock();
1506 }
1507 return INVALID_OPERATION;
1508 }
1509 // abort if start is rejected by audio policy manager
1510 if (status != NO_ERROR) {
1511 return PERMISSION_DENIED;
1512 }
1513#ifdef ADD_BATTERY_DATA
1514 // to track the speaker usage
1515 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
1516#endif
1517 }
1518
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001519 track->mFillingUpStatus = track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent81784c32012-11-19 14:55:58 -08001520 track->mResetDone = false;
1521 track->mPresentationCompleteFrames = 0;
1522 mActiveTracks.add(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001523 mWakeLockUids.add(track->uid());
1524 mActiveTracksGeneration++;
Eric Laurentfd477972013-10-25 18:10:40 -07001525 mLatestActiveTrack = track;
Eric Laurentd0107bc2013-06-11 14:38:48 -07001526 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1527 if (chain != 0) {
1528 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
1529 track->sessionId());
1530 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08001531 }
1532
1533 status = NO_ERROR;
1534 }
1535
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08001536 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001537 return status;
1538}
1539
Eric Laurentbfb1b832013-01-07 09:53:42 -08001540bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08001541{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001542 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08001543 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001544 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
1545 track->mState = TrackBase::STOPPED;
1546 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08001547 removeTrack_l(track);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001548 } else if (track->isFastTrack() || track->isOffloaded()) {
1549 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08001550 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001551
1552 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08001553}
1554
1555void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1556{
1557 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
1558 mTracks.remove(track);
1559 deleteTrackName_l(track->name());
1560 // redundant as track is about to be destroyed, for dumpsys only
1561 track->mName = -1;
1562 if (track->isFastTrack()) {
1563 int index = track->mFastIndex;
1564 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
1565 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1566 mFastTrackAvailMask |= 1 << index;
1567 // redundant as track is about to be destroyed, for dumpsys only
1568 track->mFastIndex = -1;
1569 }
1570 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1571 if (chain != 0) {
1572 chain->decTrackCnt();
1573 }
1574}
1575
Eric Laurentede6c3b2013-09-19 14:37:46 -07001576void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001577{
1578 // Thread could be blocked waiting for async
1579 // so signal it to handle state changes immediately
1580 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1581 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1582 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001583 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001584}
1585
Eric Laurent81784c32012-11-19 14:55:58 -08001586String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1587{
Eric Laurent81784c32012-11-19 14:55:58 -08001588 Mutex::Autolock _l(mLock);
1589 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07001590 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08001591 }
1592
Glenn Kastend8ea6992013-07-16 14:17:15 -07001593 char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
1594 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08001595 free(s);
1596 return out_s8;
1597}
1598
1599// audioConfigChanged_l() must be called with AudioFlinger::mLock held
1600void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1601 AudioSystem::OutputDescriptor desc;
1602 void *param2 = NULL;
1603
1604 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event,
1605 param);
1606
1607 switch (event) {
1608 case AudioSystem::OUTPUT_OPENED:
1609 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07001610 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08001611 desc.samplingRate = mSampleRate;
1612 desc.format = mFormat;
1613 desc.frameCount = mNormalFrameCount; // FIXME see
1614 // AudioFlinger::frameCount(audio_io_handle_t)
1615 desc.latency = latency();
1616 param2 = &desc;
1617 break;
1618
1619 case AudioSystem::STREAM_CONFIG_CHANGED:
1620 param2 = &param;
1621 case AudioSystem::OUTPUT_CLOSED:
1622 default:
1623 break;
1624 }
1625 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1626}
1627
Eric Laurentbfb1b832013-01-07 09:53:42 -08001628void AudioFlinger::PlaybackThread::writeCallback()
1629{
1630 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001631 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001632}
1633
1634void AudioFlinger::PlaybackThread::drainCallback()
1635{
1636 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001637 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001638}
1639
Eric Laurent3b4529e2013-09-05 18:09:19 -07001640void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001641{
1642 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001643 // reject out of sequence requests
1644 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
1645 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001646 mWaitWorkCV.signal();
1647 }
1648}
1649
Eric Laurent3b4529e2013-09-05 18:09:19 -07001650void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001651{
1652 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001653 // reject out of sequence requests
1654 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
1655 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001656 mWaitWorkCV.signal();
1657 }
1658}
1659
1660// static
1661int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
Glenn Kasten0f11b512014-01-31 16:18:54 -08001662 void *param __unused,
Eric Laurentbfb1b832013-01-07 09:53:42 -08001663 void *cookie)
1664{
1665 AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
1666 ALOGV("asyncCallback() event %d", event);
1667 switch (event) {
1668 case STREAM_CBK_EVENT_WRITE_READY:
1669 me->writeCallback();
1670 break;
1671 case STREAM_CBK_EVENT_DRAIN_READY:
1672 me->drainCallback();
1673 break;
1674 default:
1675 ALOGW("asyncCallback() unknown event %d", event);
1676 break;
1677 }
1678 return 0;
1679}
1680
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001681void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001682{
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001683 // unfortunately we have no way of recovering from errors here, hence the LOG_FATAL
Eric Laurent81784c32012-11-19 14:55:58 -08001684 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
1685 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001686 if (!audio_is_output_channel(mChannelMask)) {
1687 LOG_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
1688 }
1689 if ((mType == MIXER || mType == DUPLICATING) && mChannelMask != AUDIO_CHANNEL_OUT_STEREO) {
1690 LOG_FATAL("HAL channel mask %#x not supported for mixed output; "
1691 "must be AUDIO_CHANNEL_OUT_STEREO", mChannelMask);
1692 }
Glenn Kastenf6ed4232013-07-16 11:16:27 -07001693 mChannelCount = popcount(mChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08001694 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001695 if (!audio_is_valid_format(mFormat)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001696 LOG_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001697 }
1698 if ((mType == MIXER || mType == DUPLICATING) && mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001699 LOG_FATAL("HAL format %#x not supported for mixed output; must be AUDIO_FORMAT_PCM_16_BIT",
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001700 mFormat);
1701 }
Eric Laurent81784c32012-11-19 14:55:58 -08001702 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Glenn Kasten70949c42013-08-06 07:40:12 -07001703 mBufferSize = mOutput->stream->common.get_buffer_size(&mOutput->stream->common);
1704 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08001705 if (mFrameCount & 15) {
1706 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
1707 mFrameCount);
1708 }
1709
Eric Laurentbfb1b832013-01-07 09:53:42 -08001710 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
1711 (mOutput->stream->set_callback != NULL)) {
1712 if (mOutput->stream->set_callback(mOutput->stream,
1713 AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
1714 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07001715 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001716 }
1717 }
1718
Eric Laurent81784c32012-11-19 14:55:58 -08001719 // Calculate size of normal mix buffer relative to the HAL output buffer size
1720 double multiplier = 1.0;
1721 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
1722 kUseFastMixer == FastMixer_Dynamic)) {
1723 size_t minNormalFrameCount = (kMinNormalMixBufferSizeMs * mSampleRate) / 1000;
1724 size_t maxNormalFrameCount = (kMaxNormalMixBufferSizeMs * mSampleRate) / 1000;
1725 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
1726 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
1727 maxNormalFrameCount = maxNormalFrameCount & ~15;
1728 if (maxNormalFrameCount < minNormalFrameCount) {
1729 maxNormalFrameCount = minNormalFrameCount;
1730 }
1731 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
1732 if (multiplier <= 1.0) {
1733 multiplier = 1.0;
1734 } else if (multiplier <= 2.0) {
1735 if (2 * mFrameCount <= maxNormalFrameCount) {
1736 multiplier = 2.0;
1737 } else {
1738 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
1739 }
1740 } else {
1741 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
1742 // SRC (it would be unusual for the normal mix buffer size to not be a multiple of fast
1743 // track, but we sometimes have to do this to satisfy the maximum frame count
1744 // constraint)
1745 // FIXME this rounding up should not be done if no HAL SRC
1746 uint32_t truncMult = (uint32_t) multiplier;
1747 if ((truncMult & 1)) {
1748 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
1749 ++truncMult;
1750 }
1751 }
1752 multiplier = (double) truncMult;
1753 }
1754 }
1755 mNormalFrameCount = multiplier * mFrameCount;
1756 // round up to nearest 16 frames to satisfy AudioMixer
1757 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
1758 ALOGI("HAL output buffer size %u frames, normal mix buffer size %u frames", mFrameCount,
1759 mNormalFrameCount);
1760
Glenn Kastenc1fac192013-08-06 07:41:36 -07001761 delete[] mMixBuffer;
1762 size_t normalBufferSize = mNormalFrameCount * mFrameSize;
1763 // For historical reasons mMixBuffer is int16_t[], but mFrameSize can be odd (such as 1)
1764 mMixBuffer = new int16_t[(normalBufferSize + 1) >> 1];
1765 memset(mMixBuffer, 0, normalBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08001766
1767 // force reconfiguration of effect chains and engines to take new buffer size and audio
1768 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001769 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08001770 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1771 // matter.
1772 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1773 Vector< sp<EffectChain> > effectChains = mEffectChains;
1774 for (size_t i = 0; i < effectChains.size(); i ++) {
1775 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
1776 }
1777}
1778
1779
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001780status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08001781{
1782 if (halFrames == NULL || dspFrames == NULL) {
1783 return BAD_VALUE;
1784 }
1785 Mutex::Autolock _l(mLock);
1786 if (initCheck() != NO_ERROR) {
1787 return INVALID_OPERATION;
1788 }
1789 size_t framesWritten = mBytesWritten / mFrameSize;
1790 *halFrames = framesWritten;
1791
1792 if (isSuspended()) {
1793 // return an estimation of rendered frames when the output is suspended
1794 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
1795 *dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0;
1796 return NO_ERROR;
1797 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001798 status_t status;
1799 uint32_t frames;
1800 status = mOutput->stream->get_render_position(mOutput->stream, &frames);
1801 *dspFrames = (size_t)frames;
1802 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08001803 }
1804}
1805
1806uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
1807{
1808 Mutex::Autolock _l(mLock);
1809 uint32_t result = 0;
1810 if (getEffectChain_l(sessionId) != 0) {
1811 result = EFFECT_SESSION;
1812 }
1813
1814 for (size_t i = 0; i < mTracks.size(); ++i) {
1815 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08001816 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001817 result |= TRACK_SESSION;
1818 break;
1819 }
1820 }
1821
1822 return result;
1823}
1824
1825uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1826{
1827 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
1828 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
1829 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1830 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
1831 }
1832 for (size_t i = 0; i < mTracks.size(); i++) {
1833 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08001834 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001835 return AudioSystem::getStrategyForStream(track->streamType());
1836 }
1837 }
1838 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
1839}
1840
1841
1842AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
1843{
1844 Mutex::Autolock _l(mLock);
1845 return mOutput;
1846}
1847
1848AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1849{
1850 Mutex::Autolock _l(mLock);
1851 AudioStreamOut *output = mOutput;
1852 mOutput = NULL;
1853 // FIXME FastMixer might also have a raw ptr to mOutputSink;
1854 // must push a NULL and wait for ack
1855 mOutputSink.clear();
1856 mPipeSink.clear();
1857 mNormalSink.clear();
1858 return output;
1859}
1860
1861// this method must always be called either with ThreadBase mLock held or inside the thread loop
1862audio_stream_t* AudioFlinger::PlaybackThread::stream() const
1863{
1864 if (mOutput == NULL) {
1865 return NULL;
1866 }
1867 return &mOutput->stream->common;
1868}
1869
1870uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
1871{
1872 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
1873}
1874
1875status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
1876{
1877 if (!isValidSyncEvent(event)) {
1878 return BAD_VALUE;
1879 }
1880
1881 Mutex::Autolock _l(mLock);
1882
1883 for (size_t i = 0; i < mTracks.size(); ++i) {
1884 sp<Track> track = mTracks[i];
1885 if (event->triggerSession() == track->sessionId()) {
1886 (void) track->setSyncEvent(event);
1887 return NO_ERROR;
1888 }
1889 }
1890
1891 return NAME_NOT_FOUND;
1892}
1893
1894bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
1895{
1896 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
1897}
1898
1899void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
1900 const Vector< sp<Track> >& tracksToRemove)
1901{
1902 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07001903 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001904 for (size_t i = 0 ; i < count ; i++) {
1905 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001906 if (!track->isOutputTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001907 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001908#ifdef ADD_BATTERY_DATA
1909 // to track the speaker usage
1910 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
1911#endif
1912 if (track->isTerminated()) {
1913 AudioSystem::releaseOutput(mId);
1914 }
Eric Laurent81784c32012-11-19 14:55:58 -08001915 }
1916 }
1917 }
Eric Laurent81784c32012-11-19 14:55:58 -08001918}
1919
1920void AudioFlinger::PlaybackThread::checkSilentMode_l()
1921{
1922 if (!mMasterMute) {
1923 char value[PROPERTY_VALUE_MAX];
1924 if (property_get("ro.audio.silent", value, "0") > 0) {
1925 char *endptr;
1926 unsigned long ul = strtoul(value, &endptr, 0);
1927 if (*endptr == '\0' && ul != 0) {
1928 ALOGD("Silence is golden");
1929 // The setprop command will not allow a property to be changed after
1930 // the first time it is set, so we don't have to worry about un-muting.
1931 setMasterMute_l(true);
1932 }
1933 }
1934 }
1935}
1936
1937// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08001938ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08001939{
1940 // FIXME rewrite to reduce number of system calls
1941 mLastWriteTime = systemTime();
1942 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001943 ssize_t bytesWritten;
Eric Laurent81784c32012-11-19 14:55:58 -08001944
1945 // If an NBAIO sink is present, use it to write the normal mixer's submix
1946 if (mNormalSink != 0) {
1947#define mBitShift 2 // FIXME
Eric Laurentbfb1b832013-01-07 09:53:42 -08001948 size_t count = mBytesRemaining >> mBitShift;
1949 size_t offset = (mCurrentWriteLength - mBytesRemaining) >> 1;
Simon Wilson2d590962012-11-29 15:18:50 -08001950 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08001951 // update the setpoint when AudioFlinger::mScreenState changes
1952 uint32_t screenState = AudioFlinger::mScreenState;
1953 if (screenState != mScreenState) {
1954 mScreenState = screenState;
1955 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
1956 if (pipe != NULL) {
1957 pipe->setAvgFrames((mScreenState & 1) ?
1958 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
1959 }
1960 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001961 ssize_t framesWritten = mNormalSink->write(mMixBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08001962 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08001963 if (framesWritten > 0) {
1964 bytesWritten = framesWritten << mBitShift;
1965 } else {
1966 bytesWritten = framesWritten;
1967 }
Glenn Kasten767094d2013-08-23 13:51:43 -07001968 status_t status = mNormalSink->getTimestamp(mLatchD.mTimestamp);
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001969 if (status == NO_ERROR) {
1970 size_t totalFramesWritten = mNormalSink->framesWritten();
1971 if (totalFramesWritten >= mLatchD.mTimestamp.mPosition) {
1972 mLatchD.mUnpresentedFrames = totalFramesWritten - mLatchD.mTimestamp.mPosition;
1973 mLatchDValid = true;
1974 }
1975 }
Eric Laurent81784c32012-11-19 14:55:58 -08001976 // otherwise use the HAL / AudioStreamOut directly
1977 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001978 // Direct output and offload threads
Eric Laurent04733db2013-11-22 09:29:56 -08001979 size_t offset = (mCurrentWriteLength - mBytesRemaining);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001980 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07001981 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
1982 mWriteAckSequence += 2;
1983 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001984 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001985 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001986 }
Glenn Kasten767094d2013-08-23 13:51:43 -07001987 // FIXME We should have an implementation of timestamps for direct output threads.
1988 // They are used e.g for multichannel PCM playback over HDMI.
Eric Laurentbfb1b832013-01-07 09:53:42 -08001989 bytesWritten = mOutput->stream->write(mOutput->stream,
Eric Laurent04733db2013-11-22 09:29:56 -08001990 (char *)mMixBuffer + offset, mBytesRemaining);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001991 if (mUseAsyncWrite &&
1992 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
1993 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07001994 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001995 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001996 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001997 }
Eric Laurent81784c32012-11-19 14:55:58 -08001998 }
1999
Eric Laurent81784c32012-11-19 14:55:58 -08002000 mNumWrites++;
2001 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002002 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002003 return bytesWritten;
2004}
2005
2006void AudioFlinger::PlaybackThread::threadLoop_drain()
2007{
2008 if (mOutput->stream->drain) {
2009 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2010 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002011 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2012 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002013 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002014 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002015 }
2016 mOutput->stream->drain(mOutput->stream,
2017 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
2018 : AUDIO_DRAIN_ALL);
2019 }
2020}
2021
2022void AudioFlinger::PlaybackThread::threadLoop_exit()
2023{
2024 // Default implementation has nothing to do
Eric Laurent81784c32012-11-19 14:55:58 -08002025}
2026
2027/*
2028The derived values that are cached:
2029 - mixBufferSize from frame count * frame size
2030 - activeSleepTime from activeSleepTimeUs()
2031 - idleSleepTime from idleSleepTimeUs()
2032 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
2033 - maxPeriod from frame count and sample rate (MIXER only)
2034
2035The parameters that affect these derived values are:
2036 - frame count
2037 - frame size
2038 - sample rate
2039 - device type: A2DP or not
2040 - device latency
2041 - format: PCM or not
2042 - active sleep time
2043 - idle sleep time
2044*/
2045
2046void AudioFlinger::PlaybackThread::cacheParameters_l()
2047{
2048 mixBufferSize = mNormalFrameCount * mFrameSize;
2049 activeSleepTime = activeSleepTimeUs();
2050 idleSleepTime = idleSleepTimeUs();
2051}
2052
2053void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2054{
Glenn Kasten7c027242012-12-26 14:43:16 -08002055 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurent81784c32012-11-19 14:55:58 -08002056 this, streamType, mTracks.size());
2057 Mutex::Autolock _l(mLock);
2058
2059 size_t size = mTracks.size();
2060 for (size_t i = 0; i < size; i++) {
2061 sp<Track> t = mTracks[i];
2062 if (t->streamType() == streamType) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002063 t->invalidate();
Eric Laurent81784c32012-11-19 14:55:58 -08002064 }
2065 }
2066}
2067
2068status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2069{
2070 int session = chain->sessionId();
2071 int16_t *buffer = mMixBuffer;
2072 bool ownsBuffer = false;
2073
2074 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
2075 if (session > 0) {
2076 // Only one effect chain can be present in direct output thread and it uses
2077 // the mix buffer as input
2078 if (mType != DIRECT) {
2079 size_t numSamples = mNormalFrameCount * mChannelCount;
2080 buffer = new int16_t[numSamples];
2081 memset(buffer, 0, numSamples * sizeof(int16_t));
2082 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2083 ownsBuffer = true;
2084 }
2085
2086 // Attach all tracks with same session ID to this chain.
2087 for (size_t i = 0; i < mTracks.size(); ++i) {
2088 sp<Track> track = mTracks[i];
2089 if (session == track->sessionId()) {
2090 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2091 buffer);
2092 track->setMainBuffer(buffer);
2093 chain->incTrackCnt();
2094 }
2095 }
2096
2097 // indicate all active tracks in the chain
2098 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2099 sp<Track> track = mActiveTracks[i].promote();
2100 if (track == 0) {
2101 continue;
2102 }
2103 if (session == track->sessionId()) {
2104 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2105 chain->incActiveTrackCnt();
2106 }
2107 }
2108 }
2109
2110 chain->setInBuffer(buffer, ownsBuffer);
2111 chain->setOutBuffer(mMixBuffer);
2112 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
2113 // chains list in order to be processed last as it contains output stage effects
2114 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2115 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
2116 // after track specific effects and before output stage
2117 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
2118 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
2119 // Effect chain for other sessions are inserted at beginning of effect
2120 // chains list to be processed before output mix effects. Relative order between other
2121 // sessions is not important
2122 size_t size = mEffectChains.size();
2123 size_t i = 0;
2124 for (i = 0; i < size; i++) {
2125 if (mEffectChains[i]->sessionId() < session) {
2126 break;
2127 }
2128 }
2129 mEffectChains.insertAt(chain, i);
2130 checkSuspendOnAddEffectChain_l(chain);
2131
2132 return NO_ERROR;
2133}
2134
2135size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2136{
2137 int session = chain->sessionId();
2138
2139 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2140
2141 for (size_t i = 0; i < mEffectChains.size(); i++) {
2142 if (chain == mEffectChains[i]) {
2143 mEffectChains.removeAt(i);
2144 // detach all active tracks from the chain
2145 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2146 sp<Track> track = mActiveTracks[i].promote();
2147 if (track == 0) {
2148 continue;
2149 }
2150 if (session == track->sessionId()) {
2151 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2152 chain.get(), session);
2153 chain->decActiveTrackCnt();
2154 }
2155 }
2156
2157 // detach all tracks with same session ID from this chain
2158 for (size_t i = 0; i < mTracks.size(); ++i) {
2159 sp<Track> track = mTracks[i];
2160 if (session == track->sessionId()) {
2161 track->setMainBuffer(mMixBuffer);
2162 chain->decTrackCnt();
2163 }
2164 }
2165 break;
2166 }
2167 }
2168 return mEffectChains.size();
2169}
2170
2171status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2172 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2173{
2174 Mutex::Autolock _l(mLock);
2175 return attachAuxEffect_l(track, EffectId);
2176}
2177
2178status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2179 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2180{
2181 status_t status = NO_ERROR;
2182
2183 if (EffectId == 0) {
2184 track->setAuxBuffer(0, NULL);
2185 } else {
2186 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2187 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2188 if (effect != 0) {
2189 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2190 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2191 } else {
2192 status = INVALID_OPERATION;
2193 }
2194 } else {
2195 status = BAD_VALUE;
2196 }
2197 }
2198 return status;
2199}
2200
2201void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2202{
2203 for (size_t i = 0; i < mTracks.size(); ++i) {
2204 sp<Track> track = mTracks[i];
2205 if (track->auxEffectId() == effectId) {
2206 attachAuxEffect_l(track, 0);
2207 }
2208 }
2209}
2210
2211bool AudioFlinger::PlaybackThread::threadLoop()
2212{
2213 Vector< sp<Track> > tracksToRemove;
2214
2215 standbyTime = systemTime();
2216
2217 // MIXER
2218 nsecs_t lastWarning = 0;
2219
2220 // DUPLICATING
2221 // FIXME could this be made local to while loop?
2222 writeFrames = 0;
2223
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002224 int lastGeneration = 0;
2225
Eric Laurent81784c32012-11-19 14:55:58 -08002226 cacheParameters_l();
2227 sleepTime = idleSleepTime;
2228
2229 if (mType == MIXER) {
2230 sleepTimeShift = 0;
2231 }
2232
2233 CpuStats cpuStats;
2234 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2235
2236 acquireWakeLock();
2237
Glenn Kasten9e58b552013-01-18 15:09:48 -08002238 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2239 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2240 // and then that string will be logged at the next convenient opportunity.
2241 const char *logString = NULL;
2242
Eric Laurent664539d2013-09-23 18:24:31 -07002243 checkSilentMode_l();
2244
Eric Laurent81784c32012-11-19 14:55:58 -08002245 while (!exitPending())
2246 {
2247 cpuStats.sample(myName);
2248
2249 Vector< sp<EffectChain> > effectChains;
2250
2251 processConfigEvents();
2252
2253 { // scope for mLock
2254
2255 Mutex::Autolock _l(mLock);
2256
Glenn Kasten9e58b552013-01-18 15:09:48 -08002257 if (logString != NULL) {
2258 mNBLogWriter->logTimestamp();
2259 mNBLogWriter->log(logString);
2260 logString = NULL;
2261 }
2262
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002263 if (mLatchDValid) {
2264 mLatchQ = mLatchD;
2265 mLatchDValid = false;
2266 mLatchQValid = true;
2267 }
2268
Eric Laurent81784c32012-11-19 14:55:58 -08002269 if (checkForNewParameters_l()) {
2270 cacheParameters_l();
2271 }
2272
2273 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002274 if (mSignalPending) {
2275 // A signal was raised while we were unlocked
2276 mSignalPending = false;
2277 } else if (waitingAsyncCallback_l()) {
2278 if (exitPending()) {
2279 break;
2280 }
2281 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002282 mWakeLockUids.clear();
2283 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002284 ALOGV("wait async completion");
2285 mWaitWorkCV.wait(mLock);
2286 ALOGV("async completion/wake");
2287 acquireWakeLock_l();
Eric Laurent972a1732013-09-04 09:42:59 -07002288 standbyTime = systemTime() + standbyDelay;
2289 sleepTime = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002290
2291 continue;
2292 }
2293 if ((!mActiveTracks.size() && systemTime() > standbyTime) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08002294 isSuspended()) {
2295 // put audio hardware into standby after short delay
2296 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002297
2298 threadLoop_standby();
2299
2300 mStandby = true;
2301 }
2302
2303 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2304 // we're about to wait, flush the binder command buffer
2305 IPCThreadState::self()->flushCommands();
2306
2307 clearOutputTracks();
2308
2309 if (exitPending()) {
2310 break;
2311 }
2312
2313 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002314 mWakeLockUids.clear();
2315 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002316 // wait until we have something to do...
2317 ALOGV("%s going to sleep", myName.string());
2318 mWaitWorkCV.wait(mLock);
2319 ALOGV("%s waking up", myName.string());
2320 acquireWakeLock_l();
2321
2322 mMixerStatus = MIXER_IDLE;
2323 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2324 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002325 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002326 checkSilentMode_l();
2327
2328 standbyTime = systemTime() + standbyDelay;
2329 sleepTime = idleSleepTime;
2330 if (mType == MIXER) {
2331 sleepTimeShift = 0;
2332 }
2333
2334 continue;
2335 }
2336 }
Eric Laurent81784c32012-11-19 14:55:58 -08002337 // mMixerStatusIgnoringFastTracks is also updated internally
2338 mMixerStatus = prepareTracks_l(&tracksToRemove);
2339
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002340 // compare with previously applied list
2341 if (lastGeneration != mActiveTracksGeneration) {
2342 // update wakelock
2343 updateWakeLockUids_l(mWakeLockUids);
2344 lastGeneration = mActiveTracksGeneration;
2345 }
2346
Eric Laurent81784c32012-11-19 14:55:58 -08002347 // prevent any changes in effect chain list and in each effect chain
2348 // during mixing and effect process as the audio buffers could be deleted
2349 // or modified if an effect is created or deleted
2350 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002351 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08002352
Eric Laurentbfb1b832013-01-07 09:53:42 -08002353 if (mBytesRemaining == 0) {
2354 mCurrentWriteLength = 0;
2355 if (mMixerStatus == MIXER_TRACKS_READY) {
2356 // threadLoop_mix() sets mCurrentWriteLength
2357 threadLoop_mix();
2358 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
2359 && (mMixerStatus != MIXER_DRAIN_ALL)) {
2360 // threadLoop_sleepTime sets sleepTime to 0 if data
2361 // must be written to HAL
2362 threadLoop_sleepTime();
2363 if (sleepTime == 0) {
2364 mCurrentWriteLength = mixBufferSize;
2365 }
2366 }
2367 mBytesRemaining = mCurrentWriteLength;
2368 if (isSuspended()) {
2369 sleepTime = suspendSleepTimeUs();
2370 // simulate write to HAL when suspended
2371 mBytesWritten += mixBufferSize;
2372 mBytesRemaining = 0;
2373 }
Eric Laurent81784c32012-11-19 14:55:58 -08002374
Eric Laurentbfb1b832013-01-07 09:53:42 -08002375 // only process effects if we're going to write
Eric Laurent59fe0102013-09-27 18:48:26 -07002376 if (sleepTime == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002377 for (size_t i = 0; i < effectChains.size(); i ++) {
2378 effectChains[i]->process_l();
2379 }
Eric Laurent81784c32012-11-19 14:55:58 -08002380 }
2381 }
Eric Laurent59fe0102013-09-27 18:48:26 -07002382 // Process effect chains for offloaded thread even if no audio
2383 // was read from audio track: process only updates effect state
2384 // and thus does have to be synchronized with audio writes but may have
2385 // to be called while waiting for async write callback
2386 if (mType == OFFLOAD) {
2387 for (size_t i = 0; i < effectChains.size(); i ++) {
2388 effectChains[i]->process_l();
2389 }
2390 }
Eric Laurent81784c32012-11-19 14:55:58 -08002391
2392 // enable changes in effect chain
2393 unlockEffectChains(effectChains);
2394
Eric Laurentbfb1b832013-01-07 09:53:42 -08002395 if (!waitingAsyncCallback()) {
2396 // sleepTime == 0 means we must write to audio hardware
2397 if (sleepTime == 0) {
2398 if (mBytesRemaining) {
2399 ssize_t ret = threadLoop_write();
2400 if (ret < 0) {
2401 mBytesRemaining = 0;
2402 } else {
2403 mBytesWritten += ret;
2404 mBytesRemaining -= ret;
2405 }
2406 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
2407 (mMixerStatus == MIXER_DRAIN_ALL)) {
2408 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08002409 }
Glenn Kasten4944acb2013-08-19 08:39:20 -07002410 if (mType == MIXER) {
2411 // write blocked detection
2412 nsecs_t now = systemTime();
2413 nsecs_t delta = now - mLastWriteTime;
2414 if (!mStandby && delta > maxPeriod) {
2415 mNumDelayedWrites++;
2416 if ((now - lastWarning) > kWarningThrottleNs) {
2417 ATRACE_NAME("underrun");
2418 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2419 ns2ms(delta), mNumDelayedWrites, this);
2420 lastWarning = now;
2421 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002422 }
2423 }
Eric Laurent81784c32012-11-19 14:55:58 -08002424
Eric Laurentbfb1b832013-01-07 09:53:42 -08002425 } else {
2426 usleep(sleepTime);
2427 }
Eric Laurent81784c32012-11-19 14:55:58 -08002428 }
2429
2430 // Finally let go of removed track(s), without the lock held
2431 // since we can't guarantee the destructors won't acquire that
2432 // same lock. This will also mutate and push a new fast mixer state.
2433 threadLoop_removeTracks(tracksToRemove);
2434 tracksToRemove.clear();
2435
2436 // FIXME I don't understand the need for this here;
2437 // it was in the original code but maybe the
2438 // assignment in saveOutputTracks() makes this unnecessary?
2439 clearOutputTracks();
2440
2441 // Effect chains will be actually deleted here if they were removed from
2442 // mEffectChains list during mixing or effects processing
2443 effectChains.clear();
2444
2445 // FIXME Note that the above .clear() is no longer necessary since effectChains
2446 // is now local to this block, but will keep it for now (at least until merge done).
2447 }
2448
Eric Laurentbfb1b832013-01-07 09:53:42 -08002449 threadLoop_exit();
2450
Eric Laurent81784c32012-11-19 14:55:58 -08002451 // for DuplicatingThread, standby mode is handled by the outputTracks, otherwise ...
Eric Laurentbfb1b832013-01-07 09:53:42 -08002452 if (mType == MIXER || mType == DIRECT || mType == OFFLOAD) {
Eric Laurent81784c32012-11-19 14:55:58 -08002453 // put output stream into standby mode
2454 if (!mStandby) {
2455 mOutput->stream->common.standby(&mOutput->stream->common);
2456 }
2457 }
2458
2459 releaseWakeLock();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002460 mWakeLockUids.clear();
2461 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002462
2463 ALOGV("Thread %p type %d exiting", this, mType);
2464 return false;
2465}
2466
Eric Laurentbfb1b832013-01-07 09:53:42 -08002467// removeTracks_l() must be called with ThreadBase::mLock held
2468void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
2469{
2470 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002471 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002472 for (size_t i=0 ; i<count ; i++) {
2473 const sp<Track>& track = tracksToRemove.itemAt(i);
2474 mActiveTracks.remove(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002475 mWakeLockUids.remove(track->uid());
2476 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002477 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
2478 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2479 if (chain != 0) {
2480 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
2481 track->sessionId());
2482 chain->decActiveTrackCnt();
2483 }
2484 if (track->isTerminated()) {
2485 removeTrack_l(track);
2486 }
2487 }
2488 }
2489
2490}
Eric Laurent81784c32012-11-19 14:55:58 -08002491
Eric Laurentaccc1472013-09-20 09:36:34 -07002492status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
2493{
2494 if (mNormalSink != 0) {
2495 return mNormalSink->getTimestamp(timestamp);
2496 }
2497 if (mType == OFFLOAD && mOutput->stream->get_presentation_position) {
2498 uint64_t position64;
2499 int ret = mOutput->stream->get_presentation_position(
2500 mOutput->stream, &position64, &timestamp.mTime);
2501 if (ret == 0) {
2502 timestamp.mPosition = (uint32_t)position64;
2503 return NO_ERROR;
2504 }
2505 }
2506 return INVALID_OPERATION;
2507}
Eric Laurent81784c32012-11-19 14:55:58 -08002508// ----------------------------------------------------------------------------
2509
2510AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
2511 audio_io_handle_t id, audio_devices_t device, type_t type)
2512 : PlaybackThread(audioFlinger, output, id, device, type),
2513 // mAudioMixer below
2514 // mFastMixer below
2515 mFastMixerFutex(0)
2516 // mOutputSink below
2517 // mPipeSink below
2518 // mNormalSink below
2519{
2520 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07002521 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, "
Eric Laurent81784c32012-11-19 14:55:58 -08002522 "mFrameCount=%d, mNormalFrameCount=%d",
2523 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2524 mNormalFrameCount);
2525 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2526
2527 // FIXME - Current mixer implementation only supports stereo output
2528 if (mChannelCount != FCC_2) {
2529 ALOGE("Invalid audio hardware channel count %d", mChannelCount);
2530 }
2531
2532 // create an NBAIO sink for the HAL output stream, and negotiate
2533 mOutputSink = new AudioStreamOutSink(output->stream);
2534 size_t numCounterOffers = 0;
2535 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount)};
2536 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2537 ALOG_ASSERT(index == 0);
2538
2539 // initialize fast mixer depending on configuration
2540 bool initFastMixer;
2541 switch (kUseFastMixer) {
2542 case FastMixer_Never:
2543 initFastMixer = false;
2544 break;
2545 case FastMixer_Always:
2546 initFastMixer = true;
2547 break;
2548 case FastMixer_Static:
2549 case FastMixer_Dynamic:
2550 initFastMixer = mFrameCount < mNormalFrameCount;
2551 break;
2552 }
2553 if (initFastMixer) {
2554
2555 // create a MonoPipe to connect our submix to FastMixer
2556 NBAIO_Format format = mOutputSink->format();
2557 // This pipe depth compensates for scheduling latency of the normal mixer thread.
2558 // When it wakes up after a maximum latency, it runs a few cycles quickly before
2559 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
2560 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
2561 const NBAIO_Format offers[1] = {format};
2562 size_t numCounterOffers = 0;
2563 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2564 ALOG_ASSERT(index == 0);
2565 monoPipe->setAvgFrames((mScreenState & 1) ?
2566 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2567 mPipeSink = monoPipe;
2568
Glenn Kasten46909e72013-02-26 09:20:22 -08002569#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08002570 if (mTeeSinkOutputEnabled) {
2571 // create a Pipe to archive a copy of FastMixer's output for dumpsys
2572 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, format);
2573 numCounterOffers = 0;
2574 index = teeSink->negotiate(offers, 1, NULL, numCounterOffers);
2575 ALOG_ASSERT(index == 0);
2576 mTeeSink = teeSink;
2577 PipeReader *teeSource = new PipeReader(*teeSink);
2578 numCounterOffers = 0;
2579 index = teeSource->negotiate(offers, 1, NULL, numCounterOffers);
2580 ALOG_ASSERT(index == 0);
2581 mTeeSource = teeSource;
2582 }
Glenn Kasten46909e72013-02-26 09:20:22 -08002583#endif
Eric Laurent81784c32012-11-19 14:55:58 -08002584
2585 // create fast mixer and configure it initially with just one fast track for our submix
2586 mFastMixer = new FastMixer();
2587 FastMixerStateQueue *sq = mFastMixer->sq();
2588#ifdef STATE_QUEUE_DUMP
2589 sq->setObserverDump(&mStateQueueObserverDump);
2590 sq->setMutatorDump(&mStateQueueMutatorDump);
2591#endif
2592 FastMixerState *state = sq->begin();
2593 FastTrack *fastTrack = &state->mFastTracks[0];
2594 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2595 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2596 fastTrack->mVolumeProvider = NULL;
2597 fastTrack->mGeneration++;
2598 state->mFastTracksGen++;
2599 state->mTrackMask = 1;
2600 // fast mixer will use the HAL output sink
2601 state->mOutputSink = mOutputSink.get();
2602 state->mOutputSinkGen++;
2603 state->mFrameCount = mFrameCount;
2604 state->mCommand = FastMixerState::COLD_IDLE;
2605 // already done in constructor initialization list
2606 //mFastMixerFutex = 0;
2607 state->mColdFutexAddr = &mFastMixerFutex;
2608 state->mColdGen++;
2609 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08002610#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08002611 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08002612#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08002613 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
2614 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08002615 sq->end();
2616 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2617
2618 // start the fast mixer
2619 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
2620 pid_t tid = mFastMixer->getTid();
2621 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2622 if (err != 0) {
2623 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2624 kPriorityFastMixer, getpid_cached, tid, err);
2625 }
2626
2627#ifdef AUDIO_WATCHDOG
2628 // create and start the watchdog
2629 mAudioWatchdog = new AudioWatchdog();
2630 mAudioWatchdog->setDump(&mAudioWatchdogDump);
2631 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
2632 tid = mAudioWatchdog->getTid();
2633 err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2634 if (err != 0) {
2635 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2636 kPriorityFastMixer, getpid_cached, tid, err);
2637 }
2638#endif
2639
2640 } else {
2641 mFastMixer = NULL;
2642 }
2643
2644 switch (kUseFastMixer) {
2645 case FastMixer_Never:
2646 case FastMixer_Dynamic:
2647 mNormalSink = mOutputSink;
2648 break;
2649 case FastMixer_Always:
2650 mNormalSink = mPipeSink;
2651 break;
2652 case FastMixer_Static:
2653 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2654 break;
2655 }
2656}
2657
2658AudioFlinger::MixerThread::~MixerThread()
2659{
2660 if (mFastMixer != NULL) {
2661 FastMixerStateQueue *sq = mFastMixer->sq();
2662 FastMixerState *state = sq->begin();
2663 if (state->mCommand == FastMixerState::COLD_IDLE) {
2664 int32_t old = android_atomic_inc(&mFastMixerFutex);
2665 if (old == -1) {
2666 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2667 }
2668 }
2669 state->mCommand = FastMixerState::EXIT;
2670 sq->end();
2671 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2672 mFastMixer->join();
2673 // Though the fast mixer thread has exited, it's state queue is still valid.
2674 // We'll use that extract the final state which contains one remaining fast track
2675 // corresponding to our sub-mix.
2676 state = sq->begin();
2677 ALOG_ASSERT(state->mTrackMask == 1);
2678 FastTrack *fastTrack = &state->mFastTracks[0];
2679 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2680 delete fastTrack->mBufferProvider;
2681 sq->end(false /*didModify*/);
2682 delete mFastMixer;
2683#ifdef AUDIO_WATCHDOG
2684 if (mAudioWatchdog != 0) {
2685 mAudioWatchdog->requestExit();
2686 mAudioWatchdog->requestExitAndWait();
2687 mAudioWatchdog.clear();
2688 }
2689#endif
2690 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08002691 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08002692 delete mAudioMixer;
2693}
2694
2695
2696uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
2697{
2698 if (mFastMixer != NULL) {
2699 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2700 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
2701 }
2702 return latency;
2703}
2704
2705
2706void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2707{
2708 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
2709}
2710
Eric Laurentbfb1b832013-01-07 09:53:42 -08002711ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002712{
2713 // FIXME we should only do one push per cycle; confirm this is true
2714 // Start the fast mixer if it's not already running
2715 if (mFastMixer != NULL) {
2716 FastMixerStateQueue *sq = mFastMixer->sq();
2717 FastMixerState *state = sq->begin();
2718 if (state->mCommand != FastMixerState::MIX_WRITE &&
2719 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
2720 if (state->mCommand == FastMixerState::COLD_IDLE) {
2721 int32_t old = android_atomic_inc(&mFastMixerFutex);
2722 if (old == -1) {
2723 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2724 }
2725#ifdef AUDIO_WATCHDOG
2726 if (mAudioWatchdog != 0) {
2727 mAudioWatchdog->resume();
2728 }
2729#endif
2730 }
2731 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002732 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
2733 FastMixerDumpState::kSamplingNforLowRamDevice : FastMixerDumpState::kSamplingN);
Eric Laurent81784c32012-11-19 14:55:58 -08002734 sq->end();
2735 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2736 if (kUseFastMixer == FastMixer_Dynamic) {
2737 mNormalSink = mPipeSink;
2738 }
2739 } else {
2740 sq->end(false /*didModify*/);
2741 }
2742 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002743 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08002744}
2745
2746void AudioFlinger::MixerThread::threadLoop_standby()
2747{
2748 // Idle the fast mixer if it's currently running
2749 if (mFastMixer != NULL) {
2750 FastMixerStateQueue *sq = mFastMixer->sq();
2751 FastMixerState *state = sq->begin();
2752 if (!(state->mCommand & FastMixerState::IDLE)) {
2753 state->mCommand = FastMixerState::COLD_IDLE;
2754 state->mColdFutexAddr = &mFastMixerFutex;
2755 state->mColdGen++;
2756 mFastMixerFutex = 0;
2757 sq->end();
2758 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
2759 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
2760 if (kUseFastMixer == FastMixer_Dynamic) {
2761 mNormalSink = mOutputSink;
2762 }
2763#ifdef AUDIO_WATCHDOG
2764 if (mAudioWatchdog != 0) {
2765 mAudioWatchdog->pause();
2766 }
2767#endif
2768 } else {
2769 sq->end(false /*didModify*/);
2770 }
2771 }
2772 PlaybackThread::threadLoop_standby();
2773}
2774
Eric Laurentbfb1b832013-01-07 09:53:42 -08002775bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
2776{
2777 return false;
2778}
2779
2780bool AudioFlinger::PlaybackThread::shouldStandby_l()
2781{
2782 return !mStandby;
2783}
2784
2785bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
2786{
2787 Mutex::Autolock _l(mLock);
2788 return waitingAsyncCallback_l();
2789}
2790
Eric Laurent81784c32012-11-19 14:55:58 -08002791// shared by MIXER and DIRECT, overridden by DUPLICATING
2792void AudioFlinger::PlaybackThread::threadLoop_standby()
2793{
2794 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
2795 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002796 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002797 // discard any pending drain or write ack by incrementing sequence
2798 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
2799 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002800 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002801 mCallbackThread->setWriteBlocked(mWriteAckSequence);
2802 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002803 }
Eric Laurent81784c32012-11-19 14:55:58 -08002804}
2805
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002806void AudioFlinger::PlaybackThread::onAddNewTrack_l()
2807{
2808 ALOGV("signal playback thread");
2809 broadcast_l();
2810}
2811
Eric Laurent81784c32012-11-19 14:55:58 -08002812void AudioFlinger::MixerThread::threadLoop_mix()
2813{
2814 // obtain the presentation timestamp of the next output buffer
2815 int64_t pts;
2816 status_t status = INVALID_OPERATION;
2817
2818 if (mNormalSink != 0) {
2819 status = mNormalSink->getNextWriteTimestamp(&pts);
2820 } else {
2821 status = mOutputSink->getNextWriteTimestamp(&pts);
2822 }
2823
2824 if (status != NO_ERROR) {
2825 pts = AudioBufferProvider::kInvalidPTS;
2826 }
2827
2828 // mix buffers...
2829 mAudioMixer->process(pts);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002830 mCurrentWriteLength = mixBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002831 // increase sleep time progressively when application underrun condition clears.
2832 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2833 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2834 // such that we would underrun the audio HAL.
2835 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2836 sleepTimeShift--;
2837 }
2838 sleepTime = 0;
2839 standbyTime = systemTime() + standbyDelay;
2840 //TODO: delay standby when effects have a tail
2841}
2842
2843void AudioFlinger::MixerThread::threadLoop_sleepTime()
2844{
2845 // If no tracks are ready, sleep once for the duration of an output
2846 // buffer size, then write 0s to the output
2847 if (sleepTime == 0) {
2848 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
2849 sleepTime = activeSleepTime >> sleepTimeShift;
2850 if (sleepTime < kMinThreadSleepTimeUs) {
2851 sleepTime = kMinThreadSleepTimeUs;
2852 }
2853 // reduce sleep time in case of consecutive application underruns to avoid
2854 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2855 // duration we would end up writing less data than needed by the audio HAL if
2856 // the condition persists.
2857 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2858 sleepTimeShift++;
2859 }
2860 } else {
2861 sleepTime = idleSleepTime;
2862 }
2863 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Glenn Kastene198c362013-08-13 09:13:36 -07002864 memset(mMixBuffer, 0, mixBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002865 sleepTime = 0;
2866 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
2867 "anticipated start");
2868 }
2869 // TODO add standby time extension fct of effect tail
2870}
2871
2872// prepareTracks_l() must be called with ThreadBase::mLock held
2873AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
2874 Vector< sp<Track> > *tracksToRemove)
2875{
2876
2877 mixer_state mixerStatus = MIXER_IDLE;
2878 // find out which tracks need to be processed
2879 size_t count = mActiveTracks.size();
2880 size_t mixedTracks = 0;
2881 size_t tracksWithEffect = 0;
2882 // counts only _active_ fast tracks
2883 size_t fastTracks = 0;
2884 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
2885
2886 float masterVolume = mMasterVolume;
2887 bool masterMute = mMasterMute;
2888
2889 if (masterMute) {
2890 masterVolume = 0;
2891 }
2892 // Delegate master volume control to effect in output mix effect chain if needed
2893 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
2894 if (chain != 0) {
2895 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
2896 chain->setVolume_l(&v, &v);
2897 masterVolume = (float)((v + (1 << 23)) >> 24);
2898 chain.clear();
2899 }
2900
2901 // prepare a new state to push
2902 FastMixerStateQueue *sq = NULL;
2903 FastMixerState *state = NULL;
2904 bool didModify = false;
2905 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
2906 if (mFastMixer != NULL) {
2907 sq = mFastMixer->sq();
2908 state = sq->begin();
2909 }
2910
2911 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07002912 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08002913 if (t == 0) {
2914 continue;
2915 }
2916
2917 // this const just means the local variable doesn't change
2918 Track* const track = t.get();
2919
2920 // process fast tracks
2921 if (track->isFastTrack()) {
2922
2923 // It's theoretically possible (though unlikely) for a fast track to be created
2924 // and then removed within the same normal mix cycle. This is not a problem, as
2925 // the track never becomes active so it's fast mixer slot is never touched.
2926 // The converse, of removing an (active) track and then creating a new track
2927 // at the identical fast mixer slot within the same normal mix cycle,
2928 // is impossible because the slot isn't marked available until the end of each cycle.
2929 int j = track->mFastIndex;
2930 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
2931 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
2932 FastTrack *fastTrack = &state->mFastTracks[j];
2933
2934 // Determine whether the track is currently in underrun condition,
2935 // and whether it had a recent underrun.
2936 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
2937 FastTrackUnderruns underruns = ftDump->mUnderruns;
2938 uint32_t recentFull = (underruns.mBitFields.mFull -
2939 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
2940 uint32_t recentPartial = (underruns.mBitFields.mPartial -
2941 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
2942 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
2943 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
2944 uint32_t recentUnderruns = recentPartial + recentEmpty;
2945 track->mObservedUnderruns = underruns;
2946 // don't count underruns that occur while stopping or pausing
2947 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07002948 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
2949 recentUnderruns > 0) {
2950 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
2951 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002952 }
2953
2954 // This is similar to the state machine for normal tracks,
2955 // with a few modifications for fast tracks.
2956 bool isActive = true;
2957 switch (track->mState) {
2958 case TrackBase::STOPPING_1:
2959 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08002960 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002961 track->mState = TrackBase::STOPPING_2;
2962 }
2963 break;
2964 case TrackBase::PAUSING:
2965 // ramp down is not yet implemented
2966 track->setPaused();
2967 break;
2968 case TrackBase::RESUMING:
2969 // ramp up is not yet implemented
2970 track->mState = TrackBase::ACTIVE;
2971 break;
2972 case TrackBase::ACTIVE:
2973 if (recentFull > 0 || recentPartial > 0) {
2974 // track has provided at least some frames recently: reset retry count
2975 track->mRetryCount = kMaxTrackRetries;
2976 }
2977 if (recentUnderruns == 0) {
2978 // no recent underruns: stay active
2979 break;
2980 }
2981 // there has recently been an underrun of some kind
2982 if (track->sharedBuffer() == 0) {
2983 // were any of the recent underruns "empty" (no frames available)?
2984 if (recentEmpty == 0) {
2985 // no, then ignore the partial underruns as they are allowed indefinitely
2986 break;
2987 }
2988 // there has recently been an "empty" underrun: decrement the retry counter
2989 if (--(track->mRetryCount) > 0) {
2990 break;
2991 }
2992 // indicate to client process that the track was disabled because of underrun;
2993 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07002994 android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08002995 // remove from active list, but state remains ACTIVE [confusing but true]
2996 isActive = false;
2997 break;
2998 }
2999 // fall through
3000 case TrackBase::STOPPING_2:
3001 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003002 case TrackBase::STOPPED:
3003 case TrackBase::FLUSHED: // flush() while active
3004 // Check for presentation complete if track is inactive
3005 // We have consumed all the buffers of this track.
3006 // This would be incomplete if we auto-paused on underrun
3007 {
3008 size_t audioHALFrames =
3009 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3010 size_t framesWritten = mBytesWritten / mFrameSize;
3011 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
3012 // track stays in active list until presentation is complete
3013 break;
3014 }
3015 }
3016 if (track->isStopping_2()) {
3017 track->mState = TrackBase::STOPPED;
3018 }
3019 if (track->isStopped()) {
3020 // Can't reset directly, as fast mixer is still polling this track
3021 // track->reset();
3022 // So instead mark this track as needing to be reset after push with ack
3023 resetMask |= 1 << i;
3024 }
3025 isActive = false;
3026 break;
3027 case TrackBase::IDLE:
3028 default:
3029 LOG_FATAL("unexpected track state %d", track->mState);
3030 }
3031
3032 if (isActive) {
3033 // was it previously inactive?
3034 if (!(state->mTrackMask & (1 << j))) {
3035 ExtendedAudioBufferProvider *eabp = track;
3036 VolumeProvider *vp = track;
3037 fastTrack->mBufferProvider = eabp;
3038 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08003039 fastTrack->mChannelMask = track->mChannelMask;
3040 fastTrack->mGeneration++;
3041 state->mTrackMask |= 1 << j;
3042 didModify = true;
3043 // no acknowledgement required for newly active tracks
3044 }
3045 // cache the combined master volume and stream type volume for fast mixer; this
3046 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08003047 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08003048 ++fastTracks;
3049 } else {
3050 // was it previously active?
3051 if (state->mTrackMask & (1 << j)) {
3052 fastTrack->mBufferProvider = NULL;
3053 fastTrack->mGeneration++;
3054 state->mTrackMask &= ~(1 << j);
3055 didModify = true;
3056 // If any fast tracks were removed, we must wait for acknowledgement
3057 // because we're about to decrement the last sp<> on those tracks.
3058 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3059 } else {
3060 LOG_FATAL("fast track %d should have been active", j);
3061 }
3062 tracksToRemove->add(track);
3063 // Avoids a misleading display in dumpsys
3064 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
3065 }
3066 continue;
3067 }
3068
3069 { // local variable scope to avoid goto warning
3070
3071 audio_track_cblk_t* cblk = track->cblk();
3072
3073 // The first time a track is added we wait
3074 // for all its buffers to be filled before processing it
3075 int name = track->name();
3076 // make sure that we have enough frames to mix one full buffer.
3077 // enforce this condition only once to enable draining the buffer in case the client
3078 // app does not call stop() and relies on underrun to stop:
3079 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
3080 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003081 size_t desiredFrames;
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003082 uint32_t sr = track->sampleRate();
3083 if (sr == mSampleRate) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003084 desiredFrames = mNormalFrameCount;
3085 } else {
3086 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003087 desiredFrames = (mNormalFrameCount * sr) / mSampleRate + 1 + 1;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003088 // add frames already consumed but not yet released by the resampler
Glenn Kasten2fc14732013-08-05 14:58:14 -07003089 // because mAudioTrackServerProxy->framesReady() will include these frames
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003090 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
Glenn Kasten74935e42013-12-19 08:56:45 -08003091#if 0
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003092 // the minimum track buffer size is normally twice the number of frames necessary
3093 // to fill one buffer and the resampler should not leave more than one buffer worth
3094 // of unreleased frames after each pass, but just in case...
3095 ALOG_ASSERT(desiredFrames <= cblk->frameCount_);
Glenn Kasten74935e42013-12-19 08:56:45 -08003096#endif
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003097 }
Eric Laurent81784c32012-11-19 14:55:58 -08003098 uint32_t minFrames = 1;
3099 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
3100 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003101 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08003102 }
Eric Laurent13e4c962013-12-20 17:36:01 -08003103
3104 size_t framesReady = track->framesReady();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003105 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08003106 !track->isPaused() && !track->isTerminated())
3107 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003108 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003109
3110 mixedTracks++;
3111
3112 // track->mainBuffer() != mMixBuffer means there is an effect chain
3113 // connected to the track
3114 chain.clear();
3115 if (track->mainBuffer() != mMixBuffer) {
3116 chain = getEffectChain_l(track->sessionId());
3117 // Delegate volume control to effect in track effect chain if needed
3118 if (chain != 0) {
3119 tracksWithEffect++;
3120 } else {
3121 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
3122 "session %d",
3123 name, track->sessionId());
3124 }
3125 }
3126
3127
3128 int param = AudioMixer::VOLUME;
3129 if (track->mFillingUpStatus == Track::FS_FILLED) {
3130 // no ramp for the first volume setting
3131 track->mFillingUpStatus = Track::FS_ACTIVE;
3132 if (track->mState == TrackBase::RESUMING) {
3133 track->mState = TrackBase::ACTIVE;
3134 param = AudioMixer::RAMP_VOLUME;
3135 }
3136 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003137 // FIXME should not make a decision based on mServer
3138 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003139 // If the track is stopped before the first frame was mixed,
3140 // do not apply ramp
3141 param = AudioMixer::RAMP_VOLUME;
3142 }
3143
3144 // compute volume for this track
3145 uint32_t vl, vr, va;
Glenn Kastene4756fe2012-11-29 13:38:14 -08003146 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Eric Laurent81784c32012-11-19 14:55:58 -08003147 vl = vr = va = 0;
3148 if (track->isPausing()) {
3149 track->setPaused();
3150 }
3151 } else {
3152
3153 // read original volumes with volume control
3154 float typeVolume = mStreamTypes[track->streamType()].volume;
3155 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003156 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastene3aa6592012-12-04 12:22:46 -08003157 uint32_t vlr = proxy->getVolumeLR();
Eric Laurent81784c32012-11-19 14:55:58 -08003158 vl = vlr & 0xFFFF;
3159 vr = vlr >> 16;
3160 // track volumes come from shared memory, so can't be trusted and must be clamped
3161 if (vl > MAX_GAIN_INT) {
3162 ALOGV("Track left volume out of range: %04X", vl);
3163 vl = MAX_GAIN_INT;
3164 }
3165 if (vr > MAX_GAIN_INT) {
3166 ALOGV("Track right volume out of range: %04X", vr);
3167 vr = MAX_GAIN_INT;
3168 }
3169 // now apply the master volume and stream type volume
3170 vl = (uint32_t)(v * vl) << 12;
3171 vr = (uint32_t)(v * vr) << 12;
3172 // assuming master volume and stream type volume each go up to 1.0,
3173 // vl and vr are now in 8.24 format
3174
Glenn Kastene3aa6592012-12-04 12:22:46 -08003175 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08003176 // send level comes from shared memory and so may be corrupt
3177 if (sendLevel > MAX_GAIN_INT) {
3178 ALOGV("Track send level out of range: %04X", sendLevel);
3179 sendLevel = MAX_GAIN_INT;
3180 }
3181 va = (uint32_t)(v * sendLevel);
3182 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003183
Eric Laurent81784c32012-11-19 14:55:58 -08003184 // Delegate volume control to effect in track effect chain if needed
3185 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3186 // Do not ramp volume if volume is controlled by effect
3187 param = AudioMixer::VOLUME;
3188 track->mHasVolumeController = true;
3189 } else {
3190 // force no volume ramp when volume controller was just disabled or removed
3191 // from effect chain to avoid volume spike
3192 if (track->mHasVolumeController) {
3193 param = AudioMixer::VOLUME;
3194 }
3195 track->mHasVolumeController = false;
3196 }
3197
3198 // Convert volumes from 8.24 to 4.12 format
3199 // This additional clamping is needed in case chain->setVolume_l() overshot
3200 vl = (vl + (1 << 11)) >> 12;
3201 if (vl > MAX_GAIN_INT) {
3202 vl = MAX_GAIN_INT;
3203 }
3204 vr = (vr + (1 << 11)) >> 12;
3205 if (vr > MAX_GAIN_INT) {
3206 vr = MAX_GAIN_INT;
3207 }
3208
3209 if (va > MAX_GAIN_INT) {
3210 va = MAX_GAIN_INT; // va is uint32_t, so no need to check for -
3211 }
3212
3213 // XXX: these things DON'T need to be done each time
3214 mAudioMixer->setBufferProvider(name, track);
3215 mAudioMixer->enable(name);
3216
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003217 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)(uintptr_t)vl);
3218 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)(uintptr_t)vr);
3219 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)(uintptr_t)va);
Eric Laurent81784c32012-11-19 14:55:58 -08003220 mAudioMixer->setParameter(
3221 name,
3222 AudioMixer::TRACK,
3223 AudioMixer::FORMAT, (void *)track->format());
3224 mAudioMixer->setParameter(
3225 name,
3226 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003227 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Glenn Kastene3aa6592012-12-04 12:22:46 -08003228 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
3229 uint32_t maxSampleRate = mSampleRate * 2;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003230 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08003231 if (reqSampleRate == 0) {
3232 reqSampleRate = mSampleRate;
3233 } else if (reqSampleRate > maxSampleRate) {
3234 reqSampleRate = maxSampleRate;
3235 }
Eric Laurent81784c32012-11-19 14:55:58 -08003236 mAudioMixer->setParameter(
3237 name,
3238 AudioMixer::RESAMPLE,
3239 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003240 (void *)(uintptr_t)reqSampleRate);
Eric Laurent81784c32012-11-19 14:55:58 -08003241 mAudioMixer->setParameter(
3242 name,
3243 AudioMixer::TRACK,
3244 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3245 mAudioMixer->setParameter(
3246 name,
3247 AudioMixer::TRACK,
3248 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3249
3250 // reset retry count
3251 track->mRetryCount = kMaxTrackRetries;
3252
3253 // If one track is ready, set the mixer ready if:
3254 // - the mixer was not ready during previous round OR
3255 // - no other track is not ready
3256 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
3257 mixerStatus != MIXER_TRACKS_ENABLED) {
3258 mixerStatus = MIXER_TRACKS_READY;
3259 }
3260 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003261 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Glenn Kasten82aaf942013-07-17 16:05:07 -07003262 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003263 }
Eric Laurent81784c32012-11-19 14:55:58 -08003264 // clear effect chain input buffer if an active track underruns to avoid sending
3265 // previous audio buffer again to effects
3266 chain = getEffectChain_l(track->sessionId());
3267 if (chain != 0) {
3268 chain->clearInputBuffer();
3269 }
3270
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003271 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003272 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3273 track->isStopped() || track->isPaused()) {
3274 // We have consumed all the buffers of this track.
3275 // Remove it from the list of active tracks.
3276 // TODO: use actual buffer filling status instead of latency when available from
3277 // audio HAL
3278 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3279 size_t framesWritten = mBytesWritten / mFrameSize;
3280 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
3281 if (track->isStopped()) {
3282 track->reset();
3283 }
3284 tracksToRemove->add(track);
3285 }
3286 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08003287 // No buffers for this track. Give it a few chances to
3288 // fill a buffer, then remove it from active list.
3289 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08003290 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003291 tracksToRemove->add(track);
3292 // indicate to client process that the track was disabled because of underrun;
3293 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003294 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003295 // If one track is not ready, mark the mixer also not ready if:
3296 // - the mixer was ready during previous round OR
3297 // - no other track is ready
3298 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
3299 mixerStatus != MIXER_TRACKS_READY) {
3300 mixerStatus = MIXER_TRACKS_ENABLED;
3301 }
3302 }
3303 mAudioMixer->disable(name);
3304 }
3305
3306 } // local variable scope to avoid goto warning
3307track_is_ready: ;
3308
3309 }
3310
3311 // Push the new FastMixer state if necessary
3312 bool pauseAudioWatchdog = false;
3313 if (didModify) {
3314 state->mFastTracksGen++;
3315 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3316 if (kUseFastMixer == FastMixer_Dynamic &&
3317 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3318 state->mCommand = FastMixerState::COLD_IDLE;
3319 state->mColdFutexAddr = &mFastMixerFutex;
3320 state->mColdGen++;
3321 mFastMixerFutex = 0;
3322 if (kUseFastMixer == FastMixer_Dynamic) {
3323 mNormalSink = mOutputSink;
3324 }
3325 // If we go into cold idle, need to wait for acknowledgement
3326 // so that fast mixer stops doing I/O.
3327 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3328 pauseAudioWatchdog = true;
3329 }
Eric Laurent81784c32012-11-19 14:55:58 -08003330 }
3331 if (sq != NULL) {
3332 sq->end(didModify);
3333 sq->push(block);
3334 }
3335#ifdef AUDIO_WATCHDOG
3336 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3337 mAudioWatchdog->pause();
3338 }
3339#endif
3340
3341 // Now perform the deferred reset on fast tracks that have stopped
3342 while (resetMask != 0) {
3343 size_t i = __builtin_ctz(resetMask);
3344 ALOG_ASSERT(i < count);
3345 resetMask &= ~(1 << i);
3346 sp<Track> t = mActiveTracks[i].promote();
3347 if (t == 0) {
3348 continue;
3349 }
3350 Track* track = t.get();
3351 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3352 track->reset();
3353 }
3354
3355 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08003356 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08003357
3358 // mix buffer must be cleared if all tracks are connected to an
3359 // effect chain as in this case the mixer will not write to
3360 // mix buffer and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08003361 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3362 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08003363 // FIXME as a performance optimization, should remember previous zero status
3364 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
3365 }
3366
3367 // if any fast tracks, then status is ready
3368 mMixerStatusIgnoringFastTracks = mixerStatus;
3369 if (fastTracks > 0) {
3370 mixerStatus = MIXER_TRACKS_READY;
3371 }
3372 return mixerStatus;
3373}
3374
3375// getTrackName_l() must be called with ThreadBase::mLock held
3376int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask, int sessionId)
3377{
3378 return mAudioMixer->getTrackName(channelMask, sessionId);
3379}
3380
3381// deleteTrackName_l() must be called with ThreadBase::mLock held
3382void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3383{
3384 ALOGV("remove track (%d) and delete from mixer", name);
3385 mAudioMixer->deleteTrackName(name);
3386}
3387
3388// checkForNewParameters_l() must be called with ThreadBase::mLock held
3389bool AudioFlinger::MixerThread::checkForNewParameters_l()
3390{
3391 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3392 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3393 bool reconfig = false;
3394
3395 while (!mNewParameters.isEmpty()) {
3396
3397 if (mFastMixer != NULL) {
3398 FastMixerStateQueue *sq = mFastMixer->sq();
3399 FastMixerState *state = sq->begin();
3400 if (!(state->mCommand & FastMixerState::IDLE)) {
3401 previousCommand = state->mCommand;
3402 state->mCommand = FastMixerState::HOT_IDLE;
3403 sq->end();
3404 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3405 } else {
3406 sq->end(false /*didModify*/);
3407 }
3408 }
3409
3410 status_t status = NO_ERROR;
3411 String8 keyValuePair = mNewParameters[0];
3412 AudioParameter param = AudioParameter(keyValuePair);
3413 int value;
3414
3415 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3416 reconfig = true;
3417 }
3418 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
3419 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
3420 status = BAD_VALUE;
3421 } else {
Glenn Kasten2fc14732013-08-05 14:58:14 -07003422 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08003423 reconfig = true;
3424 }
3425 }
3426 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Glenn Kastenfad226a2013-07-16 17:19:58 -07003427 if ((audio_channel_mask_t) value != AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurent81784c32012-11-19 14:55:58 -08003428 status = BAD_VALUE;
3429 } else {
Glenn Kasten2fc14732013-08-05 14:58:14 -07003430 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08003431 reconfig = true;
3432 }
3433 }
3434 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3435 // do not accept frame count changes if tracks are open as the track buffer
3436 // size depends on frame count and correct behavior would not be guaranteed
3437 // if frame count is changed after track creation
3438 if (!mTracks.isEmpty()) {
3439 status = INVALID_OPERATION;
3440 } else {
3441 reconfig = true;
3442 }
3443 }
3444 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
3445#ifdef ADD_BATTERY_DATA
3446 // when changing the audio output device, call addBatteryData to notify
3447 // the change
3448 if (mOutDevice != value) {
3449 uint32_t params = 0;
3450 // check whether speaker is on
3451 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
3452 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
3453 }
3454
3455 audio_devices_t deviceWithoutSpeaker
3456 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3457 // check if any other device (except speaker) is on
3458 if (value & deviceWithoutSpeaker ) {
3459 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3460 }
3461
3462 if (params != 0) {
3463 addBatteryData(params);
3464 }
3465 }
3466#endif
3467
3468 // forward device change to effects that have requested to be
3469 // aware of attached audio device.
Eric Laurent7e1139c2013-06-06 18:29:01 -07003470 if (value != AUDIO_DEVICE_NONE) {
3471 mOutDevice = value;
3472 for (size_t i = 0; i < mEffectChains.size(); i++) {
3473 mEffectChains[i]->setDevice_l(mOutDevice);
3474 }
Eric Laurent81784c32012-11-19 14:55:58 -08003475 }
3476 }
3477
3478 if (status == NO_ERROR) {
3479 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3480 keyValuePair.string());
3481 if (!mStandby && status == INVALID_OPERATION) {
3482 mOutput->stream->common.standby(&mOutput->stream->common);
3483 mStandby = true;
3484 mBytesWritten = 0;
3485 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3486 keyValuePair.string());
3487 }
3488 if (status == NO_ERROR && reconfig) {
Glenn Kastendeca2ae2014-02-07 10:25:56 -08003489 readOutputParameters_l();
Glenn Kasten9e8fcbc2013-07-25 10:09:11 -07003490 delete mAudioMixer;
Eric Laurent81784c32012-11-19 14:55:58 -08003491 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3492 for (size_t i = 0; i < mTracks.size() ; i++) {
3493 int name = getTrackName_l(mTracks[i]->mChannelMask, mTracks[i]->mSessionId);
3494 if (name < 0) {
3495 break;
3496 }
3497 mTracks[i]->mName = name;
Eric Laurent81784c32012-11-19 14:55:58 -08003498 }
3499 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3500 }
3501 }
3502
3503 mNewParameters.removeAt(0);
3504
3505 mParamStatus = status;
3506 mParamCond.signal();
3507 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3508 // already timed out waiting for the status and will never signal the condition.
3509 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
3510 }
3511
3512 if (!(previousCommand & FastMixerState::IDLE)) {
3513 ALOG_ASSERT(mFastMixer != NULL);
3514 FastMixerStateQueue *sq = mFastMixer->sq();
3515 FastMixerState *state = sq->begin();
3516 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3517 state->mCommand = previousCommand;
3518 sq->end();
3519 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3520 }
3521
3522 return reconfig;
3523}
3524
3525
3526void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
3527{
3528 const size_t SIZE = 256;
3529 char buffer[SIZE];
3530 String8 result;
3531
3532 PlaybackThread::dumpInternals(fd, args);
3533
Marco Nelissenb2208842014-02-07 14:00:50 -08003534 fdprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Eric Laurent81784c32012-11-19 14:55:58 -08003535
3536 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003537 const FastMixerDumpState copy(mFastMixerDumpState);
Eric Laurent81784c32012-11-19 14:55:58 -08003538 copy.dump(fd);
3539
3540#ifdef STATE_QUEUE_DUMP
3541 // Similar for state queue
3542 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
3543 observerCopy.dump(fd);
3544 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
3545 mutatorCopy.dump(fd);
3546#endif
3547
Glenn Kasten46909e72013-02-26 09:20:22 -08003548#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003549 // Write the tee output to a .wav file
3550 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08003551#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003552
3553#ifdef AUDIO_WATCHDOG
3554 if (mAudioWatchdog != 0) {
3555 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
3556 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
3557 wdCopy.dump(fd);
3558 }
3559#endif
3560}
3561
3562uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
3563{
3564 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
3565}
3566
3567uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
3568{
3569 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3570}
3571
3572void AudioFlinger::MixerThread::cacheParameters_l()
3573{
3574 PlaybackThread::cacheParameters_l();
3575
3576 // FIXME: Relaxed timing because of a certain device that can't meet latency
3577 // Should be reduced to 2x after the vendor fixes the driver issue
3578 // increase threshold again due to low power audio mode. The way this warning
3579 // threshold is calculated and its usefulness should be reconsidered anyway.
3580 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
3581}
3582
3583// ----------------------------------------------------------------------------
3584
3585AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3586 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
3587 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
3588 // mLeftVolFloat, mRightVolFloat
3589{
3590}
3591
Eric Laurentbfb1b832013-01-07 09:53:42 -08003592AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3593 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
3594 ThreadBase::type_t type)
3595 : PlaybackThread(audioFlinger, output, id, device, type)
3596 // mLeftVolFloat, mRightVolFloat
3597{
3598}
3599
Eric Laurent81784c32012-11-19 14:55:58 -08003600AudioFlinger::DirectOutputThread::~DirectOutputThread()
3601{
3602}
3603
Eric Laurentbfb1b832013-01-07 09:53:42 -08003604void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
3605{
3606 audio_track_cblk_t* cblk = track->cblk();
3607 float left, right;
3608
3609 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
3610 left = right = 0;
3611 } else {
3612 float typeVolume = mStreamTypes[track->streamType()].volume;
3613 float v = mMasterVolume * typeVolume;
3614 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
3615 uint32_t vlr = proxy->getVolumeLR();
3616 float v_clamped = v * (vlr & 0xFFFF);
3617 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3618 left = v_clamped/MAX_GAIN;
3619 v_clamped = v * (vlr >> 16);
3620 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3621 right = v_clamped/MAX_GAIN;
3622 }
3623
3624 if (lastTrack) {
3625 if (left != mLeftVolFloat || right != mRightVolFloat) {
3626 mLeftVolFloat = left;
3627 mRightVolFloat = right;
3628
3629 // Convert volumes from float to 8.24
3630 uint32_t vl = (uint32_t)(left * (1 << 24));
3631 uint32_t vr = (uint32_t)(right * (1 << 24));
3632
3633 // Delegate volume control to effect in track effect chain if needed
3634 // only one effect chain can be present on DirectOutputThread, so if
3635 // there is one, the track is connected to it
3636 if (!mEffectChains.isEmpty()) {
3637 mEffectChains[0]->setVolume_l(&vl, &vr);
3638 left = (float)vl / (1 << 24);
3639 right = (float)vr / (1 << 24);
3640 }
3641 if (mOutput->stream->set_volume) {
3642 mOutput->stream->set_volume(mOutput->stream, left, right);
3643 }
3644 }
3645 }
3646}
3647
3648
Eric Laurent81784c32012-11-19 14:55:58 -08003649AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
3650 Vector< sp<Track> > *tracksToRemove
3651)
3652{
Eric Laurentd595b7c2013-04-03 17:27:56 -07003653 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08003654 mixer_state mixerStatus = MIXER_IDLE;
3655
3656 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07003657 for (size_t i = 0; i < count; i++) {
3658 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003659 // The track died recently
3660 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003661 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08003662 }
3663
3664 Track* const track = t.get();
3665 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07003666 // Only consider last track started for volume and mixer state control.
3667 // In theory an older track could underrun and restart after the new one starts
3668 // but as we only care about the transition phase between two tracks on a
3669 // direct output, it is not a problem to ignore the underrun case.
3670 sp<Track> l = mLatestActiveTrack.promote();
3671 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08003672
3673 // The first time a track is added we wait
3674 // for all its buffers to be filled before processing it
3675 uint32_t minFrames;
3676 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing()) {
3677 minFrames = mNormalFrameCount;
3678 } else {
3679 minFrames = 1;
3680 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003681
Eric Laurent81784c32012-11-19 14:55:58 -08003682 if ((track->framesReady() >= minFrames) && track->isReady() &&
3683 !track->isPaused() && !track->isTerminated())
3684 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003685 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08003686
3687 if (track->mFillingUpStatus == Track::FS_FILLED) {
3688 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07003689 // make sure processVolume_l() will apply new volume even if 0
3690 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurent81784c32012-11-19 14:55:58 -08003691 if (track->mState == TrackBase::RESUMING) {
3692 track->mState = TrackBase::ACTIVE;
3693 }
3694 }
3695
3696 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08003697 processVolume_l(track, last);
3698 if (last) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003699 // reset retry count
3700 track->mRetryCount = kMaxTrackRetriesDirect;
3701 mActiveTrack = t;
3702 mixerStatus = MIXER_TRACKS_READY;
3703 }
Eric Laurent81784c32012-11-19 14:55:58 -08003704 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003705 // clear effect chain input buffer if the last active track started underruns
3706 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07003707 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08003708 mEffectChains[0]->clearInputBuffer();
3709 }
3710
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003711 ALOGVV("track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08003712 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3713 track->isStopped() || track->isPaused()) {
3714 // We have consumed all the buffers of this track.
3715 // Remove it from the list of active tracks.
3716 // TODO: implement behavior for compressed audio
3717 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3718 size_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07003719 if (mStandby || !last ||
3720 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003721 if (track->isStopped()) {
3722 track->reset();
3723 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07003724 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08003725 }
3726 } else {
3727 // No buffers for this track. Give it a few chances to
3728 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07003729 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08003730 if (--(track->mRetryCount) <= 0) {
3731 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07003732 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08003733 // indicate to client process that the track was disabled because of underrun;
3734 // it will then automatically call start() when data is available
3735 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003736 } else if (last) {
Eric Laurent81784c32012-11-19 14:55:58 -08003737 mixerStatus = MIXER_TRACKS_ENABLED;
3738 }
3739 }
3740 }
3741 }
3742
Eric Laurent81784c32012-11-19 14:55:58 -08003743 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08003744 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08003745
3746 return mixerStatus;
3747}
3748
3749void AudioFlinger::DirectOutputThread::threadLoop_mix()
3750{
Eric Laurent81784c32012-11-19 14:55:58 -08003751 size_t frameCount = mFrameCount;
3752 int8_t *curBuf = (int8_t *)mMixBuffer;
3753 // output audio to hardware
3754 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07003755 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08003756 buffer.frameCount = frameCount;
3757 mActiveTrack->getNextBuffer(&buffer);
Glenn Kastenfa319e62013-07-29 17:17:38 -07003758 if (buffer.raw == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08003759 memset(curBuf, 0, frameCount * mFrameSize);
3760 break;
3761 }
3762 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
3763 frameCount -= buffer.frameCount;
3764 curBuf += buffer.frameCount * mFrameSize;
3765 mActiveTrack->releaseBuffer(&buffer);
3766 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003767 mCurrentWriteLength = curBuf - (int8_t *)mMixBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08003768 sleepTime = 0;
3769 standbyTime = systemTime() + standbyDelay;
3770 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003771}
3772
3773void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3774{
3775 if (sleepTime == 0) {
3776 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3777 sleepTime = activeSleepTime;
3778 } else {
3779 sleepTime = idleSleepTime;
3780 }
3781 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
3782 memset(mMixBuffer, 0, mFrameCount * mFrameSize);
3783 sleepTime = 0;
3784 }
3785}
3786
3787// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08003788int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
3789 int sessionId __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08003790{
3791 return 0;
3792}
3793
3794// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08003795void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08003796{
3797}
3798
3799// checkForNewParameters_l() must be called with ThreadBase::mLock held
3800bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
3801{
3802 bool reconfig = false;
3803
3804 while (!mNewParameters.isEmpty()) {
3805 status_t status = NO_ERROR;
3806 String8 keyValuePair = mNewParameters[0];
3807 AudioParameter param = AudioParameter(keyValuePair);
3808 int value;
3809
3810 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3811 // do not accept frame count changes if tracks are open as the track buffer
3812 // size depends on frame count and correct behavior would not be garantied
3813 // if frame count is changed after track creation
3814 if (!mTracks.isEmpty()) {
3815 status = INVALID_OPERATION;
3816 } else {
3817 reconfig = true;
3818 }
3819 }
3820 if (status == NO_ERROR) {
3821 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3822 keyValuePair.string());
3823 if (!mStandby && status == INVALID_OPERATION) {
3824 mOutput->stream->common.standby(&mOutput->stream->common);
3825 mStandby = true;
3826 mBytesWritten = 0;
3827 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3828 keyValuePair.string());
3829 }
3830 if (status == NO_ERROR && reconfig) {
Glenn Kastendeca2ae2014-02-07 10:25:56 -08003831 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08003832 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3833 }
3834 }
3835
3836 mNewParameters.removeAt(0);
3837
3838 mParamStatus = status;
3839 mParamCond.signal();
3840 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3841 // already timed out waiting for the status and will never signal the condition.
3842 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
3843 }
3844 return reconfig;
3845}
3846
3847uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
3848{
3849 uint32_t time;
3850 if (audio_is_linear_pcm(mFormat)) {
3851 time = PlaybackThread::activeSleepTimeUs();
3852 } else {
3853 time = 10000;
3854 }
3855 return time;
3856}
3857
3858uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
3859{
3860 uint32_t time;
3861 if (audio_is_linear_pcm(mFormat)) {
3862 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
3863 } else {
3864 time = 10000;
3865 }
3866 return time;
3867}
3868
3869uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
3870{
3871 uint32_t time;
3872 if (audio_is_linear_pcm(mFormat)) {
3873 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3874 } else {
3875 time = 10000;
3876 }
3877 return time;
3878}
3879
3880void AudioFlinger::DirectOutputThread::cacheParameters_l()
3881{
3882 PlaybackThread::cacheParameters_l();
3883
3884 // use shorter standby delay as on normal output to release
3885 // hardware resources as soon as possible
Eric Laurent972a1732013-09-04 09:42:59 -07003886 if (audio_is_linear_pcm(mFormat)) {
3887 standbyDelay = microseconds(activeSleepTime*2);
3888 } else {
3889 standbyDelay = kOffloadStandbyDelayNs;
3890 }
Eric Laurent81784c32012-11-19 14:55:58 -08003891}
3892
3893// ----------------------------------------------------------------------------
3894
Eric Laurentbfb1b832013-01-07 09:53:42 -08003895AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07003896 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003897 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07003898 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07003899 mWriteAckSequence(0),
3900 mDrainSequence(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003901{
3902}
3903
3904AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
3905{
3906}
3907
3908void AudioFlinger::AsyncCallbackThread::onFirstRef()
3909{
3910 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
3911}
3912
3913bool AudioFlinger::AsyncCallbackThread::threadLoop()
3914{
3915 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003916 uint32_t writeAckSequence;
3917 uint32_t drainSequence;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003918
3919 {
3920 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08003921 while (!((mWriteAckSequence & 1) ||
3922 (mDrainSequence & 1) ||
3923 exitPending())) {
3924 mWaitWorkCV.wait(mLock);
3925 }
3926
Eric Laurentbfb1b832013-01-07 09:53:42 -08003927 if (exitPending()) {
3928 break;
3929 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07003930 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
3931 mWriteAckSequence, mDrainSequence);
3932 writeAckSequence = mWriteAckSequence;
3933 mWriteAckSequence &= ~1;
3934 drainSequence = mDrainSequence;
3935 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003936 }
3937 {
Eric Laurent4de95592013-09-26 15:28:21 -07003938 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
3939 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003940 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07003941 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003942 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07003943 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07003944 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003945 }
3946 }
3947 }
3948 }
3949 return false;
3950}
3951
3952void AudioFlinger::AsyncCallbackThread::exit()
3953{
3954 ALOGV("AsyncCallbackThread::exit");
3955 Mutex::Autolock _l(mLock);
3956 requestExit();
3957 mWaitWorkCV.broadcast();
3958}
3959
Eric Laurent3b4529e2013-09-05 18:09:19 -07003960void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003961{
3962 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003963 // bit 0 is cleared
3964 mWriteAckSequence = sequence << 1;
3965}
3966
3967void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
3968{
3969 Mutex::Autolock _l(mLock);
3970 // ignore unexpected callbacks
3971 if (mWriteAckSequence & 2) {
3972 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003973 mWaitWorkCV.signal();
3974 }
3975}
3976
Eric Laurent3b4529e2013-09-05 18:09:19 -07003977void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003978{
3979 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003980 // bit 0 is cleared
3981 mDrainSequence = sequence << 1;
3982}
3983
3984void AudioFlinger::AsyncCallbackThread::resetDraining()
3985{
3986 Mutex::Autolock _l(mLock);
3987 // ignore unexpected callbacks
3988 if (mDrainSequence & 2) {
3989 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003990 mWaitWorkCV.signal();
3991 }
3992}
3993
3994
3995// ----------------------------------------------------------------------------
3996AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
3997 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
3998 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD),
3999 mHwPaused(false),
Eric Laurentea0fade2013-10-04 16:23:48 -07004000 mFlushPending(false),
Eric Laurentd7e59222013-11-15 12:02:28 -08004001 mPausedBytesRemaining(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004002{
Eric Laurentfd477972013-10-25 18:10:40 -07004003 //FIXME: mStandby should be set to true by ThreadBase constructor
4004 mStandby = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004005}
4006
Eric Laurentbfb1b832013-01-07 09:53:42 -08004007void AudioFlinger::OffloadThread::threadLoop_exit()
4008{
4009 if (mFlushPending || mHwPaused) {
4010 // If a flush is pending or track was paused, just discard buffered data
4011 flushHw_l();
4012 } else {
4013 mMixerStatus = MIXER_DRAIN_ALL;
4014 threadLoop_drain();
4015 }
4016 mCallbackThread->exit();
4017 PlaybackThread::threadLoop_exit();
4018}
4019
4020AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
4021 Vector< sp<Track> > *tracksToRemove
4022)
4023{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004024 size_t count = mActiveTracks.size();
4025
4026 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07004027 bool doHwPause = false;
4028 bool doHwResume = false;
4029
Eric Laurentede6c3b2013-09-19 14:37:46 -07004030 ALOGV("OffloadThread::prepareTracks_l active tracks %d", count);
4031
Eric Laurentbfb1b832013-01-07 09:53:42 -08004032 // find out which tracks need to be processed
4033 for (size_t i = 0; i < count; i++) {
4034 sp<Track> t = mActiveTracks[i].promote();
4035 // The track died recently
4036 if (t == 0) {
4037 continue;
4038 }
4039 Track* const track = t.get();
4040 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07004041 // Only consider last track started for volume and mixer state control.
4042 // In theory an older track could underrun and restart after the new one starts
4043 // but as we only care about the transition phase between two tracks on a
4044 // direct output, it is not a problem to ignore the underrun case.
4045 sp<Track> l = mLatestActiveTrack.promote();
4046 bool last = l.get() == track;
4047
Haynes Mathew George7844f672014-01-15 12:32:55 -08004048 if (track->isInvalid()) {
4049 ALOGW("An invalidated track shouldn't be in active list");
4050 tracksToRemove->add(track);
4051 continue;
4052 }
4053
4054 if (track->mState == TrackBase::IDLE) {
4055 ALOGW("An idle track shouldn't be in active list");
4056 continue;
4057 }
4058
Eric Laurentbfb1b832013-01-07 09:53:42 -08004059 if (track->isPausing()) {
4060 track->setPaused();
4061 if (last) {
4062 if (!mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07004063 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004064 mHwPaused = true;
4065 }
4066 // If we were part way through writing the mixbuffer to
4067 // the HAL we must save this until we resume
4068 // BUG - this will be wrong if a different track is made active,
4069 // in that case we want to discard the pending data in the
4070 // mixbuffer and tell the client to present it again when the
4071 // track is resumed
4072 mPausedWriteLength = mCurrentWriteLength;
4073 mPausedBytesRemaining = mBytesRemaining;
4074 mBytesRemaining = 0; // stop writing
4075 }
4076 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08004077 } else if (track->isFlushPending()) {
4078 track->flushAck();
4079 if (last) {
4080 mFlushPending = true;
4081 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004082 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07004083 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004084 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004085 if (track->mFillingUpStatus == Track::FS_FILLED) {
4086 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004087 // make sure processVolume_l() will apply new volume even if 0
4088 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004089 if (track->mState == TrackBase::RESUMING) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004090 track->mState = TrackBase::ACTIVE;
Eric Laurentede6c3b2013-09-19 14:37:46 -07004091 if (last) {
4092 if (mPausedBytesRemaining) {
4093 // Need to continue write that was interrupted
4094 mCurrentWriteLength = mPausedWriteLength;
4095 mBytesRemaining = mPausedBytesRemaining;
4096 mPausedBytesRemaining = 0;
4097 }
4098 if (mHwPaused) {
4099 doHwResume = true;
4100 mHwPaused = false;
4101 // threadLoop_mix() will handle the case that we need to
4102 // resume an interrupted write
4103 }
4104 // enable write to audio HAL
4105 sleepTime = 0;
4106 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004107 }
4108 }
4109
4110 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08004111 sp<Track> previousTrack = mPreviousTrack.promote();
4112 if (previousTrack != 0) {
4113 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08004114 // Flush any data still being written from last track
4115 mBytesRemaining = 0;
4116 if (mPausedBytesRemaining) {
4117 // Last track was paused so we also need to flush saved
4118 // mixbuffer state and invalidate track so that it will
4119 // re-submit that unwritten data when it is next resumed
4120 mPausedBytesRemaining = 0;
4121 // Invalidate is a bit drastic - would be more efficient
4122 // to have a flag to tell client that some of the
4123 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08004124 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004125 }
4126 // flush data already sent to the DSP if changing audio session as audio
4127 // comes from a different source. Also invalidate previous track to force a
4128 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08004129 if (previousTrack->sessionId() != track->sessionId()) {
4130 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004131 }
4132 }
4133 }
4134 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004135 // reset retry count
4136 track->mRetryCount = kMaxTrackRetriesOffload;
4137 mActiveTrack = t;
4138 mixerStatus = MIXER_TRACKS_READY;
4139 }
4140 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004141 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004142 if (track->isStopping_1()) {
4143 // Hardware buffer can hold a large amount of audio so we must
4144 // wait for all current track's data to drain before we say
4145 // that the track is stopped.
4146 if (mBytesRemaining == 0) {
4147 // Only start draining when all data in mixbuffer
4148 // has been written
4149 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
4150 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004151 // do not drain if no data was ever sent to HAL (mStandby == true)
4152 if (last && !mStandby) {
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004153 // do not modify drain sequence if we are already draining. This happens
4154 // when resuming from pause after drain.
4155 if ((mDrainSequence & 1) == 0) {
4156 sleepTime = 0;
4157 standbyTime = systemTime() + standbyDelay;
4158 mixerStatus = MIXER_DRAIN_TRACK;
4159 mDrainSequence += 2;
4160 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004161 if (mHwPaused) {
4162 // It is possible to move from PAUSED to STOPPING_1 without
4163 // a resume so we must ensure hardware is running
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004164 doHwResume = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004165 mHwPaused = false;
4166 }
4167 }
4168 }
4169 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004170 // Drain has completed or we are in standby, signal presentation complete
4171 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004172 track->mState = TrackBase::STOPPED;
4173 size_t audioHALFrames =
4174 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
4175 size_t framesWritten =
4176 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
4177 track->presentationComplete(framesWritten, audioHALFrames);
4178 track->reset();
4179 tracksToRemove->add(track);
4180 }
4181 } else {
4182 // No buffers for this track. Give it a few chances to
4183 // fill a buffer, then remove it from active list.
4184 if (--(track->mRetryCount) <= 0) {
4185 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
4186 track->name());
4187 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004188 // indicate to client process that the track was disabled because of underrun;
4189 // it will then automatically call start() when data is available
4190 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004191 } else if (last){
4192 mixerStatus = MIXER_TRACKS_ENABLED;
4193 }
4194 }
4195 }
4196 // compute volume for this track
4197 processVolume_l(track, last);
4198 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004199
Eric Laurentea0fade2013-10-04 16:23:48 -07004200 // make sure the pause/flush/resume sequence is executed in the right order.
4201 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4202 // before flush and then resume HW. This can happen in case of pause/flush/resume
4203 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07004204 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurent972a1732013-09-04 09:42:59 -07004205 mOutput->stream->pause(mOutput->stream);
4206 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004207 if (mFlushPending) {
4208 flushHw_l();
4209 mFlushPending = false;
4210 }
Eric Laurentfd477972013-10-25 18:10:40 -07004211 if (!mStandby && doHwResume) {
Eric Laurent972a1732013-09-04 09:42:59 -07004212 mOutput->stream->resume(mOutput->stream);
4213 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004214
Eric Laurentbfb1b832013-01-07 09:53:42 -08004215 // remove all the tracks that need to be...
4216 removeTracks_l(*tracksToRemove);
4217
4218 return mixerStatus;
4219}
4220
Eric Laurentbfb1b832013-01-07 09:53:42 -08004221// must be called with thread mutex locked
4222bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
4223{
Eric Laurent3b4529e2013-09-05 18:09:19 -07004224 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
4225 mWriteAckSequence, mDrainSequence);
4226 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004227 return true;
4228 }
4229 return false;
4230}
4231
4232// must be called with thread mutex locked
4233bool AudioFlinger::OffloadThread::shouldStandby_l()
4234{
Glenn Kastene6f35b12013-08-19 09:58:50 -07004235 bool trackPaused = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004236
4237 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4238 // after a timeout and we will enter standby then.
4239 if (mTracks.size() > 0) {
Glenn Kastene6f35b12013-08-19 09:58:50 -07004240 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004241 }
4242
Glenn Kastene6f35b12013-08-19 09:58:50 -07004243 return !mStandby && !trackPaused;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004244}
4245
4246
4247bool AudioFlinger::OffloadThread::waitingAsyncCallback()
4248{
4249 Mutex::Autolock _l(mLock);
4250 return waitingAsyncCallback_l();
4251}
4252
4253void AudioFlinger::OffloadThread::flushHw_l()
4254{
4255 mOutput->stream->flush(mOutput->stream);
4256 // Flush anything still waiting in the mixbuffer
4257 mCurrentWriteLength = 0;
4258 mBytesRemaining = 0;
4259 mPausedWriteLength = 0;
4260 mPausedBytesRemaining = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08004261 mHwPaused = false;
4262
Eric Laurentbfb1b832013-01-07 09:53:42 -08004263 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004264 // discard any pending drain or write ack by incrementing sequence
4265 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4266 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004267 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004268 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4269 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004270 }
4271}
4272
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08004273void AudioFlinger::OffloadThread::onAddNewTrack_l()
4274{
4275 sp<Track> previousTrack = mPreviousTrack.promote();
4276 sp<Track> latestTrack = mLatestActiveTrack.promote();
4277
4278 if (previousTrack != 0 && latestTrack != 0 &&
4279 (previousTrack->sessionId() != latestTrack->sessionId())) {
4280 mFlushPending = true;
4281 }
4282 PlaybackThread::onAddNewTrack_l();
4283}
4284
Eric Laurentbfb1b832013-01-07 09:53:42 -08004285// ----------------------------------------------------------------------------
4286
Eric Laurent81784c32012-11-19 14:55:58 -08004287AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
4288 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
4289 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
4290 DUPLICATING),
4291 mWaitTimeMs(UINT_MAX)
4292{
4293 addOutputTrack(mainThread);
4294}
4295
4296AudioFlinger::DuplicatingThread::~DuplicatingThread()
4297{
4298 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4299 mOutputTracks[i]->destroy();
4300 }
4301}
4302
4303void AudioFlinger::DuplicatingThread::threadLoop_mix()
4304{
4305 // mix buffers...
4306 if (outputsReady(outputTracks)) {
4307 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
4308 } else {
4309 memset(mMixBuffer, 0, mixBufferSize);
4310 }
4311 sleepTime = 0;
4312 writeFrames = mNormalFrameCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004313 mCurrentWriteLength = mixBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004314 standbyTime = systemTime() + standbyDelay;
4315}
4316
4317void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
4318{
4319 if (sleepTime == 0) {
4320 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4321 sleepTime = activeSleepTime;
4322 } else {
4323 sleepTime = idleSleepTime;
4324 }
4325 } else if (mBytesWritten != 0) {
4326 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4327 writeFrames = mNormalFrameCount;
4328 memset(mMixBuffer, 0, mixBufferSize);
4329 } else {
4330 // flush remaining overflow buffers in output tracks
4331 writeFrames = 0;
4332 }
4333 sleepTime = 0;
4334 }
4335}
4336
Eric Laurentbfb1b832013-01-07 09:53:42 -08004337ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004338{
4339 for (size_t i = 0; i < outputTracks.size(); i++) {
4340 outputTracks[i]->write(mMixBuffer, writeFrames);
4341 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07004342 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004343 return (ssize_t)mixBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004344}
4345
4346void AudioFlinger::DuplicatingThread::threadLoop_standby()
4347{
4348 // DuplicatingThread implements standby by stopping all tracks
4349 for (size_t i = 0; i < outputTracks.size(); i++) {
4350 outputTracks[i]->stop();
4351 }
4352}
4353
4354void AudioFlinger::DuplicatingThread::saveOutputTracks()
4355{
4356 outputTracks = mOutputTracks;
4357}
4358
4359void AudioFlinger::DuplicatingThread::clearOutputTracks()
4360{
4361 outputTracks.clear();
4362}
4363
4364void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
4365{
4366 Mutex::Autolock _l(mLock);
4367 // FIXME explain this formula
4368 size_t frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
4369 OutputTrack *outputTrack = new OutputTrack(thread,
4370 this,
4371 mSampleRate,
4372 mFormat,
4373 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004374 frameCount,
4375 IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08004376 if (outputTrack->cblk() != NULL) {
4377 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
4378 mOutputTracks.add(outputTrack);
4379 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
4380 updateWaitTime_l();
4381 }
4382}
4383
4384void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
4385{
4386 Mutex::Autolock _l(mLock);
4387 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4388 if (mOutputTracks[i]->thread() == thread) {
4389 mOutputTracks[i]->destroy();
4390 mOutputTracks.removeAt(i);
4391 updateWaitTime_l();
4392 return;
4393 }
4394 }
4395 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
4396}
4397
4398// caller must hold mLock
4399void AudioFlinger::DuplicatingThread::updateWaitTime_l()
4400{
4401 mWaitTimeMs = UINT_MAX;
4402 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4403 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
4404 if (strong != 0) {
4405 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4406 if (waitTimeMs < mWaitTimeMs) {
4407 mWaitTimeMs = waitTimeMs;
4408 }
4409 }
4410 }
4411}
4412
4413
4414bool AudioFlinger::DuplicatingThread::outputsReady(
4415 const SortedVector< sp<OutputTrack> > &outputTracks)
4416{
4417 for (size_t i = 0; i < outputTracks.size(); i++) {
4418 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
4419 if (thread == 0) {
4420 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
4421 outputTracks[i].get());
4422 return false;
4423 }
4424 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4425 // see note at standby() declaration
4426 if (playbackThread->standby() && !playbackThread->isSuspended()) {
4427 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
4428 thread.get());
4429 return false;
4430 }
4431 }
4432 return true;
4433}
4434
4435uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
4436{
4437 return (mWaitTimeMs * 1000) / 2;
4438}
4439
4440void AudioFlinger::DuplicatingThread::cacheParameters_l()
4441{
4442 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
4443 updateWaitTime_l();
4444
4445 MixerThread::cacheParameters_l();
4446}
4447
4448// ----------------------------------------------------------------------------
4449// Record
4450// ----------------------------------------------------------------------------
4451
4452AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4453 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08004454 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08004455 audio_devices_t outDevice,
Glenn Kasten46909e72013-02-26 09:20:22 -08004456 audio_devices_t inDevice
4457#ifdef TEE_SINK
4458 , const sp<NBAIO_Sink>& teeSink
4459#endif
4460 ) :
Eric Laurentd3922f72013-02-01 17:57:04 -08004461 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD),
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004462 mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
Glenn Kastendeca2ae2014-02-07 10:25:56 -08004463 // mRsmpInFrames and mRsmpInFramesP2 are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08004464 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08004465#ifdef TEE_SINK
4466 , mTeeSink(teeSink)
4467#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004468{
4469 snprintf(mName, kNameLength, "AudioIn_%X", id);
Glenn Kasten481fb672013-09-30 14:39:28 -07004470 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mName);
Eric Laurent81784c32012-11-19 14:55:58 -08004471
Glenn Kastendeca2ae2014-02-07 10:25:56 -08004472 readInputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08004473}
4474
4475
4476AudioFlinger::RecordThread::~RecordThread()
4477{
Glenn Kasten481fb672013-09-30 14:39:28 -07004478 mAudioFlinger->unregisterWriter(mNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08004479 delete[] mRsmpInBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004480}
4481
4482void AudioFlinger::RecordThread::onFirstRef()
4483{
4484 run(mName, PRIORITY_URGENT_AUDIO);
4485}
4486
Eric Laurent81784c32012-11-19 14:55:58 -08004487bool AudioFlinger::RecordThread::threadLoop()
4488{
Eric Laurent81784c32012-11-19 14:55:58 -08004489 nsecs_t lastWarning = 0;
4490
4491 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08004492
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004493reacquire_wakelock:
4494 sp<RecordTrack> activeTrack;
Glenn Kasten2b806402013-11-20 16:37:38 -08004495 int activeTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004496 {
4497 Mutex::Autolock _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08004498 size_t size = mActiveTracks.size();
4499 activeTracksGen = mActiveTracksGen;
4500 if (size > 0) {
4501 // FIXME an arbitrary choice
4502 activeTrack = mActiveTracks[0];
4503 acquireWakeLock_l(activeTrack->uid());
4504 if (size > 1) {
4505 SortedVector<int> tmp;
4506 for (size_t i = 0; i < size; i++) {
4507 tmp.add(mActiveTracks[i]->uid());
4508 }
4509 updateWakeLockUids_l(tmp);
4510 }
4511 } else {
4512 acquireWakeLock_l(-1);
4513 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004514 }
4515
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004516 // used to request a deferred sleep, to be executed later while mutex is unlocked
4517 uint32_t sleepUs = 0;
4518
4519 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07004520 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07004521 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07004522
Glenn Kasten5edadd42013-08-14 16:30:49 -07004523 // sleep with mutex unlocked
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004524 if (sleepUs > 0) {
4525 usleep(sleepUs);
4526 sleepUs = 0;
Glenn Kasten5edadd42013-08-14 16:30:49 -07004527 }
4528
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004529 // activeTracks accumulates a copy of a subset of mActiveTracks
4530 Vector< sp<RecordTrack> > activeTracks;
4531
Eric Laurent81784c32012-11-19 14:55:58 -08004532 { // scope for mLock
4533 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08004534
Glenn Kasten2cfbf882013-08-14 13:12:11 -07004535 processConfigEvents_l();
Glenn Kasten26a40292013-08-14 13:11:40 -07004536 // return value 'reconfig' is currently unused
4537 bool reconfig = checkForNewParameters_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004538
Eric Laurent000a4192014-01-29 15:17:32 -08004539 // check exitPending here because checkForNewParameters_l() and
4540 // checkForNewParameters_l() can temporarily release mLock
4541 if (exitPending()) {
4542 break;
4543 }
4544
Glenn Kasten2b806402013-11-20 16:37:38 -08004545 // if no active track(s), then standby and release wakelock
4546 size_t size = mActiveTracks.size();
4547 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07004548 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07004549 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08004550 releaseWakeLock_l();
4551 ALOGV("RecordThread: loop stopping");
4552 // go to sleep
4553 mWaitWorkCV.wait(mLock);
4554 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004555 goto reacquire_wakelock;
4556 }
4557
Glenn Kasten2b806402013-11-20 16:37:38 -08004558 if (mActiveTracksGen != activeTracksGen) {
4559 activeTracksGen = mActiveTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004560 SortedVector<int> tmp;
Glenn Kasten2b806402013-11-20 16:37:38 -08004561 for (size_t i = 0; i < size; i++) {
4562 tmp.add(mActiveTracks[i]->uid());
4563 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004564 updateWakeLockUids_l(tmp);
Eric Laurent81784c32012-11-19 14:55:58 -08004565 }
Glenn Kasten9e982352013-08-14 14:39:50 -07004566
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004567 bool doBroadcast = false;
4568 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07004569
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004570 activeTrack = mActiveTracks[i];
4571 if (activeTrack->isTerminated()) {
4572 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08004573 mActiveTracks.remove(activeTrack);
4574 mActiveTracksGen++;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004575 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07004576 continue;
4577 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004578
4579 TrackBase::track_state activeTrackState = activeTrack->mState;
4580 switch (activeTrackState) {
4581
4582 case TrackBase::PAUSING:
4583 mActiveTracks.remove(activeTrack);
4584 mActiveTracksGen++;
4585 doBroadcast = true;
4586 size--;
4587 continue;
4588
4589 case TrackBase::STARTING_1:
4590 sleepUs = 10000;
4591 i++;
4592 continue;
4593
4594 case TrackBase::STARTING_2:
4595 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004596 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07004597 activeTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004598 break;
4599
4600 case TrackBase::ACTIVE:
4601 break;
4602
4603 case TrackBase::IDLE:
4604 i++;
4605 continue;
4606
4607 default:
4608 LOG_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07004609 }
Glenn Kasten9e982352013-08-14 14:39:50 -07004610
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004611 activeTracks.add(activeTrack);
4612 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07004613
Glenn Kasten9e982352013-08-14 14:39:50 -07004614 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004615 if (doBroadcast) {
4616 mStartStopCond.broadcast();
4617 }
4618
4619 // sleep if there are no active tracks to process
4620 if (activeTracks.size() == 0) {
4621 if (sleepUs == 0) {
4622 sleepUs = kRecordThreadSleepUs;
4623 }
4624 continue;
4625 }
4626 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07004627
Eric Laurent81784c32012-11-19 14:55:58 -08004628 lockEffectChains_l(effectChains);
4629 }
4630
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004631 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07004632
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004633 size_t size = effectChains.size();
4634 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004635 // thread mutex is not locked, but effect chain is locked
4636 effectChains[i]->process_l();
4637 }
4638
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004639 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
4640 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
4641 // slow, then this RecordThread will overrun by not calling HAL read often enough.
4642 // If destination is non-contiguous, first read past the nominal end of buffer, then
4643 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004644
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004645 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
4646 ssize_t bytesRead = mInput->stream->read(mInput->stream,
4647 &mRsmpInBuffer[rear * mChannelCount], mBufferSize);
4648 if (bytesRead <= 0) {
4649 ALOGE("read failed: bytesRead=%d < %u", bytesRead, mBufferSize);
4650 // Force input into standby so that it tries to recover at next read attempt
4651 inputStandBy();
4652 sleepUs = kRecordThreadSleepUs;
4653 continue;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004654 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004655 ALOG_ASSERT((size_t) bytesRead <= mBufferSize);
4656 size_t framesRead = bytesRead / mFrameSize;
4657 ALOG_ASSERT(framesRead > 0);
4658 if (mTeeSink != 0) {
4659 (void) mTeeSink->write(&mRsmpInBuffer[rear * mChannelCount], framesRead);
4660 }
4661 // If destination is non-contiguous, we now correct for reading past end of buffer.
4662 size_t part1 = mRsmpInFramesP2 - rear;
4663 if (framesRead > part1) {
4664 memcpy(mRsmpInBuffer, &mRsmpInBuffer[mRsmpInFramesP2 * mChannelCount],
4665 (framesRead - part1) * mFrameSize);
4666 }
4667 rear = mRsmpInRear += framesRead;
4668
4669 size = activeTracks.size();
4670 // loop over each active track
4671 for (size_t i = 0; i < size; i++) {
4672 activeTrack = activeTracks[i];
4673
4674 enum {
4675 OVERRUN_UNKNOWN,
4676 OVERRUN_TRUE,
4677 OVERRUN_FALSE
4678 } overrun = OVERRUN_UNKNOWN;
4679
4680 // loop over getNextBuffer to handle circular sink
4681 for (;;) {
4682
4683 activeTrack->mSink.frameCount = ~0;
4684 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
4685 size_t framesOut = activeTrack->mSink.frameCount;
4686 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
4687
4688 int32_t front = activeTrack->mRsmpInFront;
4689 ssize_t filled = rear - front;
4690 size_t framesIn;
4691
4692 if (filled < 0) {
4693 // should not happen, but treat like a massive overrun and re-sync
4694 framesIn = 0;
4695 activeTrack->mRsmpInFront = rear;
4696 overrun = OVERRUN_TRUE;
4697 } else if ((size_t) filled <= mRsmpInFramesP2) {
4698 framesIn = (size_t) filled;
4699 } else {
4700 // client is not keeping up with server, but give it latest data
4701 framesIn = mRsmpInFramesP2;
4702 activeTrack->mRsmpInFront = rear - framesIn;
4703 overrun = OVERRUN_TRUE;
4704 }
4705
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08004706 if (framesOut == 0 || framesIn == 0) {
4707 break;
4708 }
4709
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004710 if (activeTrack->mResampler == NULL) {
4711 // no resampling
4712 if (framesIn > framesOut) {
4713 framesIn = framesOut;
4714 } else {
4715 framesOut = framesIn;
4716 }
4717 int8_t *dst = activeTrack->mSink.i8;
4718 while (framesIn > 0) {
4719 front &= mRsmpInFramesP2 - 1;
4720 size_t part1 = mRsmpInFramesP2 - front;
4721 if (part1 > framesIn) {
4722 part1 = framesIn;
4723 }
4724 int8_t *src = (int8_t *)mRsmpInBuffer + (front * mFrameSize);
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08004725 if (mChannelCount == activeTrack->mChannelCount) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004726 memcpy(dst, src, part1 * mFrameSize);
4727 } else if (mChannelCount == 1) {
4728 upmix_to_stereo_i16_from_mono_i16((int16_t *)dst, (int16_t *)src,
4729 part1);
4730 } else {
4731 downmix_to_mono_i16_from_stereo_i16((int16_t *)dst, (int16_t *)src,
4732 part1);
4733 }
4734 dst += part1 * activeTrack->mFrameSize;
4735 front += part1;
4736 framesIn -= part1;
4737 }
4738 activeTrack->mRsmpInFront += framesOut;
4739
4740 } else {
4741 // resampling
4742 // FIXME framesInNeeded should really be part of resampler API, and should
4743 // depend on the SRC ratio
4744 // to keep mRsmpInBuffer full so resampler always has sufficient input
4745 size_t framesInNeeded;
4746 // FIXME only re-calculate when it changes, and optimize for common ratios
4747 double inOverOut = (double) mSampleRate / activeTrack->mSampleRate;
4748 double outOverIn = (double) activeTrack->mSampleRate / mSampleRate;
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08004749 framesInNeeded = ceil(framesOut * inOverOut) + 1;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004750 if (framesIn < framesInNeeded) {
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08004751 ALOGV("not enough to resample: have %u but need %u to produce %u "
4752 "given in/out ratio of %.4g",
4753 framesIn, framesInNeeded, framesOut, inOverOut);
4754 size_t newFramesOut = framesIn > 0 ? floor((framesIn - 1) * outOverIn) : 0;
4755 size_t newFramesInNeeded = ceil(newFramesOut * inOverOut) + 1;
4756 ALOGV("now need %u frames to produce %u given out/in ratio of %.4g",
4757 newFramesInNeeded, newFramesOut, outOverIn);
4758 if (framesIn < newFramesInNeeded) {
4759 ALOGE("failure: have %u but need %u", framesIn, newFramesInNeeded);
4760 framesOut = 0;
4761 } else {
4762 ALOGV("success 2: have %u and need %u to produce %u "
4763 "given in/out ratio of %.4g",
4764 framesIn, newFramesInNeeded, newFramesOut, inOverOut);
4765 LOG_ALWAYS_FATAL_IF(newFramesOut > framesOut);
4766 framesOut = newFramesOut;
4767 }
4768 } else {
4769 ALOGI("success 1: have %u and need %u to produce %u "
4770 "given in/out ratio of %.4g",
4771 framesIn, framesInNeeded, framesOut, inOverOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004772 }
4773
4774 // reallocate mRsmpOutBuffer as needed; we will grow but never shrink
4775 if (activeTrack->mRsmpOutFrameCount < framesOut) {
4776 delete[] activeTrack->mRsmpOutBuffer;
4777 // resampler always outputs stereo
4778 activeTrack->mRsmpOutBuffer = new int32_t[framesOut * FCC_2];
4779 activeTrack->mRsmpOutFrameCount = framesOut;
4780 }
4781
4782 // resampler accumulates, but we only have one source track
4783 memset(activeTrack->mRsmpOutBuffer, 0, framesOut * FCC_2 * sizeof(int32_t));
4784 activeTrack->mResampler->resample(activeTrack->mRsmpOutBuffer, framesOut,
4785 activeTrack->mResamplerBufferProvider
4786 /*this*/ /* AudioBufferProvider* */);
4787 // ditherAndClamp() works as long as all buffers returned by
4788 // activeTrack->getNextBuffer() are 32 bit aligned which should be always true.
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08004789 if (activeTrack->mChannelCount == 1) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004790 // temporarily type pun mRsmpOutBuffer from Q19.12 to int16_t
4791 ditherAndClamp(activeTrack->mRsmpOutBuffer, activeTrack->mRsmpOutBuffer,
4792 framesOut);
4793 // the resampler always outputs stereo samples:
4794 // do post stereo to mono conversion
4795 downmix_to_mono_i16_from_stereo_i16(activeTrack->mSink.i16,
4796 (int16_t *)activeTrack->mRsmpOutBuffer, framesOut);
4797 } else {
4798 ditherAndClamp((int32_t *)activeTrack->mSink.raw,
4799 activeTrack->mRsmpOutBuffer, framesOut);
4800 }
4801 // now done with mRsmpOutBuffer
4802
4803 }
4804
4805 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
4806 overrun = OVERRUN_FALSE;
4807 }
4808
4809 if (activeTrack->mFramesToDrop == 0) {
4810 if (framesOut > 0) {
4811 activeTrack->mSink.frameCount = framesOut;
4812 activeTrack->releaseBuffer(&activeTrack->mSink);
4813 }
4814 } else {
4815 // FIXME could do a partial drop of framesOut
4816 if (activeTrack->mFramesToDrop > 0) {
4817 activeTrack->mFramesToDrop -= framesOut;
4818 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08004819 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004820 }
4821 } else {
4822 activeTrack->mFramesToDrop += framesOut;
4823 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
4824 activeTrack->mSyncStartEvent->isCancelled()) {
4825 ALOGW("Synced record %s, session %d, trigger session %d",
4826 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
4827 activeTrack->sessionId(),
4828 (activeTrack->mSyncStartEvent != 0) ?
4829 activeTrack->mSyncStartEvent->triggerSession() : 0);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08004830 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004831 }
4832 }
4833 }
4834
4835 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004836 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004837 }
4838 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004839
4840 switch (overrun) {
4841 case OVERRUN_TRUE:
4842 // client isn't retrieving buffers fast enough
4843 if (!activeTrack->setOverflow()) {
4844 nsecs_t now = systemTime();
4845 // FIXME should lastWarning per track?
4846 if ((now - lastWarning) > kWarningThrottleNs) {
4847 ALOGW("RecordThread: buffer overflow");
4848 lastWarning = now;
4849 }
4850 }
4851 break;
4852 case OVERRUN_FALSE:
4853 activeTrack->clearOverflow();
4854 break;
4855 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004856 break;
4857 }
4858
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004859 }
4860
Eric Laurent81784c32012-11-19 14:55:58 -08004861 // enable changes in effect chain
4862 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07004863 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08004864 }
4865
Glenn Kasten93e471f2013-08-19 08:40:07 -07004866 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08004867
4868 {
4869 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07004870 for (size_t i = 0; i < mTracks.size(); i++) {
4871 sp<RecordTrack> track = mTracks[i];
4872 track->invalidate();
4873 }
Glenn Kasten2b806402013-11-20 16:37:38 -08004874 mActiveTracks.clear();
4875 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08004876 mStartStopCond.broadcast();
4877 }
4878
4879 releaseWakeLock();
4880
4881 ALOGV("RecordThread %p exiting", this);
4882 return false;
4883}
4884
Glenn Kasten93e471f2013-08-19 08:40:07 -07004885void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08004886{
4887 if (!mStandby) {
4888 inputStandBy();
4889 mStandby = true;
4890 }
4891}
4892
4893void AudioFlinger::RecordThread::inputStandBy()
4894{
4895 mInput->stream->common.standby(&mInput->stream->common);
4896}
4897
Glenn Kastene198c362013-08-13 09:13:36 -07004898sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08004899 const sp<AudioFlinger::Client>& client,
4900 uint32_t sampleRate,
4901 audio_format_t format,
4902 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08004903 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08004904 int sessionId,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004905 int uid,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07004906 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08004907 pid_t tid,
4908 status_t *status)
4909{
Glenn Kasten74935e42013-12-19 08:56:45 -08004910 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08004911 sp<RecordTrack> track;
4912 status_t lStatus;
4913
4914 lStatus = initCheck();
4915 if (lStatus != NO_ERROR) {
Glenn Kastene93cf2c2013-09-24 11:52:37 -07004916 ALOGE("createRecordTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08004917 goto Exit;
4918 }
Glenn Kasten4944acb2013-08-19 08:39:20 -07004919
Glenn Kasten90e58b12013-07-31 16:16:02 -07004920 // client expresses a preference for FAST, but we get the final say
4921 if (*flags & IAudioFlinger::TRACK_FAST) {
4922 if (
4923 // use case: callback handler and frame count is default or at least as large as HAL
4924 (
4925 (tid != -1) &&
4926 ((frameCount == 0) ||
Glenn Kastenb5fed682013-12-03 09:06:43 -08004927 (frameCount >= mFrameCount))
Glenn Kasten90e58b12013-07-31 16:16:02 -07004928 ) &&
4929 // FIXME when record supports non-PCM data, also check for audio_is_linear_pcm(format)
4930 // mono or stereo
4931 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
4932 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
4933 // hardware sample rate
4934 (sampleRate == mSampleRate) &&
4935 // record thread has an associated fast recorder
4936 hasFastRecorder()
4937 // FIXME test that RecordThread for this fast track has a capable output HAL
4938 // FIXME add a permission test also?
4939 ) {
4940 // if frameCount not specified, then it defaults to fast recorder (HAL) frame count
4941 if (frameCount == 0) {
4942 frameCount = mFrameCount * kFastTrackMultiplier;
4943 }
4944 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
4945 frameCount, mFrameCount);
4946 } else {
4947 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%d "
4948 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
4949 "hasFastRecorder=%d tid=%d",
4950 frameCount, mFrameCount, format,
4951 audio_is_linear_pcm(format),
4952 channelMask, sampleRate, mSampleRate, hasFastRecorder(), tid);
4953 *flags &= ~IAudioFlinger::TRACK_FAST;
4954 // For compatibility with AudioRecord calculation, buffer depth is forced
4955 // to be at least 2 x the record thread frame count and cover audio hardware latency.
4956 // This is probably too conservative, but legacy application code may depend on it.
4957 // If you change this calculation, also review the start threshold which is related.
4958 uint32_t latencyMs = 50; // FIXME mInput->stream->get_latency(mInput->stream);
4959 size_t mNormalFrameCount = 2048; // FIXME
4960 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
4961 if (minBufCount < 2) {
4962 minBufCount = 2;
4963 }
4964 size_t minFrameCount = mNormalFrameCount * minBufCount;
4965 if (frameCount < minFrameCount) {
4966 frameCount = minFrameCount;
4967 }
4968 }
4969 }
Glenn Kasten74935e42013-12-19 08:56:45 -08004970 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07004971
Eric Laurent81784c32012-11-19 14:55:58 -08004972 // FIXME use flags and tid similar to createTrack_l()
4973
4974 { // scope for mLock
4975 Mutex::Autolock _l(mLock);
4976
4977 track = new RecordTrack(this, client, sampleRate,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004978 format, channelMask, frameCount, sessionId, uid);
Eric Laurent81784c32012-11-19 14:55:58 -08004979
Glenn Kasten03003332013-08-06 15:40:54 -07004980 lStatus = track->initCheck();
4981 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07004982 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08004983 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08004984 goto Exit;
4985 }
4986 mTracks.add(track);
4987
4988 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4989 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
4990 mAudioFlinger->btNrecIsOff();
4991 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
4992 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07004993
4994 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
4995 pid_t callingPid = IPCThreadState::self()->getCallingPid();
4996 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
4997 // so ask activity manager to do this on our behalf
4998 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
4999 }
Eric Laurent81784c32012-11-19 14:55:58 -08005000 }
5001 lStatus = NO_ERROR;
5002
5003Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07005004 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08005005 return track;
5006}
5007
5008status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
5009 AudioSystem::sync_event_t event,
5010 int triggerSession)
5011{
5012 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
5013 sp<ThreadBase> strongMe = this;
5014 status_t status = NO_ERROR;
5015
5016 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005017 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08005018 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005019 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08005020 triggerSession,
5021 recordTrack->sessionId(),
5022 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005023 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08005024 // Sync event can be cancelled by the trigger session if the track is not in a
5025 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005026 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005027 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08005028 } else {
5029 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005030 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005031 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08005032 }
5033 }
5034
5035 {
Glenn Kasten47c20702013-08-13 15:37:35 -07005036 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08005037 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005038 if (mActiveTracks.indexOf(recordTrack) >= 0) {
5039 if (recordTrack->mState == TrackBase::PAUSING) {
5040 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005041 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005042 } else {
5043 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08005044 }
5045 return status;
5046 }
5047
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005048 // TODO consider other ways of handling this, such as changing the state to :STARTING and
5049 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
5050 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005051 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08005052 mActiveTracks.add(recordTrack);
5053 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08005054 mLock.unlock();
5055 status_t status = AudioSystem::startInput(mId);
5056 mLock.lock();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005057 // FIXME should verify that recordTrack is still in mActiveTracks
Eric Laurent81784c32012-11-19 14:55:58 -08005058 if (status != NO_ERROR) {
Glenn Kasten2b806402013-11-20 16:37:38 -08005059 mActiveTracks.remove(recordTrack);
5060 mActiveTracksGen++;
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005061 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08005062 return status;
5063 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005064 // Catch up with current buffer indices if thread is already running.
5065 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
5066 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
5067 // see previously buffered data before it called start(), but with greater risk of overrun.
5068
5069 recordTrack->mRsmpInFront = mRsmpInRear;
5070 recordTrack->mRsmpInUnrel = 0;
5071 // FIXME why reset?
5072 if (recordTrack->mResampler != NULL) {
5073 recordTrack->mResampler->reset();
Eric Laurent81784c32012-11-19 14:55:58 -08005074 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005075 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08005076 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08005077 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08005078 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005079 ALOGV("Record failed to start");
5080 status = BAD_VALUE;
5081 goto startError;
5082 }
Eric Laurent81784c32012-11-19 14:55:58 -08005083 return status;
5084 }
Glenn Kasten7c027242012-12-26 14:43:16 -08005085
Eric Laurent81784c32012-11-19 14:55:58 -08005086startError:
5087 AudioSystem::stopInput(mId);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005088 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005089 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08005090 return status;
5091}
5092
Eric Laurent81784c32012-11-19 14:55:58 -08005093void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
5094{
5095 sp<SyncEvent> strongEvent = event.promote();
5096
5097 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08005098 sp<RefBase> ptr = strongEvent->cookie().promote();
5099 if (ptr != 0) {
5100 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
5101 recordTrack->handleSyncStartEvent(strongEvent);
5102 }
Eric Laurent81784c32012-11-19 14:55:58 -08005103 }
5104}
5105
Glenn Kastena8356f62013-07-25 14:37:52 -07005106bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08005107 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07005108 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005109 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08005110 return false;
5111 }
Glenn Kasten47c20702013-08-13 15:37:35 -07005112 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08005113 recordTrack->mState = TrackBase::PAUSING;
5114 // do not wait for mStartStopCond if exiting
5115 if (exitPending()) {
5116 return true;
5117 }
Glenn Kasten47c20702013-08-13 15:37:35 -07005118 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08005119 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005120 // if we have been restarted, recordTrack is in mActiveTracks here
5121 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005122 ALOGV("Record stopped OK");
5123 return true;
5124 }
5125 return false;
5126}
5127
Glenn Kasten0f11b512014-01-31 16:18:54 -08005128bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08005129{
5130 return false;
5131}
5132
Glenn Kasten0f11b512014-01-31 16:18:54 -08005133status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005134{
5135#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
5136 if (!isValidSyncEvent(event)) {
5137 return BAD_VALUE;
5138 }
5139
5140 int eventSession = event->triggerSession();
5141 status_t ret = NAME_NOT_FOUND;
5142
5143 Mutex::Autolock _l(mLock);
5144
5145 for (size_t i = 0; i < mTracks.size(); i++) {
5146 sp<RecordTrack> track = mTracks[i];
5147 if (eventSession == track->sessionId()) {
5148 (void) track->setSyncEvent(event);
5149 ret = NO_ERROR;
5150 }
5151 }
5152 return ret;
5153#else
5154 return BAD_VALUE;
5155#endif
5156}
5157
5158// destroyTrack_l() must be called with ThreadBase::mLock held
5159void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
5160{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005161 track->terminate();
5162 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08005163 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08005164 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005165 removeTrack_l(track);
5166 }
5167}
5168
5169void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
5170{
5171 mTracks.remove(track);
5172 // need anything related to effects here?
5173}
5174
5175void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
5176{
5177 dumpInternals(fd, args);
5178 dumpTracks(fd, args);
5179 dumpEffectChains(fd, args);
5180}
5181
5182void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
5183{
Marco Nelissenb2208842014-02-07 14:00:50 -08005184 fdprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08005185
Glenn Kasten2b806402013-11-20 16:37:38 -08005186 if (mActiveTracks.size() > 0) {
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +00005187 fdprintf(fd, " Buffer size: %zu bytes\n", mBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005188 } else {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005189 fdprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08005190 }
5191
Eric Laurent81784c32012-11-19 14:55:58 -08005192 dumpBase(fd, args);
5193}
5194
Glenn Kasten0f11b512014-01-31 16:18:54 -08005195void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005196{
5197 const size_t SIZE = 256;
5198 char buffer[SIZE];
5199 String8 result;
5200
Marco Nelissenb2208842014-02-07 14:00:50 -08005201 size_t numtracks = mTracks.size();
5202 size_t numactive = mActiveTracks.size();
5203 size_t numactiveseen = 0;
5204 fdprintf(fd, " %d Tracks", numtracks);
5205 if (numtracks) {
5206 fdprintf(fd, " of which %d are active\n", numactive);
5207 RecordTrack::appendDumpHeader(result);
5208 for (size_t i = 0; i < numtracks ; ++i) {
5209 sp<RecordTrack> track = mTracks[i];
5210 if (track != 0) {
5211 bool active = mActiveTracks.indexOf(track) >= 0;
5212 if (active) {
5213 numactiveseen++;
5214 }
5215 track->dump(buffer, SIZE, active);
5216 result.append(buffer);
5217 }
Eric Laurent81784c32012-11-19 14:55:58 -08005218 }
Marco Nelissenb2208842014-02-07 14:00:50 -08005219 } else {
5220 fdprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08005221 }
5222
Marco Nelissenb2208842014-02-07 14:00:50 -08005223 if (numactiveseen != numactive) {
5224 snprintf(buffer, SIZE, " The following tracks are in the active list but"
5225 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08005226 result.append(buffer);
5227 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08005228 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08005229 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08005230 if (mTracks.indexOf(track) < 0) {
5231 track->dump(buffer, SIZE, true);
5232 result.append(buffer);
5233 }
Glenn Kasten2b806402013-11-20 16:37:38 -08005234 }
Eric Laurent81784c32012-11-19 14:55:58 -08005235
5236 }
5237 write(fd, result.string(), result.size());
5238}
5239
5240// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005241status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
5242 AudioBufferProvider::Buffer* buffer, int64_t pts __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005243{
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005244 RecordTrack *activeTrack = mRecordTrack;
5245 sp<ThreadBase> threadBase = activeTrack->mThread.promote();
5246 if (threadBase == 0) {
5247 buffer->frameCount = 0;
5248 return NOT_ENOUGH_DATA;
5249 }
5250 RecordThread *recordThread = (RecordThread *) threadBase.get();
5251 int32_t rear = recordThread->mRsmpInRear;
5252 int32_t front = activeTrack->mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07005253 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005254 // FIXME should not be P2 (don't want to increase latency)
5255 // FIXME if client not keeping up, discard
5256 ALOG_ASSERT(0 <= filled && (size_t) filled <= recordThread->mRsmpInFramesP2);
Glenn Kasten85948432013-08-19 12:09:05 -07005257 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005258 front &= recordThread->mRsmpInFramesP2 - 1;
5259 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07005260 if (part1 > (size_t) filled) {
5261 part1 = filled;
5262 }
5263 size_t ask = buffer->frameCount;
5264 ALOG_ASSERT(ask > 0);
5265 if (part1 > ask) {
5266 part1 = ask;
5267 }
5268 if (part1 == 0) {
5269 // Higher-level should keep mRsmpInBuffer full, and not call resampler if empty
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005270 LOG_FATAL("RecordThread::getNextBuffer() starved");
Glenn Kasten85948432013-08-19 12:09:05 -07005271 buffer->raw = NULL;
5272 buffer->frameCount = 0;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005273 activeTrack->mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07005274 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08005275 }
5276
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005277 buffer->raw = recordThread->mRsmpInBuffer + front * recordThread->mChannelCount;
Glenn Kasten85948432013-08-19 12:09:05 -07005278 buffer->frameCount = part1;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005279 activeTrack->mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08005280 return NO_ERROR;
5281}
5282
5283// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005284void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
5285 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08005286{
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005287 RecordTrack *activeTrack = mRecordTrack;
Glenn Kasten85948432013-08-19 12:09:05 -07005288 size_t stepCount = buffer->frameCount;
5289 if (stepCount == 0) {
5290 return;
5291 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005292 ALOG_ASSERT(stepCount <= activeTrack->mRsmpInUnrel);
5293 activeTrack->mRsmpInUnrel -= stepCount;
5294 activeTrack->mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07005295 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08005296 buffer->frameCount = 0;
5297}
5298
5299bool AudioFlinger::RecordThread::checkForNewParameters_l()
5300{
5301 bool reconfig = false;
5302
5303 while (!mNewParameters.isEmpty()) {
5304 status_t status = NO_ERROR;
5305 String8 keyValuePair = mNewParameters[0];
5306 AudioParameter param = AudioParameter(keyValuePair);
5307 int value;
5308 audio_format_t reqFormat = mFormat;
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005309 uint32_t samplingRate = mSampleRate;
5310 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
Eric Laurent81784c32012-11-19 14:55:58 -08005311
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005312 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
5313 // channel count change can be requested. Do we mandate the first client defines the
5314 // HAL sampling rate and channel count or do we allow changes on the fly?
Eric Laurent81784c32012-11-19 14:55:58 -08005315 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005316 samplingRate = value;
Eric Laurent81784c32012-11-19 14:55:58 -08005317 reconfig = true;
5318 }
5319 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten291bb6d2013-07-16 17:23:39 -07005320 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
5321 status = BAD_VALUE;
5322 } else {
5323 reqFormat = (audio_format_t) value;
5324 reconfig = true;
5325 }
Eric Laurent81784c32012-11-19 14:55:58 -08005326 }
5327 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Glenn Kastenec3fb502013-07-17 07:30:58 -07005328 audio_channel_mask_t mask = (audio_channel_mask_t) value;
5329 if (mask != AUDIO_CHANNEL_IN_MONO && mask != AUDIO_CHANNEL_IN_STEREO) {
5330 status = BAD_VALUE;
5331 } else {
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005332 channelMask = mask;
Glenn Kastenec3fb502013-07-17 07:30:58 -07005333 reconfig = true;
5334 }
Eric Laurent81784c32012-11-19 14:55:58 -08005335 }
5336 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5337 // do not accept frame count changes if tracks are open as the track buffer
5338 // size depends on frame count and correct behavior would not be guaranteed
5339 // if frame count is changed after track creation
Glenn Kasten2b806402013-11-20 16:37:38 -08005340 if (mActiveTracks.size() > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005341 status = INVALID_OPERATION;
5342 } else {
5343 reconfig = true;
5344 }
5345 }
5346 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5347 // forward device change to effects that have requested to be
5348 // aware of attached audio device.
5349 for (size_t i = 0; i < mEffectChains.size(); i++) {
5350 mEffectChains[i]->setDevice_l(value);
5351 }
5352
5353 // store input device and output device but do not forward output device to audio HAL.
5354 // Note that status is ignored by the caller for output device
5355 // (see AudioFlinger::setParameters()
5356 if (audio_is_output_devices(value)) {
5357 mOutDevice = value;
5358 status = BAD_VALUE;
5359 } else {
5360 mInDevice = value;
5361 // disable AEC and NS if the device is a BT SCO headset supporting those
5362 // pre processings
5363 if (mTracks.size() > 0) {
5364 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
5365 mAudioFlinger->btNrecIsOff();
5366 for (size_t i = 0; i < mTracks.size(); i++) {
5367 sp<RecordTrack> track = mTracks[i];
5368 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
5369 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
5370 }
5371 }
5372 }
5373 }
5374 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
5375 mAudioSource != (audio_source_t)value) {
5376 // forward device change to effects that have requested to be
5377 // aware of attached audio device.
5378 for (size_t i = 0; i < mEffectChains.size(); i++) {
5379 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
5380 }
5381 mAudioSource = (audio_source_t)value;
5382 }
Glenn Kastene198c362013-08-13 09:13:36 -07005383
Eric Laurent81784c32012-11-19 14:55:58 -08005384 if (status == NO_ERROR) {
5385 status = mInput->stream->common.set_parameters(&mInput->stream->common,
5386 keyValuePair.string());
5387 if (status == INVALID_OPERATION) {
5388 inputStandBy();
5389 status = mInput->stream->common.set_parameters(&mInput->stream->common,
5390 keyValuePair.string());
5391 }
5392 if (reconfig) {
5393 if (status == BAD_VALUE &&
5394 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
5395 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Glenn Kastenc4974312012-12-14 07:13:28 -08005396 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005397 <= (2 * samplingRate)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08005398 popcount(mInput->stream->common.get_channels(&mInput->stream->common))
5399 <= FCC_2 &&
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005400 (channelMask == AUDIO_CHANNEL_IN_MONO ||
5401 channelMask == AUDIO_CHANNEL_IN_STEREO)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005402 status = NO_ERROR;
5403 }
5404 if (status == NO_ERROR) {
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005405 readInputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08005406 sendIoConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
5407 }
5408 }
5409 }
5410
5411 mNewParameters.removeAt(0);
5412
5413 mParamStatus = status;
5414 mParamCond.signal();
5415 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
5416 // already timed out waiting for the status and will never signal the condition.
5417 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
5418 }
5419 return reconfig;
5420}
5421
5422String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
5423{
Eric Laurent81784c32012-11-19 14:55:58 -08005424 Mutex::Autolock _l(mLock);
5425 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07005426 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08005427 }
5428
Glenn Kastend8ea6992013-07-16 14:17:15 -07005429 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
5430 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08005431 free(s);
5432 return out_s8;
5433}
5434
Glenn Kasten0f11b512014-01-31 16:18:54 -08005435void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param __unused) {
Eric Laurent81784c32012-11-19 14:55:58 -08005436 AudioSystem::OutputDescriptor desc;
Glenn Kastenb2737d02013-08-19 12:03:11 -07005437 const void *param2 = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08005438
5439 switch (event) {
5440 case AudioSystem::INPUT_OPENED:
5441 case AudioSystem::INPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07005442 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08005443 desc.samplingRate = mSampleRate;
5444 desc.format = mFormat;
5445 desc.frameCount = mFrameCount;
5446 desc.latency = 0;
5447 param2 = &desc;
5448 break;
5449
5450 case AudioSystem::INPUT_CLOSED:
5451 default:
5452 break;
5453 }
5454 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
5455}
5456
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005457void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08005458{
Eric Laurent81784c32012-11-19 14:55:58 -08005459 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
5460 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07005461 mChannelCount = popcount(mChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08005462 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07005463 if (mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08005464 ALOGE("HAL format %#x not supported; must be AUDIO_FORMAT_PCM_16_BIT", mFormat);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07005465 }
Eric Laurent81784c32012-11-19 14:55:58 -08005466 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Glenn Kasten548efc92012-11-29 08:48:51 -08005467 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
5468 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005469 // This is the formula for calculating the temporary buffer size.
Glenn Kasten85948432013-08-19 12:09:05 -07005470 // With 3 HAL buffers, we can guarantee ability to down-sample the input by ratio of 2:1 to
5471 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005472 // The "3" is somewhat arbitrary, and could probably be larger.
5473 // A larger value should allow more old data to be read after a track calls start(),
5474 // without increasing latency.
Glenn Kasten85948432013-08-19 12:09:05 -07005475 mRsmpInFrames = mFrameCount * 3;
5476 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005477 delete[] mRsmpInBuffer;
Glenn Kasten85948432013-08-19 12:09:05 -07005478 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
5479 mRsmpInBuffer = new int16_t[(mRsmpInFramesP2 + mFrameCount - 1) * mChannelCount];
Eric Laurent81784c32012-11-19 14:55:58 -08005480
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005481 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
5482 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08005483}
5484
Glenn Kasten5f972c02014-01-13 09:59:31 -08005485uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08005486{
5487 Mutex::Autolock _l(mLock);
5488 if (initCheck() != NO_ERROR) {
5489 return 0;
5490 }
5491
5492 return mInput->stream->get_input_frames_lost(mInput->stream);
5493}
5494
5495uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
5496{
5497 Mutex::Autolock _l(mLock);
5498 uint32_t result = 0;
5499 if (getEffectChain_l(sessionId) != 0) {
5500 result = EFFECT_SESSION;
5501 }
5502
5503 for (size_t i = 0; i < mTracks.size(); ++i) {
5504 if (sessionId == mTracks[i]->sessionId()) {
5505 result |= TRACK_SESSION;
5506 break;
5507 }
5508 }
5509
5510 return result;
5511}
5512
5513KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
5514{
5515 KeyedVector<int, bool> ids;
5516 Mutex::Autolock _l(mLock);
5517 for (size_t j = 0; j < mTracks.size(); ++j) {
5518 sp<RecordThread::RecordTrack> track = mTracks[j];
5519 int sessionId = track->sessionId();
5520 if (ids.indexOfKey(sessionId) < 0) {
5521 ids.add(sessionId, true);
5522 }
5523 }
5524 return ids;
5525}
5526
5527AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
5528{
5529 Mutex::Autolock _l(mLock);
5530 AudioStreamIn *input = mInput;
5531 mInput = NULL;
5532 return input;
5533}
5534
5535// this method must always be called either with ThreadBase mLock held or inside the thread loop
5536audio_stream_t* AudioFlinger::RecordThread::stream() const
5537{
5538 if (mInput == NULL) {
5539 return NULL;
5540 }
5541 return &mInput->stream->common;
5542}
5543
5544status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
5545{
5546 // only one chain per input thread
5547 if (mEffectChains.size() != 0) {
5548 return INVALID_OPERATION;
5549 }
5550 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
5551
5552 chain->setInBuffer(NULL);
5553 chain->setOutBuffer(NULL);
5554
5555 checkSuspendOnAddEffectChain_l(chain);
5556
5557 mEffectChains.add(chain);
5558
5559 return NO_ERROR;
5560}
5561
5562size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
5563{
5564 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
5565 ALOGW_IF(mEffectChains.size() != 1,
5566 "removeEffectChain_l() %p invalid chain size %d on thread %p",
5567 chain.get(), mEffectChains.size(), this);
5568 if (mEffectChains.size() == 1) {
5569 mEffectChains.removeAt(0);
5570 }
5571 return 0;
5572}
5573
5574}; // namespace android