blob: cb3db372730daa916a31ec823bf203ba6ff6bd3b [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>
Andy Hungcd044842014-08-07 11:04:34 -070029#include <media/AudioResamplerPublic.h>
Eric Laurent81784c32012-11-19 14:55:58 -080030#include <utils/Log.h>
Alex Ray371eb972012-11-30 11:11:54 -080031#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080032
33#include <private/media/AudioTrackShared.h>
34#include <hardware/audio.h>
35#include <audio_effects/effect_ns.h>
36#include <audio_effects/effect_aec.h>
37#include <audio_utils/primitives.h>
Andy Hung98ef9782014-03-04 14:46:50 -080038#include <audio_utils/format.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070039#include <audio_utils/minifloat.h>
Eric Laurent81784c32012-11-19 14:55:58 -080040
41// NBAIO implementations
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070042#include <media/nbaio/AudioStreamInSource.h>
Eric Laurent81784c32012-11-19 14:55:58 -080043#include <media/nbaio/AudioStreamOutSink.h>
44#include <media/nbaio/MonoPipe.h>
45#include <media/nbaio/MonoPipeReader.h>
46#include <media/nbaio/Pipe.h>
47#include <media/nbaio/PipeReader.h>
48#include <media/nbaio/SourceAudioBufferProvider.h>
49
50#include <powermanager/PowerManager.h>
51
52#include <common_time/cc_helper.h>
53#include <common_time/local_clock.h>
54
55#include "AudioFlinger.h"
56#include "AudioMixer.h"
57#include "FastMixer.h"
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070058#include "FastCapture.h"
Eric Laurent81784c32012-11-19 14:55:58 -080059#include "ServiceUtilities.h"
60#include "SchedulingPolicyService.h"
61
Eric Laurent81784c32012-11-19 14:55:58 -080062#ifdef ADD_BATTERY_DATA
63#include <media/IMediaPlayerService.h>
64#include <media/IMediaDeathNotifier.h>
65#endif
66
Eric Laurent81784c32012-11-19 14:55:58 -080067#ifdef DEBUG_CPU_USAGE
68#include <cpustats/CentralTendencyStatistics.h>
69#include <cpustats/ThreadCpuUsage.h>
70#endif
71
72// ----------------------------------------------------------------------------
73
74// Note: the following macro is used for extremely verbose logging message. In
75// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
76// 0; but one side effect of this is to turn all LOGV's as well. Some messages
77// are so verbose that we want to suppress them even when we have ALOG_ASSERT
78// turned on. Do not uncomment the #def below unless you really know what you
79// are doing and want to see all of the extremely verbose messages.
80//#define VERY_VERY_VERBOSE_LOGGING
81#ifdef VERY_VERY_VERBOSE_LOGGING
82#define ALOGVV ALOGV
83#else
84#define ALOGVV(a...) do { } while(0)
85#endif
86
Glenn Kasten49d00ad2014-07-21 11:22:03 -070087#define max(a, b) ((a) > (b) ? (a) : (b))
88
Eric Laurent81784c32012-11-19 14:55:58 -080089namespace android {
90
91// retry counts for buffer fill timeout
92// 50 * ~20msecs = 1 second
93static const int8_t kMaxTrackRetries = 50;
94static const int8_t kMaxTrackStartupRetries = 50;
95// allow less retry attempts on direct output thread.
96// direct outputs can be a scarce resource in audio hardware and should
97// be released as quickly as possible.
98static const int8_t kMaxTrackRetriesDirect = 2;
99
100// don't warn about blocked writes or record buffer overflows more often than this
101static const nsecs_t kWarningThrottleNs = seconds(5);
102
103// RecordThread loop sleep time upon application overrun or audio HAL read error
104static const int kRecordThreadSleepUs = 5000;
105
Eric Laurent10351942014-05-08 18:49:52 -0700106// maximum time to wait in sendConfigEvent_l() for a status to be received
107static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800108
109// minimum sleep time for the mixer thread loop when tracks are active but in underrun
110static const uint32_t kMinThreadSleepTimeUs = 5000;
111// maximum divider applied to the active sleep time in the mixer thread loop
112static const uint32_t kMaxThreadSleepTimeShift = 2;
113
Andy Hung09a50072014-02-27 14:30:47 -0800114// minimum normal sink buffer size, expressed in milliseconds rather than frames
115static const uint32_t kMinNormalSinkBufferSizeMs = 20;
116// maximum normal sink buffer size
117static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800118
Eric Laurent972a1732013-09-04 09:42:59 -0700119// Offloaded output thread standby delay: allows track transition without going to standby
120static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
121
Eric Laurent81784c32012-11-19 14:55:58 -0800122// Whether to use fast mixer
123static const enum {
124 FastMixer_Never, // never initialize or use: for debugging only
125 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
126 // normal mixer multiplier is 1
127 FastMixer_Static, // initialize if needed, then use all the time if initialized,
128 // multiplier is calculated based on min & max normal mixer buffer size
129 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
130 // multiplier is calculated based on min & max normal mixer buffer size
131 // FIXME for FastMixer_Dynamic:
132 // Supporting this option will require fixing HALs that can't handle large writes.
133 // For example, one HAL implementation returns an error from a large write,
134 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
135 // We could either fix the HAL implementations, or provide a wrapper that breaks
136 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
137} kUseFastMixer = FastMixer_Static;
138
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700139// Whether to use fast capture
140static const enum {
141 FastCapture_Never, // never initialize or use: for debugging only
142 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
143 FastCapture_Static, // initialize if needed, then use all the time if initialized
144} kUseFastCapture = FastCapture_Static;
145
Eric Laurent81784c32012-11-19 14:55:58 -0800146// Priorities for requestPriority
147static const int kPriorityAudioApp = 2;
148static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700149static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800150
151// IAudioFlinger::createTrack() reports back to client the total size of shared memory area
152// for the track. The client then sub-divides this into smaller buffers for its use.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800153// Currently the client uses N-buffering by default, but doesn't tell us about the value of N.
154// So for now we just assume that client is double-buffered for fast tracks.
155// FIXME It would be better for client to tell AudioFlinger the value of N,
156// so AudioFlinger could allocate the right amount of memory.
Eric Laurent81784c32012-11-19 14:55:58 -0800157// See the client's minBufCount and mNotificationFramesAct calculations for details.
Glenn Kasten03490092014-05-27 12:30:54 -0700158
159// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800160static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800161
Glenn Kasten03490092014-05-27 12:30:54 -0700162// The minimum and maximum allowed values
163static const int kFastTrackMultiplierMin = 1;
164static const int kFastTrackMultiplierMax = 2;
165
166// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
167static int sFastTrackMultiplier = kFastTrackMultiplier;
168
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700169// See Thread::readOnlyHeap().
170// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
171// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
172// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Glenn Kasten9f81de32014-07-27 15:02:23 -0700173static const size_t kRecordThreadReadOnlyHeapSize = 0x2000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700174
Eric Laurent81784c32012-11-19 14:55:58 -0800175// ----------------------------------------------------------------------------
176
Glenn Kasten03490092014-05-27 12:30:54 -0700177static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
178
179static void sFastTrackMultiplierInit()
180{
181 char value[PROPERTY_VALUE_MAX];
182 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
183 char *endptr;
184 unsigned long ul = strtoul(value, &endptr, 0);
185 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
186 sFastTrackMultiplier = (int) ul;
187 }
188 }
189}
190
191// ----------------------------------------------------------------------------
192
Eric Laurent81784c32012-11-19 14:55:58 -0800193#ifdef ADD_BATTERY_DATA
194// To collect the amplifier usage
195static void addBatteryData(uint32_t params) {
196 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
197 if (service == NULL) {
198 // it already logged
199 return;
200 }
201
202 service->addBatteryData(params);
203}
204#endif
205
206
207// ----------------------------------------------------------------------------
208// CPU Stats
209// ----------------------------------------------------------------------------
210
211class CpuStats {
212public:
213 CpuStats();
214 void sample(const String8 &title);
215#ifdef DEBUG_CPU_USAGE
216private:
217 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
218 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
219
220 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
221
222 int mCpuNum; // thread's current CPU number
223 int mCpukHz; // frequency of thread's current CPU in kHz
224#endif
225};
226
227CpuStats::CpuStats()
228#ifdef DEBUG_CPU_USAGE
229 : mCpuNum(-1), mCpukHz(-1)
230#endif
231{
232}
233
Glenn Kasten0f11b512014-01-31 16:18:54 -0800234void CpuStats::sample(const String8 &title
235#ifndef DEBUG_CPU_USAGE
236 __unused
237#endif
238 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800239#ifdef DEBUG_CPU_USAGE
240 // get current thread's delta CPU time in wall clock ns
241 double wcNs;
242 bool valid = mCpuUsage.sampleAndEnable(wcNs);
243
244 // record sample for wall clock statistics
245 if (valid) {
246 mWcStats.sample(wcNs);
247 }
248
249 // get the current CPU number
250 int cpuNum = sched_getcpu();
251
252 // get the current CPU frequency in kHz
253 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
254
255 // check if either CPU number or frequency changed
256 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
257 mCpuNum = cpuNum;
258 mCpukHz = cpukHz;
259 // ignore sample for purposes of cycles
260 valid = false;
261 }
262
263 // if no change in CPU number or frequency, then record sample for cycle statistics
264 if (valid && mCpukHz > 0) {
265 double cycles = wcNs * cpukHz * 0.000001;
266 mHzStats.sample(cycles);
267 }
268
269 unsigned n = mWcStats.n();
270 // mCpuUsage.elapsed() is expensive, so don't call it every loop
271 if ((n & 127) == 1) {
272 long long elapsed = mCpuUsage.elapsed();
273 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
274 double perLoop = elapsed / (double) n;
275 double perLoop100 = perLoop * 0.01;
276 double perLoop1k = perLoop * 0.001;
277 double mean = mWcStats.mean();
278 double stddev = mWcStats.stddev();
279 double minimum = mWcStats.minimum();
280 double maximum = mWcStats.maximum();
281 double meanCycles = mHzStats.mean();
282 double stddevCycles = mHzStats.stddev();
283 double minCycles = mHzStats.minimum();
284 double maxCycles = mHzStats.maximum();
285 mCpuUsage.resetElapsed();
286 mWcStats.reset();
287 mHzStats.reset();
288 ALOGD("CPU usage for %s over past %.1f secs\n"
289 " (%u mixer loops at %.1f mean ms per loop):\n"
290 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
291 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
292 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
293 title.string(),
294 elapsed * .000000001, n, perLoop * .000001,
295 mean * .001,
296 stddev * .001,
297 minimum * .001,
298 maximum * .001,
299 mean / perLoop100,
300 stddev / perLoop100,
301 minimum / perLoop100,
302 maximum / perLoop100,
303 meanCycles / perLoop1k,
304 stddevCycles / perLoop1k,
305 minCycles / perLoop1k,
306 maxCycles / perLoop1k);
307
308 }
309 }
310#endif
311};
312
313// ----------------------------------------------------------------------------
314// ThreadBase
315// ----------------------------------------------------------------------------
316
317AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
318 audio_devices_t outDevice, audio_devices_t inDevice, type_t type)
319 : Thread(false /*canCallJava*/),
320 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700321 mAudioFlinger(audioFlinger),
Glenn Kasten70949c42013-08-06 07:40:12 -0700322 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800323 // are set by PlaybackThread::readOutputParameters_l() or
324 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700325 //FIXME: mStandby should be true here. Is this some kind of hack?
Eric Laurent81784c32012-11-19 14:55:58 -0800326 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
327 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
328 // mName will be set by concrete (non-virtual) subclass
329 mDeathRecipient(new PMDeathRecipient(this))
330{
331}
332
333AudioFlinger::ThreadBase::~ThreadBase()
334{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700335 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700336 mConfigEvents.clear();
337
Eric Laurent81784c32012-11-19 14:55:58 -0800338 // do not lock the mutex in destructor
339 releaseWakeLock_l();
340 if (mPowerManager != 0) {
341 sp<IBinder> binder = mPowerManager->asBinder();
342 binder->unlinkToDeath(mDeathRecipient);
343 }
344}
345
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700346status_t AudioFlinger::ThreadBase::readyToRun()
347{
348 status_t status = initCheck();
349 if (status == NO_ERROR) {
350 ALOGI("AudioFlinger's thread %p ready to run", this);
351 } else {
352 ALOGE("No working audio driver found.");
353 }
354 return status;
355}
356
Eric Laurent81784c32012-11-19 14:55:58 -0800357void AudioFlinger::ThreadBase::exit()
358{
359 ALOGV("ThreadBase::exit");
360 // do any cleanup required for exit to succeed
361 preExit();
362 {
363 // This lock prevents the following race in thread (uniprocessor for illustration):
364 // if (!exitPending()) {
365 // // context switch from here to exit()
366 // // exit() calls requestExit(), what exitPending() observes
367 // // exit() calls signal(), which is dropped since no waiters
368 // // context switch back from exit() to here
369 // mWaitWorkCV.wait(...);
370 // // now thread is hung
371 // }
372 AutoMutex lock(mLock);
373 requestExit();
374 mWaitWorkCV.broadcast();
375 }
376 // When Thread::requestExitAndWait is made virtual and this method is renamed to
377 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
378 requestExitAndWait();
379}
380
381status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
382{
383 status_t status;
384
385 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
386 Mutex::Autolock _l(mLock);
387
Eric Laurent10351942014-05-08 18:49:52 -0700388 return sendSetParameterConfigEvent_l(keyValuePairs);
389}
390
391// sendConfigEvent_l() must be called with ThreadBase::mLock held
392// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
393status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
394{
395 status_t status = NO_ERROR;
396
397 mConfigEvents.add(event);
398 ALOGV("sendConfigEvent_l() num events %d event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800399 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700400 mLock.unlock();
401 {
402 Mutex::Autolock _l(event->mLock);
403 while (event->mWaitStatus) {
404 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
405 event->mStatus = TIMED_OUT;
406 event->mWaitStatus = false;
407 }
408 }
409 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800410 }
Eric Laurent10351942014-05-08 18:49:52 -0700411 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800412 return status;
413}
414
415void AudioFlinger::ThreadBase::sendIoConfigEvent(int event, int param)
416{
417 Mutex::Autolock _l(mLock);
418 sendIoConfigEvent_l(event, param);
419}
420
421// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
422void AudioFlinger::ThreadBase::sendIoConfigEvent_l(int event, int param)
423{
Eric Laurent10351942014-05-08 18:49:52 -0700424 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, param);
425 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800426}
427
428// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
429void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
430{
Eric Laurent10351942014-05-08 18:49:52 -0700431 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio);
432 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800433}
434
Eric Laurent10351942014-05-08 18:49:52 -0700435// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
436status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800437{
Eric Laurent10351942014-05-08 18:49:52 -0700438 sp<ConfigEvent> configEvent = (ConfigEvent *)new SetParameterConfigEvent(keyValuePair);
439 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700440}
441
Eric Laurent1c333e22014-05-20 10:48:17 -0700442status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
443 const struct audio_patch *patch,
444 audio_patch_handle_t *handle)
445{
446 Mutex::Autolock _l(mLock);
447 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
448 status_t status = sendConfigEvent_l(configEvent);
449 if (status == NO_ERROR) {
450 CreateAudioPatchConfigEventData *data =
451 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
452 *handle = data->mHandle;
453 }
454 return status;
455}
456
457status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
458 const audio_patch_handle_t handle)
459{
460 Mutex::Autolock _l(mLock);
461 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
462 return sendConfigEvent_l(configEvent);
463}
464
465
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700466// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700467void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700468{
Eric Laurent10351942014-05-08 18:49:52 -0700469 bool configChanged = false;
470
Eric Laurent81784c32012-11-19 14:55:58 -0800471 while (!mConfigEvents.isEmpty()) {
Eric Laurent10351942014-05-08 18:49:52 -0700472 ALOGV("processConfigEvents_l() remaining events %d", mConfigEvents.size());
473 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800474 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700475 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700476 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700477 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
478 // FIXME Need to understand why this has to be done asynchronously
479 int err = requestPriority(data->mPid, data->mTid, data->mPrio,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700480 true /*asynchronous*/);
481 if (err != 0) {
482 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700483 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700484 }
485 } break;
486 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700487 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent021cf962014-05-13 10:18:14 -0700488 audioConfigChanged(data->mEvent, data->mParam);
Eric Laurent10351942014-05-08 18:49:52 -0700489 } break;
490 case CFG_EVENT_SET_PARAMETER: {
491 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
492 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
493 configChanged = true;
Glenn Kastend5418eb2013-08-14 13:11:06 -0700494 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700495 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700496 case CFG_EVENT_CREATE_AUDIO_PATCH: {
497 CreateAudioPatchConfigEventData *data =
498 (CreateAudioPatchConfigEventData *)event->mData.get();
499 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
500 } break;
501 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
502 ReleaseAudioPatchConfigEventData *data =
503 (ReleaseAudioPatchConfigEventData *)event->mData.get();
504 event->mStatus = releaseAudioPatch_l(data->mHandle);
505 } break;
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700506 default:
Eric Laurent10351942014-05-08 18:49:52 -0700507 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700508 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800509 }
Eric Laurent10351942014-05-08 18:49:52 -0700510 {
511 Mutex::Autolock _l(event->mLock);
512 if (event->mWaitStatus) {
513 event->mWaitStatus = false;
514 event->mCond.signal();
515 }
516 }
517 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
518 }
519
520 if (configChanged) {
521 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800522 }
Eric Laurent81784c32012-11-19 14:55:58 -0800523}
524
Marco Nelissenb2208842014-02-07 14:00:50 -0800525String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
526 String8 s;
527 if (output) {
528 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
529 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
530 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
531 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
532 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
533 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
534 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
535 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
536 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
537 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
538 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
539 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
540 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
541 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
542 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
543 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
544 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
545 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
546 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
547 } else {
548 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
549 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
550 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
551 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
552 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
553 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
554 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
555 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
556 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
557 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
558 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
559 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
560 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
561 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
562 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
563 }
564 int len = s.length();
565 if (s.length() > 2) {
566 char *str = s.lockBuffer(len);
567 s.unlockBuffer(len - 2);
568 }
569 return s;
570}
571
Glenn Kasten0f11b512014-01-31 16:18:54 -0800572void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800573{
574 const size_t SIZE = 256;
575 char buffer[SIZE];
576 String8 result;
577
578 bool locked = AudioFlinger::dumpTryLock(mLock);
579 if (!locked) {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700580 dprintf(fd, "thread %p maybe dead locked\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -0800581 }
582
Elliott Hughes87cebad2014-05-22 10:14:43 -0700583 dprintf(fd, " I/O handle: %d\n", mId);
584 dprintf(fd, " TID: %d\n", getTid());
585 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
586 dprintf(fd, " Sample rate: %u\n", mSampleRate);
587 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
588 dprintf(fd, " HAL buffer size: %u bytes\n", mBufferSize);
589 dprintf(fd, " Channel Count: %u\n", mChannelCount);
590 dprintf(fd, " Channel Mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800591 channelMaskToString(mChannelMask, mType != RECORD).string());
Andy Hung463be252014-07-10 16:56:07 -0700592 dprintf(fd, " Format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat));
Elliott Hughes87cebad2014-05-22 10:14:43 -0700593 dprintf(fd, " Frame size: %zu\n", mFrameSize);
594 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800595 size_t numConfig = mConfigEvents.size();
596 if (numConfig) {
597 for (size_t i = 0; i < numConfig; i++) {
598 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700599 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800600 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700601 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800602 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700603 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800604 }
Eric Laurent81784c32012-11-19 14:55:58 -0800605
606 if (locked) {
607 mLock.unlock();
608 }
609}
610
611void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
612{
613 const size_t SIZE = 256;
614 char buffer[SIZE];
615 String8 result;
616
Marco Nelissenb2208842014-02-07 14:00:50 -0800617 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000618 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800619 write(fd, buffer, strlen(buffer));
620
Marco Nelissenb2208842014-02-07 14:00:50 -0800621 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800622 sp<EffectChain> chain = mEffectChains[i];
623 if (chain != 0) {
624 chain->dump(fd, args);
625 }
626 }
627}
628
Marco Nelissene14a5d62013-10-03 08:51:24 -0700629void AudioFlinger::ThreadBase::acquireWakeLock(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800630{
631 Mutex::Autolock _l(mLock);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700632 acquireWakeLock_l(uid);
Eric Laurent81784c32012-11-19 14:55:58 -0800633}
634
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100635String16 AudioFlinger::ThreadBase::getWakeLockTag()
636{
637 switch (mType) {
638 case MIXER:
639 return String16("AudioMix");
640 case DIRECT:
641 return String16("AudioDirectOut");
642 case DUPLICATING:
643 return String16("AudioDup");
644 case RECORD:
645 return String16("AudioIn");
646 case OFFLOAD:
647 return String16("AudioOffload");
648 default:
649 ALOG_ASSERT(false);
650 return String16("AudioUnknown");
651 }
652}
653
Marco Nelissene14a5d62013-10-03 08:51:24 -0700654void AudioFlinger::ThreadBase::acquireWakeLock_l(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800655{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800656 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800657 if (mPowerManager != 0) {
658 sp<IBinder> binder = new BBinder();
Marco Nelissene14a5d62013-10-03 08:51:24 -0700659 status_t status;
660 if (uid >= 0) {
Eric Laurent547789d2013-10-04 11:46:55 -0700661 status = mPowerManager->acquireWakeLockWithUid(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700662 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100663 getWakeLockTag(),
Marco Nelissene14a5d62013-10-03 08:51:24 -0700664 String16("media"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700665 uid,
666 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700667 } else {
Eric Laurent547789d2013-10-04 11:46:55 -0700668 status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700669 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100670 getWakeLockTag(),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700671 String16("media"),
672 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700673 }
Eric Laurent81784c32012-11-19 14:55:58 -0800674 if (status == NO_ERROR) {
675 mWakeLockToken = binder;
676 }
677 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
678 }
679}
680
681void AudioFlinger::ThreadBase::releaseWakeLock()
682{
683 Mutex::Autolock _l(mLock);
684 releaseWakeLock_l();
685}
686
687void AudioFlinger::ThreadBase::releaseWakeLock_l()
688{
689 if (mWakeLockToken != 0) {
690 ALOGV("releaseWakeLock_l() %s", mName);
691 if (mPowerManager != 0) {
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700692 mPowerManager->releaseWakeLock(mWakeLockToken, 0,
693 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800694 }
695 mWakeLockToken.clear();
696 }
697}
698
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800699void AudioFlinger::ThreadBase::updateWakeLockUids(const SortedVector<int> &uids) {
700 Mutex::Autolock _l(mLock);
701 updateWakeLockUids_l(uids);
702}
703
704void AudioFlinger::ThreadBase::getPowerManager_l() {
705
706 if (mPowerManager == 0) {
707 // use checkService() to avoid blocking if power service is not up yet
708 sp<IBinder> binder =
709 defaultServiceManager()->checkService(String16("power"));
710 if (binder == 0) {
711 ALOGW("Thread %s cannot connect to the power manager service", mName);
712 } else {
713 mPowerManager = interface_cast<IPowerManager>(binder);
714 binder->linkToDeath(mDeathRecipient);
715 }
716 }
717}
718
719void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<int> &uids) {
720
721 getPowerManager_l();
722 if (mWakeLockToken == NULL) {
723 ALOGE("no wake lock to update!");
724 return;
725 }
726 if (mPowerManager != 0) {
727 sp<IBinder> binder = new BBinder();
728 status_t status;
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700729 status = mPowerManager->updateWakeLockUids(mWakeLockToken, uids.size(), uids.array(),
730 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800731 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
732 }
733}
734
Eric Laurent81784c32012-11-19 14:55:58 -0800735void AudioFlinger::ThreadBase::clearPowerManager()
736{
737 Mutex::Autolock _l(mLock);
738 releaseWakeLock_l();
739 mPowerManager.clear();
740}
741
Glenn Kasten0f11b512014-01-31 16:18:54 -0800742void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800743{
744 sp<ThreadBase> thread = mThread.promote();
745 if (thread != 0) {
746 thread->clearPowerManager();
747 }
748 ALOGW("power manager service died !!!");
749}
750
751void AudioFlinger::ThreadBase::setEffectSuspended(
752 const effect_uuid_t *type, bool suspend, int sessionId)
753{
754 Mutex::Autolock _l(mLock);
755 setEffectSuspended_l(type, suspend, sessionId);
756}
757
758void AudioFlinger::ThreadBase::setEffectSuspended_l(
759 const effect_uuid_t *type, bool suspend, int sessionId)
760{
761 sp<EffectChain> chain = getEffectChain_l(sessionId);
762 if (chain != 0) {
763 if (type != NULL) {
764 chain->setEffectSuspended_l(type, suspend);
765 } else {
766 chain->setEffectSuspendedAll_l(suspend);
767 }
768 }
769
770 updateSuspendedSessions_l(type, suspend, sessionId);
771}
772
773void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
774{
775 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
776 if (index < 0) {
777 return;
778 }
779
780 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
781 mSuspendedSessions.valueAt(index);
782
783 for (size_t i = 0; i < sessionEffects.size(); i++) {
784 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
785 for (int j = 0; j < desc->mRefCount; j++) {
786 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
787 chain->setEffectSuspendedAll_l(true);
788 } else {
789 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
790 desc->mType.timeLow);
791 chain->setEffectSuspended_l(&desc->mType, true);
792 }
793 }
794 }
795}
796
797void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
798 bool suspend,
799 int sessionId)
800{
801 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
802
803 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
804
805 if (suspend) {
806 if (index >= 0) {
807 sessionEffects = mSuspendedSessions.valueAt(index);
808 } else {
809 mSuspendedSessions.add(sessionId, sessionEffects);
810 }
811 } else {
812 if (index < 0) {
813 return;
814 }
815 sessionEffects = mSuspendedSessions.valueAt(index);
816 }
817
818
819 int key = EffectChain::kKeyForSuspendAll;
820 if (type != NULL) {
821 key = type->timeLow;
822 }
823 index = sessionEffects.indexOfKey(key);
824
825 sp<SuspendedSessionDesc> desc;
826 if (suspend) {
827 if (index >= 0) {
828 desc = sessionEffects.valueAt(index);
829 } else {
830 desc = new SuspendedSessionDesc();
831 if (type != NULL) {
832 desc->mType = *type;
833 }
834 sessionEffects.add(key, desc);
835 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
836 }
837 desc->mRefCount++;
838 } else {
839 if (index < 0) {
840 return;
841 }
842 desc = sessionEffects.valueAt(index);
843 if (--desc->mRefCount == 0) {
844 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
845 sessionEffects.removeItemsAt(index);
846 if (sessionEffects.isEmpty()) {
847 ALOGV("updateSuspendedSessions_l() restore removing session %d",
848 sessionId);
849 mSuspendedSessions.removeItem(sessionId);
850 }
851 }
852 }
853 if (!sessionEffects.isEmpty()) {
854 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
855 }
856}
857
858void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
859 bool enabled,
860 int sessionId)
861{
862 Mutex::Autolock _l(mLock);
863 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
864}
865
866void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
867 bool enabled,
868 int sessionId)
869{
870 if (mType != RECORD) {
871 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
872 // another session. This gives the priority to well behaved effect control panels
873 // and applications not using global effects.
874 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
875 // global effects
876 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
877 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
878 }
879 }
880
881 sp<EffectChain> chain = getEffectChain_l(sessionId);
882 if (chain != 0) {
883 chain->checkSuspendOnEffectEnabled(effect, enabled);
884 }
885}
886
887// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
888sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
889 const sp<AudioFlinger::Client>& client,
890 const sp<IEffectClient>& effectClient,
891 int32_t priority,
892 int sessionId,
893 effect_descriptor_t *desc,
894 int *enabled,
Eric Laurent7da83aa2016-12-01 15:28:29 -0800895 status_t *status,
896 bool pinned)
Eric Laurent81784c32012-11-19 14:55:58 -0800897{
898 sp<EffectModule> effect;
899 sp<EffectHandle> handle;
900 status_t lStatus;
901 sp<EffectChain> chain;
902 bool chainCreated = false;
903 bool effectCreated = false;
904 bool effectRegistered = false;
905
906 lStatus = initCheck();
907 if (lStatus != NO_ERROR) {
908 ALOGW("createEffect_l() Audio driver not initialized.");
909 goto Exit;
910 }
911
Andy Hung98ef9782014-03-04 14:46:50 -0800912 // Reject any effect on Direct output threads for now, since the format of
913 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
914 if (mType == DIRECT) {
915 ALOGW("createEffect_l() Cannot add effect %s on Direct output type thread %s",
916 desc->name, mName);
917 lStatus = BAD_VALUE;
918 goto Exit;
919 }
920
Andy Hung389cfdb2014-08-07 17:49:53 -0700921 // Reject any effect on mixer or duplicating multichannel sinks.
Andy Hung9a592762014-07-21 21:56:01 -0700922 // TODO: fix both format and multichannel issues with effects.
Andy Hung389cfdb2014-08-07 17:49:53 -0700923 if ((mType == MIXER || mType == DUPLICATING) && mChannelCount != FCC_2) {
924 ALOGW("createEffect_l() Cannot add effect %s for multichannel(%d) %s threads",
925 desc->name, mChannelCount, mType == MIXER ? "MIXER" : "DUPLICATING");
Andy Hung9a592762014-07-21 21:56:01 -0700926 lStatus = BAD_VALUE;
927 goto Exit;
928 }
929
Eric Laurent5baf2af2013-09-12 17:37:00 -0700930 // Allow global effects only on offloaded and mixer threads
931 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
932 switch (mType) {
933 case MIXER:
934 case OFFLOAD:
935 break;
936 case DIRECT:
937 case DUPLICATING:
938 case RECORD:
939 default:
940 ALOGW("createEffect_l() Cannot add global effect %s on thread %s", desc->name, mName);
941 lStatus = BAD_VALUE;
942 goto Exit;
943 }
Eric Laurent81784c32012-11-19 14:55:58 -0800944 }
Eric Laurent5baf2af2013-09-12 17:37:00 -0700945
Eric Laurent81784c32012-11-19 14:55:58 -0800946 // Only Pre processor effects are allowed on input threads and only on input threads
947 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
948 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
949 desc->name, desc->flags, mType);
950 lStatus = BAD_VALUE;
951 goto Exit;
952 }
953
954 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
955
956 { // scope for mLock
957 Mutex::Autolock _l(mLock);
958
959 // check for existing effect chain with the requested audio session
960 chain = getEffectChain_l(sessionId);
961 if (chain == 0) {
962 // create a new chain for this session
963 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
964 chain = new EffectChain(this, sessionId);
965 addEffectChain_l(chain);
966 chain->setStrategy(getStrategyForSession_l(sessionId));
967 chainCreated = true;
968 } else {
969 effect = chain->getEffectFromDesc_l(desc);
970 }
971
972 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
973
974 if (effect == 0) {
975 int id = mAudioFlinger->nextUniqueId();
976 // Check CPU and memory usage
977 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
978 if (lStatus != NO_ERROR) {
979 goto Exit;
980 }
981 effectRegistered = true;
982 // create a new effect module if none present in the chain
Eric Laurent7da83aa2016-12-01 15:28:29 -0800983 lStatus = chain->createEffect_l(effect, this, desc, id, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -0800984 if (lStatus != NO_ERROR) {
985 goto Exit;
986 }
987 effectCreated = true;
988
989 effect->setDevice(mOutDevice);
990 effect->setDevice(mInDevice);
991 effect->setMode(mAudioFlinger->getMode());
992 effect->setAudioSource(mAudioSource);
993 }
994 // create effect handle and connect it to effect module
995 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -0800996 lStatus = handle->initCheck();
997 if (lStatus == OK) {
998 lStatus = effect->addHandle(handle.get());
999 }
Eric Laurent81784c32012-11-19 14:55:58 -08001000 if (enabled != NULL) {
1001 *enabled = (int)effect->isEnabled();
1002 }
1003 }
1004
1005Exit:
1006 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1007 Mutex::Autolock _l(mLock);
1008 if (effectCreated) {
1009 chain->removeEffect_l(effect);
1010 }
1011 if (effectRegistered) {
1012 AudioSystem::unregisterEffect(effect->id());
1013 }
1014 if (chainCreated) {
1015 removeEffectChain_l(chain);
1016 }
1017 handle.clear();
1018 }
1019
Glenn Kasten9156ef32013-08-06 15:39:08 -07001020 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001021 return handle;
1022}
1023
Eric Laurent7da83aa2016-12-01 15:28:29 -08001024void AudioFlinger::ThreadBase::disconnectEffectHandle(EffectHandle *handle,
1025 bool unpinIfLast)
1026{
1027 bool remove = false;
1028 sp<EffectModule> effect;
1029 {
1030 Mutex::Autolock _l(mLock);
1031
1032 effect = handle->effect().promote();
1033 if (effect == 0) {
1034 return;
1035 }
1036 // restore suspended effects if the disconnected handle was enabled and the last one.
1037 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1038 if (remove) {
1039 removeEffect_l(effect, true);
1040 }
1041 }
1042 if (remove) {
1043 mAudioFlinger->updateOrphanEffectChains(effect);
1044 AudioSystem::unregisterEffect(effect->id());
1045 if (handle->enabled()) {
1046 checkSuspendOnEffectEnabled(effect, false, effect->sessionId());
1047 }
1048 }
1049}
1050
Eric Laurent81784c32012-11-19 14:55:58 -08001051sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
1052{
1053 Mutex::Autolock _l(mLock);
1054 return getEffect_l(sessionId, effectId);
1055}
1056
1057sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
1058{
1059 sp<EffectChain> chain = getEffectChain_l(sessionId);
1060 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1061}
1062
1063// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1064// PlaybackThread::mLock held
1065status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1066{
1067 // check for existing effect chain with the requested audio session
1068 int sessionId = effect->sessionId();
1069 sp<EffectChain> chain = getEffectChain_l(sessionId);
1070 bool chainCreated = false;
1071
Eric Laurent5baf2af2013-09-12 17:37:00 -07001072 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
1073 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
1074 this, effect->desc().name, effect->desc().flags);
1075
Eric Laurent81784c32012-11-19 14:55:58 -08001076 if (chain == 0) {
1077 // create a new chain for this session
1078 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1079 chain = new EffectChain(this, sessionId);
1080 addEffectChain_l(chain);
1081 chain->setStrategy(getStrategyForSession_l(sessionId));
1082 chainCreated = true;
1083 }
1084 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1085
1086 if (chain->getEffectFromId_l(effect->id()) != 0) {
1087 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1088 this, effect->desc().name, chain.get());
1089 return BAD_VALUE;
1090 }
1091
Eric Laurent5baf2af2013-09-12 17:37:00 -07001092 effect->setOffloaded(mType == OFFLOAD, mId);
1093
Eric Laurent81784c32012-11-19 14:55:58 -08001094 status_t status = chain->addEffect_l(effect);
1095 if (status != NO_ERROR) {
1096 if (chainCreated) {
1097 removeEffectChain_l(chain);
1098 }
1099 return status;
1100 }
1101
1102 effect->setDevice(mOutDevice);
1103 effect->setDevice(mInDevice);
1104 effect->setMode(mAudioFlinger->getMode());
1105 effect->setAudioSource(mAudioSource);
1106 return NO_ERROR;
1107}
1108
Eric Laurent7da83aa2016-12-01 15:28:29 -08001109void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001110
Eric Laurent7da83aa2016-12-01 15:28:29 -08001111 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001112 effect_descriptor_t desc = effect->desc();
1113 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1114 detachAuxEffect_l(effect->id());
1115 }
1116
1117 sp<EffectChain> chain = effect->chain().promote();
1118 if (chain != 0) {
1119 // remove effect chain if removing last effect
Eric Laurent7da83aa2016-12-01 15:28:29 -08001120 if (chain->removeEffect_l(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001121 removeEffectChain_l(chain);
1122 }
1123 } else {
1124 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1125 }
1126}
1127
1128void AudioFlinger::ThreadBase::lockEffectChains_l(
1129 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1130{
1131 effectChains = mEffectChains;
1132 for (size_t i = 0; i < mEffectChains.size(); i++) {
1133 mEffectChains[i]->lock();
1134 }
1135}
1136
1137void AudioFlinger::ThreadBase::unlockEffectChains(
1138 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1139{
1140 for (size_t i = 0; i < effectChains.size(); i++) {
1141 effectChains[i]->unlock();
1142 }
1143}
1144
1145sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
1146{
1147 Mutex::Autolock _l(mLock);
1148 return getEffectChain_l(sessionId);
1149}
1150
1151sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const
1152{
1153 size_t size = mEffectChains.size();
1154 for (size_t i = 0; i < size; i++) {
1155 if (mEffectChains[i]->sessionId() == sessionId) {
1156 return mEffectChains[i];
1157 }
1158 }
1159 return 0;
1160}
1161
1162void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1163{
1164 Mutex::Autolock _l(mLock);
1165 size_t size = mEffectChains.size();
1166 for (size_t i = 0; i < size; i++) {
1167 mEffectChains[i]->setMode_l(mode);
1168 }
1169}
1170
Eric Laurent83b88082014-06-20 18:31:16 -07001171void AudioFlinger::ThreadBase::getAudioPortConfig(struct audio_port_config *config)
1172{
1173 config->type = AUDIO_PORT_TYPE_MIX;
1174 config->ext.mix.handle = mId;
1175 config->sample_rate = mSampleRate;
1176 config->format = mFormat;
1177 config->channel_mask = mChannelMask;
1178 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1179 AUDIO_PORT_CONFIG_FORMAT;
1180}
1181
1182
Eric Laurent81784c32012-11-19 14:55:58 -08001183// ----------------------------------------------------------------------------
1184// Playback
1185// ----------------------------------------------------------------------------
1186
1187AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1188 AudioStreamOut* output,
1189 audio_io_handle_t id,
1190 audio_devices_t device,
1191 type_t type)
1192 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type),
Andy Hung2098f272014-02-27 14:00:06 -08001193 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001194 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001195 mMixerBuffer(NULL),
1196 mMixerBufferSize(0),
1197 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1198 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001199 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001200 mEffectBuffer(NULL),
1201 mEffectBufferSize(0),
1202 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1203 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001204 mSuspended(0), mBytesWritten(0),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001205 mActiveTracksGeneration(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001206 // mStreamTypes[] initialized in constructor body
1207 mOutput(output),
1208 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
1209 mMixerStatus(MIXER_IDLE),
1210 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
1211 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001212 mBytesRemaining(0),
1213 mCurrentWriteLength(0),
1214 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001215 mWriteAckSequence(0),
1216 mDrainSequence(0),
Eric Laurentede6c3b2013-09-19 14:37:46 -07001217 mSignalPending(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001218 mScreenState(AudioFlinger::mScreenState),
1219 // index 0 is reserved for normal mixer's submix
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001220 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1),
Eric Laurentd1f69b02014-12-15 14:33:13 -08001221 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001222 // mLatchD, mLatchQ,
1223 mLatchDValid(false), mLatchQValid(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001224{
1225 snprintf(mName, kNameLength, "AudioOut_%X", id);
Glenn Kasten9e58b552013-01-18 15:09:48 -08001226 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mName);
Eric Laurent81784c32012-11-19 14:55:58 -08001227
1228 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1229 // it would be safer to explicitly pass initial masterVolume/masterMute as
1230 // parameter.
1231 //
1232 // If the HAL we are using has support for master volume or master mute,
1233 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1234 // and the mute set to false).
1235 mMasterVolume = audioFlinger->masterVolume_l();
1236 mMasterMute = audioFlinger->masterMute_l();
1237 if (mOutput && mOutput->audioHwDev) {
1238 if (mOutput->audioHwDev->canSetMasterVolume()) {
1239 mMasterVolume = 1.0;
1240 }
1241
1242 if (mOutput->audioHwDev->canSetMasterMute()) {
1243 mMasterMute = false;
1244 }
1245 }
1246
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001247 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001248
Eric Laurent223fd5c2014-11-11 13:43:36 -08001249 // ++ operator does not compile
Glenn Kasten66e46352014-01-16 17:44:23 -08001250 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001251 stream = (audio_stream_type_t) (stream + 1)) {
1252 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1253 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1254 }
Eric Laurent81784c32012-11-19 14:55:58 -08001255}
1256
1257AudioFlinger::PlaybackThread::~PlaybackThread()
1258{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001259 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001260 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001261 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001262 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001263}
1264
1265void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1266{
1267 dumpInternals(fd, args);
1268 dumpTracks(fd, args);
1269 dumpEffectChains(fd, args);
1270}
1271
Glenn Kasten0f11b512014-01-31 16:18:54 -08001272void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001273{
1274 const size_t SIZE = 256;
1275 char buffer[SIZE];
1276 String8 result;
1277
Marco Nelissenb2208842014-02-07 14:00:50 -08001278 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001279 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1280 const stream_type_t *st = &mStreamTypes[i];
1281 if (i > 0) {
1282 result.appendFormat(", ");
1283 }
1284 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1285 if (st->mute) {
1286 result.append("M");
1287 }
1288 }
1289 result.append("\n");
1290 write(fd, result.string(), result.length());
1291 result.clear();
1292
Eric Laurent81784c32012-11-19 14:55:58 -08001293 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1294 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001295 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001296 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001297
1298 size_t numtracks = mTracks.size();
1299 size_t numactive = mActiveTracks.size();
Elliott Hughes87cebad2014-05-22 10:14:43 -07001300 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001301 size_t numactiveseen = 0;
1302 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07001303 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08001304 Track::appendDumpHeader(result);
1305 for (size_t i = 0; i < numtracks; ++i) {
1306 sp<Track> track = mTracks[i];
1307 if (track != 0) {
1308 bool active = mActiveTracks.indexOf(track) >= 0;
1309 if (active) {
1310 numactiveseen++;
1311 }
1312 track->dump(buffer, SIZE, active);
1313 result.append(buffer);
1314 }
1315 }
1316 } else {
1317 result.append("\n");
1318 }
1319 if (numactiveseen != numactive) {
1320 // some tracks in the active list were not in the tracks list
1321 snprintf(buffer, SIZE, " The following tracks are in the active list but"
1322 " not in the track list\n");
1323 result.append(buffer);
1324 Track::appendDumpHeader(result);
1325 for (size_t i = 0; i < numactive; ++i) {
1326 sp<Track> track = mActiveTracks[i].promote();
1327 if (track != 0 && mTracks.indexOf(track) < 0) {
1328 track->dump(buffer, SIZE, true);
1329 result.append(buffer);
1330 }
1331 }
1332 }
1333
1334 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001335}
1336
1337void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1338{
Elliott Hughes87cebad2014-05-22 10:14:43 -07001339 dprintf(fd, "\nOutput thread %p:\n", this);
1340 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
1341 dprintf(fd, " Last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1342 dprintf(fd, " Total writes: %d\n", mNumWrites);
1343 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1344 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1345 dprintf(fd, " Suspend count: %d\n", mSuspended);
1346 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1347 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1348 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1349 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent81784c32012-11-19 14:55:58 -08001350
1351 dumpBase(fd, args);
1352}
1353
1354// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001355
1356void AudioFlinger::PlaybackThread::onFirstRef()
1357{
1358 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
1359}
1360
1361// ThreadBase virtuals
1362void AudioFlinger::PlaybackThread::preExit()
1363{
1364 ALOGV(" preExit()");
1365 // FIXME this is using hard-coded strings but in the future, this functionality will be
1366 // converted to use audio HAL extensions required to support tunneling
1367 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1368}
1369
1370// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1371sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1372 const sp<AudioFlinger::Client>& client,
1373 audio_stream_type_t streamType,
1374 uint32_t sampleRate,
1375 audio_format_t format,
1376 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001377 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001378 const sp<IMemory>& sharedBuffer,
1379 int sessionId,
1380 IAudioFlinger::track_flags_t *flags,
1381 pid_t tid,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001382 int uid,
Eric Laurent81784c32012-11-19 14:55:58 -08001383 status_t *status)
1384{
Glenn Kasten74935e42013-12-19 08:56:45 -08001385 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001386 sp<Track> track;
1387 status_t lStatus;
1388
1389 bool isTimed = (*flags & IAudioFlinger::TRACK_TIMED) != 0;
1390
1391 // client expresses a preference for FAST, but we get the final say
1392 if (*flags & IAudioFlinger::TRACK_FAST) {
1393 if (
1394 // not timed
1395 (!isTimed) &&
1396 // either of these use cases:
1397 (
1398 // use case 1: shared buffer with any frame count
1399 (
1400 (sharedBuffer != 0)
1401 ) ||
1402 // use case 2: callback handler and frame count is default or at least as large as HAL
1403 (
1404 (tid != -1) &&
1405 ((frameCount == 0) ||
Glenn Kastenb5fed682013-12-03 09:06:43 -08001406 (frameCount >= mFrameCount))
Eric Laurent81784c32012-11-19 14:55:58 -08001407 )
1408 ) &&
1409 // PCM data
1410 audio_is_linear_pcm(format) &&
Andy Hung9a592762014-07-21 21:56:01 -07001411 // identical channel mask to sink, or mono in and stereo sink
1412 (channelMask == mChannelMask ||
1413 (channelMask == AUDIO_CHANNEL_OUT_MONO &&
1414 mChannelMask == AUDIO_CHANNEL_OUT_STEREO)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001415 // hardware sample rate
1416 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001417 // normal mixer has an associated fast mixer
1418 hasFastMixer() &&
1419 // there are sufficient fast track slots available
1420 (mFastTrackAvailMask != 0)
1421 // FIXME test that MixerThread for this fast track has a capable output HAL
1422 // FIXME add a permission test also?
1423 ) {
1424 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1425 if (frameCount == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001426 // read the fast track multiplier property the first time it is needed
1427 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1428 if (ok != 0) {
1429 ALOGE("%s pthread_once failed: %d", __func__, ok);
1430 }
1431 frameCount = mFrameCount * sFastTrackMultiplier;
Eric Laurent81784c32012-11-19 14:55:58 -08001432 }
1433 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
1434 frameCount, mFrameCount);
1435 } else {
1436 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
Andy Hung6146c082014-03-18 11:56:15 -07001437 "mFrameCount=%d format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
1438 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001439 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Andy Hung6146c082014-03-18 11:56:15 -07001440 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001441 audio_is_linear_pcm(format),
1442 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
1443 *flags &= ~IAudioFlinger::TRACK_FAST;
1444 // For compatibility with AudioTrack calculation, buffer depth is forced
1445 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1446 // This is probably too conservative, but legacy application code may depend on it.
1447 // If you change this calculation, also review the start threshold which is related.
1448 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1449 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1450 if (minBufCount < 2) {
1451 minBufCount = 2;
1452 }
1453 size_t minFrameCount = mNormalFrameCount * minBufCount;
1454 if (frameCount < minFrameCount) {
1455 frameCount = minFrameCount;
1456 }
1457 }
1458 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001459 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001460
Glenn Kastenc3df8382014-03-13 15:05:25 -07001461 switch (mType) {
1462
1463 case DIRECT:
Glenn Kasten993fa062014-05-02 11:14:34 -07001464 if (audio_is_linear_pcm(format)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001465 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001466 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1467 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001468 sampleRate, format, channelMask, mOutput, mFormat);
1469 lStatus = BAD_VALUE;
1470 goto Exit;
1471 }
1472 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001473 break;
1474
1475 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001476 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001477 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1478 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001479 sampleRate, format, channelMask, mOutput, mFormat);
1480 lStatus = BAD_VALUE;
1481 goto Exit;
1482 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001483 break;
1484
1485 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07001486 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001487 ALOGE("createTrack_l() Bad parameter: format %#x \""
1488 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001489 format, mOutput, mFormat);
1490 lStatus = BAD_VALUE;
1491 goto Exit;
1492 }
Andy Hungcd044842014-08-07 11:04:34 -07001493 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08001494 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1495 lStatus = BAD_VALUE;
1496 goto Exit;
1497 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001498 break;
1499
Eric Laurent81784c32012-11-19 14:55:58 -08001500 }
1501
1502 lStatus = initCheck();
1503 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07001504 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08001505 goto Exit;
1506 }
1507
1508 { // scope for mLock
1509 Mutex::Autolock _l(mLock);
1510
1511 // all tracks in same audio session must share the same routing strategy otherwise
1512 // conflicts will happen when tracks are moved from one output to another by audio policy
1513 // manager
1514 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1515 for (size_t i = 0; i < mTracks.size(); ++i) {
1516 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07001517 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001518 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1519 if (sessionId == t->sessionId() && strategy != actual) {
1520 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1521 strategy, actual);
1522 lStatus = BAD_VALUE;
1523 goto Exit;
1524 }
1525 }
1526 }
1527
1528 if (!isTimed) {
1529 track = new Track(this, client, streamType, sampleRate, format,
Eric Laurent83b88082014-06-20 18:31:16 -07001530 channelMask, frameCount, NULL, sharedBuffer,
1531 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08001532 } else {
1533 track = TimedTrack::create(this, client, streamType, sampleRate, format,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001534 channelMask, frameCount, sharedBuffer, sessionId, uid);
Eric Laurent81784c32012-11-19 14:55:58 -08001535 }
Glenn Kasten03003332013-08-06 15:40:54 -07001536
1537 // new Track always returns non-NULL,
1538 // but TimedTrack::create() is a factory that could fail by returning NULL
1539 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
1540 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08001541 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001542 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08001543 goto Exit;
1544 }
1545 mTracks.add(track);
1546
1547 sp<EffectChain> chain = getEffectChain_l(sessionId);
1548 if (chain != 0) {
1549 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1550 track->setMainBuffer(chain->inBuffer());
1551 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1552 chain->incTrackCnt();
1553 }
1554
1555 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1556 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1557 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1558 // so ask activity manager to do this on our behalf
1559 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1560 }
1561 }
1562
1563 lStatus = NO_ERROR;
1564
1565Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001566 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001567 return track;
1568}
1569
1570uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1571{
1572 return latency;
1573}
1574
1575uint32_t AudioFlinger::PlaybackThread::latency() const
1576{
1577 Mutex::Autolock _l(mLock);
1578 return latency_l();
1579}
1580uint32_t AudioFlinger::PlaybackThread::latency_l() const
1581{
1582 if (initCheck() == NO_ERROR) {
1583 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
1584 } else {
1585 return 0;
1586 }
1587}
1588
1589void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1590{
1591 Mutex::Autolock _l(mLock);
1592 // Don't apply master volume in SW if our HAL can do it for us.
1593 if (mOutput && mOutput->audioHwDev &&
1594 mOutput->audioHwDev->canSetMasterVolume()) {
1595 mMasterVolume = 1.0;
1596 } else {
1597 mMasterVolume = value;
1598 }
1599}
1600
1601void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1602{
1603 Mutex::Autolock _l(mLock);
1604 // Don't apply master mute in SW if our HAL can do it for us.
1605 if (mOutput && mOutput->audioHwDev &&
1606 mOutput->audioHwDev->canSetMasterMute()) {
1607 mMasterMute = false;
1608 } else {
1609 mMasterMute = muted;
1610 }
1611}
1612
1613void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
1614{
1615 Mutex::Autolock _l(mLock);
1616 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001617 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001618}
1619
1620void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
1621{
1622 Mutex::Autolock _l(mLock);
1623 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001624 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001625}
1626
1627float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
1628{
1629 Mutex::Autolock _l(mLock);
1630 return mStreamTypes[stream].volume;
1631}
1632
1633// addTrack_l() must be called with ThreadBase::mLock held
1634status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1635{
1636 status_t status = ALREADY_EXISTS;
1637
1638 // set retry count for buffer fill
1639 track->mRetryCount = kMaxTrackStartupRetries;
1640 if (mActiveTracks.indexOf(track) < 0) {
1641 // the track is newly added, make sure it fills up all its
1642 // buffers before playing. This is to ensure the client will
1643 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07001644 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001645 TrackBase::track_state state = track->mState;
1646 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08001647 status = AudioSystem::startOutput(mId, track->streamType(),
1648 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001649 mLock.lock();
1650 // abort track was stopped/paused while we released the lock
1651 if (state != track->mState) {
1652 if (status == NO_ERROR) {
1653 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08001654 AudioSystem::stopOutput(mId, track->streamType(),
1655 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001656 mLock.lock();
1657 }
1658 return INVALID_OPERATION;
1659 }
1660 // abort if start is rejected by audio policy manager
1661 if (status != NO_ERROR) {
1662 return PERMISSION_DENIED;
1663 }
1664#ifdef ADD_BATTERY_DATA
1665 // to track the speaker usage
1666 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
1667#endif
1668 }
1669
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001670 track->mFillingUpStatus = track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent81784c32012-11-19 14:55:58 -08001671 track->mResetDone = false;
1672 track->mPresentationCompleteFrames = 0;
1673 mActiveTracks.add(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001674 mWakeLockUids.add(track->uid());
1675 mActiveTracksGeneration++;
Eric Laurentfd477972013-10-25 18:10:40 -07001676 mLatestActiveTrack = track;
Eric Laurentd0107bc2013-06-11 14:38:48 -07001677 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1678 if (chain != 0) {
1679 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
1680 track->sessionId());
1681 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08001682 }
1683
1684 status = NO_ERROR;
1685 }
1686
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08001687 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001688 return status;
1689}
1690
Eric Laurentbfb1b832013-01-07 09:53:42 -08001691bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08001692{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001693 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08001694 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001695 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
1696 track->mState = TrackBase::STOPPED;
1697 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08001698 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07001699 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001700 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08001701 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001702
1703 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08001704}
1705
1706void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1707{
1708 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
1709 mTracks.remove(track);
1710 deleteTrackName_l(track->name());
1711 // redundant as track is about to be destroyed, for dumpsys only
1712 track->mName = -1;
1713 if (track->isFastTrack()) {
1714 int index = track->mFastIndex;
1715 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
1716 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1717 mFastTrackAvailMask |= 1 << index;
1718 // redundant as track is about to be destroyed, for dumpsys only
1719 track->mFastIndex = -1;
1720 }
1721 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1722 if (chain != 0) {
1723 chain->decTrackCnt();
1724 }
1725}
1726
Eric Laurentede6c3b2013-09-19 14:37:46 -07001727void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001728{
1729 // Thread could be blocked waiting for async
1730 // so signal it to handle state changes immediately
1731 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1732 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1733 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001734 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001735}
1736
Eric Laurent81784c32012-11-19 14:55:58 -08001737String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1738{
Eric Laurent81784c32012-11-19 14:55:58 -08001739 Mutex::Autolock _l(mLock);
1740 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07001741 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08001742 }
1743
Glenn Kastend8ea6992013-07-16 14:17:15 -07001744 char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
1745 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08001746 free(s);
1747 return out_s8;
1748}
1749
Eric Laurent021cf962014-05-13 10:18:14 -07001750void AudioFlinger::PlaybackThread::audioConfigChanged(int event, int param) {
Eric Laurent81784c32012-11-19 14:55:58 -08001751 AudioSystem::OutputDescriptor desc;
1752 void *param2 = NULL;
1753
Eric Laurent021cf962014-05-13 10:18:14 -07001754 ALOGV("PlaybackThread::audioConfigChanged, thread %p, event %d, param %d", this, event,
Eric Laurent81784c32012-11-19 14:55:58 -08001755 param);
1756
1757 switch (event) {
1758 case AudioSystem::OUTPUT_OPENED:
1759 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07001760 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08001761 desc.samplingRate = mSampleRate;
1762 desc.format = mFormat;
1763 desc.frameCount = mNormalFrameCount; // FIXME see
1764 // AudioFlinger::frameCount(audio_io_handle_t)
Eric Laurent10351942014-05-08 18:49:52 -07001765 desc.latency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001766 param2 = &desc;
1767 break;
1768
1769 case AudioSystem::STREAM_CONFIG_CHANGED:
1770 param2 = &param;
1771 case AudioSystem::OUTPUT_CLOSED:
1772 default:
1773 break;
1774 }
Eric Laurent021cf962014-05-13 10:18:14 -07001775 mAudioFlinger->audioConfigChanged(event, mId, param2);
Eric Laurent81784c32012-11-19 14:55:58 -08001776}
1777
Eric Laurentbfb1b832013-01-07 09:53:42 -08001778void AudioFlinger::PlaybackThread::writeCallback()
1779{
1780 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001781 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001782}
1783
1784void AudioFlinger::PlaybackThread::drainCallback()
1785{
1786 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001787 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001788}
1789
Eric Laurent3b4529e2013-09-05 18:09:19 -07001790void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001791{
1792 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001793 // reject out of sequence requests
1794 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
1795 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001796 mWaitWorkCV.signal();
1797 }
1798}
1799
Eric Laurent3b4529e2013-09-05 18:09:19 -07001800void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001801{
1802 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001803 // reject out of sequence requests
1804 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
1805 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001806 mWaitWorkCV.signal();
1807 }
1808}
1809
1810// static
1811int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
Glenn Kasten0f11b512014-01-31 16:18:54 -08001812 void *param __unused,
Eric Laurentbfb1b832013-01-07 09:53:42 -08001813 void *cookie)
1814{
1815 AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
1816 ALOGV("asyncCallback() event %d", event);
1817 switch (event) {
1818 case STREAM_CBK_EVENT_WRITE_READY:
1819 me->writeCallback();
1820 break;
1821 case STREAM_CBK_EVENT_DRAIN_READY:
1822 me->drainCallback();
1823 break;
1824 default:
1825 ALOGW("asyncCallback() unknown event %d", event);
1826 break;
1827 }
1828 return 0;
1829}
1830
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001831void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001832{
Glenn Kastenadad3d72014-02-21 14:51:43 -08001833 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Eric Laurent81784c32012-11-19 14:55:58 -08001834 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
1835 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001836 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08001837 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001838 }
Andy Hung9a592762014-07-21 21:56:01 -07001839 if ((mType == MIXER || mType == DUPLICATING)
1840 && !isValidPcmSinkChannelMask(mChannelMask)) {
1841 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
1842 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001843 }
Andy Hunge5412692014-05-16 11:25:07 -07001844 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Andy Hung463be252014-07-10 16:56:07 -07001845 mHALFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
1846 mFormat = mHALFormat;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001847 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08001848 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001849 }
Andy Hung6146c082014-03-18 11:56:15 -07001850 if ((mType == MIXER || mType == DUPLICATING)
1851 && !isValidPcmSinkFormat(mFormat)) {
1852 LOG_FATAL("HAL format %#x not supported for mixed output",
1853 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001854 }
Eric Laurent665470b2014-07-03 16:37:08 -07001855 mFrameSize = audio_stream_out_frame_size(mOutput->stream);
Glenn Kasten70949c42013-08-06 07:40:12 -07001856 mBufferSize = mOutput->stream->common.get_buffer_size(&mOutput->stream->common);
1857 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08001858 if (mFrameCount & 15) {
1859 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
1860 mFrameCount);
1861 }
1862
Eric Laurentbfb1b832013-01-07 09:53:42 -08001863 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
1864 (mOutput->stream->set_callback != NULL)) {
1865 if (mOutput->stream->set_callback(mOutput->stream,
1866 AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
1867 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07001868 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001869 }
1870 }
1871
Eric Laurentd1f69b02014-12-15 14:33:13 -08001872 mHwSupportsPause = false;
1873 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
1874 if (mOutput->stream->pause != NULL) {
1875 if (mOutput->stream->resume != NULL) {
1876 mHwSupportsPause = true;
1877 } else {
1878 ALOGW("direct output implements pause but not resume");
1879 }
1880 } else if (mOutput->stream->resume != NULL) {
1881 ALOGW("direct output implements resume but not pause");
1882 }
1883 }
1884
Andy Hung09a50072014-02-27 14:30:47 -08001885 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08001886 double multiplier = 1.0;
1887 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
1888 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08001889 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
1890 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Eric Laurent81784c32012-11-19 14:55:58 -08001891 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
1892 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
1893 maxNormalFrameCount = maxNormalFrameCount & ~15;
1894 if (maxNormalFrameCount < minNormalFrameCount) {
1895 maxNormalFrameCount = minNormalFrameCount;
1896 }
1897 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
1898 if (multiplier <= 1.0) {
1899 multiplier = 1.0;
1900 } else if (multiplier <= 2.0) {
1901 if (2 * mFrameCount <= maxNormalFrameCount) {
1902 multiplier = 2.0;
1903 } else {
1904 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
1905 }
1906 } else {
1907 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
Andy Hung09a50072014-02-27 14:30:47 -08001908 // SRC (it would be unusual for the normal sink buffer size to not be a multiple of fast
Eric Laurent81784c32012-11-19 14:55:58 -08001909 // track, but we sometimes have to do this to satisfy the maximum frame count
1910 // constraint)
1911 // FIXME this rounding up should not be done if no HAL SRC
1912 uint32_t truncMult = (uint32_t) multiplier;
1913 if ((truncMult & 1)) {
1914 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
1915 ++truncMult;
1916 }
1917 }
1918 multiplier = (double) truncMult;
1919 }
1920 }
1921 mNormalFrameCount = multiplier * mFrameCount;
1922 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07001923 if (mType == MIXER || mType == DUPLICATING) {
1924 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
1925 }
Andy Hung09a50072014-02-27 14:30:47 -08001926 ALOGI("HAL output buffer size %u frames, normal sink buffer size %u frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001927 mNormalFrameCount);
1928
Andy Hung010a1a12014-03-13 13:57:33 -07001929 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
1930 // Originally this was int16_t[] array, need to remove legacy implications.
1931 free(mSinkBuffer);
1932 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07001933 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
1934 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
1935 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07001936 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08001937
Andy Hung69aed5f2014-02-25 17:24:40 -08001938 // We resize the mMixerBuffer according to the requirements of the sink buffer which
1939 // drives the output.
1940 free(mMixerBuffer);
1941 mMixerBuffer = NULL;
1942 if (mMixerBufferEnabled) {
1943 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
1944 mMixerBufferSize = mNormalFrameCount * mChannelCount
1945 * audio_bytes_per_sample(mMixerBufferFormat);
1946 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
1947 }
Andy Hung98ef9782014-03-04 14:46:50 -08001948 free(mEffectBuffer);
1949 mEffectBuffer = NULL;
1950 if (mEffectBufferEnabled) {
1951 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
1952 mEffectBufferSize = mNormalFrameCount * mChannelCount
1953 * audio_bytes_per_sample(mEffectBufferFormat);
1954 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
1955 }
Andy Hung69aed5f2014-02-25 17:24:40 -08001956
Eric Laurent81784c32012-11-19 14:55:58 -08001957 // force reconfiguration of effect chains and engines to take new buffer size and audio
1958 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001959 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08001960 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1961 // matter.
1962 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1963 Vector< sp<EffectChain> > effectChains = mEffectChains;
1964 for (size_t i = 0; i < effectChains.size(); i ++) {
1965 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
1966 }
1967}
1968
1969
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001970status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08001971{
1972 if (halFrames == NULL || dspFrames == NULL) {
1973 return BAD_VALUE;
1974 }
1975 Mutex::Autolock _l(mLock);
1976 if (initCheck() != NO_ERROR) {
1977 return INVALID_OPERATION;
1978 }
1979 size_t framesWritten = mBytesWritten / mFrameSize;
1980 *halFrames = framesWritten;
1981
1982 if (isSuspended()) {
1983 // return an estimation of rendered frames when the output is suspended
1984 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
1985 *dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0;
1986 return NO_ERROR;
1987 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001988 status_t status;
1989 uint32_t frames;
1990 status = mOutput->stream->get_render_position(mOutput->stream, &frames);
1991 *dspFrames = (size_t)frames;
1992 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08001993 }
1994}
1995
1996uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
1997{
1998 Mutex::Autolock _l(mLock);
1999 uint32_t result = 0;
2000 if (getEffectChain_l(sessionId) != 0) {
2001 result = EFFECT_SESSION;
2002 }
2003
2004 for (size_t i = 0; i < mTracks.size(); ++i) {
2005 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002006 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002007 result |= TRACK_SESSION;
2008 break;
2009 }
2010 }
2011
2012 return result;
2013}
2014
2015uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
2016{
2017 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2018 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2019 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2020 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2021 }
2022 for (size_t i = 0; i < mTracks.size(); i++) {
2023 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002024 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002025 return AudioSystem::getStrategyForStream(track->streamType());
2026 }
2027 }
2028 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2029}
2030
2031
2032AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
2033{
2034 Mutex::Autolock _l(mLock);
2035 return mOutput;
2036}
2037
2038AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
2039{
2040 Mutex::Autolock _l(mLock);
2041 AudioStreamOut *output = mOutput;
2042 mOutput = NULL;
2043 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2044 // must push a NULL and wait for ack
2045 mOutputSink.clear();
2046 mPipeSink.clear();
2047 mNormalSink.clear();
2048 return output;
2049}
2050
2051// this method must always be called either with ThreadBase mLock held or inside the thread loop
2052audio_stream_t* AudioFlinger::PlaybackThread::stream() const
2053{
2054 if (mOutput == NULL) {
2055 return NULL;
2056 }
2057 return &mOutput->stream->common;
2058}
2059
2060uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2061{
2062 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2063}
2064
2065status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2066{
2067 if (!isValidSyncEvent(event)) {
2068 return BAD_VALUE;
2069 }
2070
2071 Mutex::Autolock _l(mLock);
2072
2073 for (size_t i = 0; i < mTracks.size(); ++i) {
2074 sp<Track> track = mTracks[i];
2075 if (event->triggerSession() == track->sessionId()) {
2076 (void) track->setSyncEvent(event);
2077 return NO_ERROR;
2078 }
2079 }
2080
2081 return NAME_NOT_FOUND;
2082}
2083
2084bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2085{
2086 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2087}
2088
2089void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2090 const Vector< sp<Track> >& tracksToRemove)
2091{
2092 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002093 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002094 for (size_t i = 0 ; i < count ; i++) {
2095 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002096 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002097 AudioSystem::stopOutput(mId, track->streamType(),
2098 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002099#ifdef ADD_BATTERY_DATA
2100 // to track the speaker usage
2101 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2102#endif
2103 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002104 AudioSystem::releaseOutput(mId, track->streamType(),
2105 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002106 }
Eric Laurent81784c32012-11-19 14:55:58 -08002107 }
2108 }
2109 }
Eric Laurent81784c32012-11-19 14:55:58 -08002110}
2111
2112void AudioFlinger::PlaybackThread::checkSilentMode_l()
2113{
2114 if (!mMasterMute) {
2115 char value[PROPERTY_VALUE_MAX];
2116 if (property_get("ro.audio.silent", value, "0") > 0) {
2117 char *endptr;
2118 unsigned long ul = strtoul(value, &endptr, 0);
2119 if (*endptr == '\0' && ul != 0) {
2120 ALOGD("Silence is golden");
2121 // The setprop command will not allow a property to be changed after
2122 // the first time it is set, so we don't have to worry about un-muting.
2123 setMasterMute_l(true);
2124 }
2125 }
2126 }
2127}
2128
2129// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002130ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002131{
2132 // FIXME rewrite to reduce number of system calls
2133 mLastWriteTime = systemTime();
2134 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002135 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002136 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002137
2138 // If an NBAIO sink is present, use it to write the normal mixer's submix
2139 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002140
Andy Hung010a1a12014-03-13 13:57:33 -07002141 const size_t count = mBytesRemaining / mFrameSize;
2142
Simon Wilson2d590962012-11-29 15:18:50 -08002143 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002144 // update the setpoint when AudioFlinger::mScreenState changes
2145 uint32_t screenState = AudioFlinger::mScreenState;
2146 if (screenState != mScreenState) {
2147 mScreenState = screenState;
2148 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2149 if (pipe != NULL) {
2150 pipe->setAvgFrames((mScreenState & 1) ?
2151 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2152 }
2153 }
Andy Hung010a1a12014-03-13 13:57:33 -07002154 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002155 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002156 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002157 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002158 } else {
2159 bytesWritten = framesWritten;
2160 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002161 status_t status = mNormalSink->getTimestamp(mLatchD.mTimestamp);
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002162 if (status == NO_ERROR) {
2163 size_t totalFramesWritten = mNormalSink->framesWritten();
2164 if (totalFramesWritten >= mLatchD.mTimestamp.mPosition) {
2165 mLatchD.mUnpresentedFrames = totalFramesWritten - mLatchD.mTimestamp.mPosition;
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002166 // mLatchD.mFramesReleased is set immediately before D is clocked into Q
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002167 mLatchDValid = true;
2168 }
2169 }
Eric Laurent81784c32012-11-19 14:55:58 -08002170 // otherwise use the HAL / AudioStreamOut directly
2171 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002172 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002173
Eric Laurentbfb1b832013-01-07 09:53:42 -08002174 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002175 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2176 mWriteAckSequence += 2;
2177 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002178 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002179 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002180 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002181 // FIXME We should have an implementation of timestamps for direct output threads.
2182 // They are used e.g for multichannel PCM playback over HDMI.
Eric Laurentbfb1b832013-01-07 09:53:42 -08002183 bytesWritten = mOutput->stream->write(mOutput->stream,
Andy Hung2098f272014-02-27 14:00:06 -08002184 (char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002185 if (mUseAsyncWrite &&
2186 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2187 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002188 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002189 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002190 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002191 }
Eric Laurent81784c32012-11-19 14:55:58 -08002192 }
2193
Eric Laurent81784c32012-11-19 14:55:58 -08002194 mNumWrites++;
2195 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002196 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002197 return bytesWritten;
2198}
2199
2200void AudioFlinger::PlaybackThread::threadLoop_drain()
2201{
2202 if (mOutput->stream->drain) {
2203 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2204 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002205 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2206 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002207 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002208 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002209 }
2210 mOutput->stream->drain(mOutput->stream,
2211 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
2212 : AUDIO_DRAIN_ALL);
2213 }
2214}
2215
2216void AudioFlinger::PlaybackThread::threadLoop_exit()
2217{
Eric Laurent275e8e92014-11-30 15:14:47 -08002218 {
2219 Mutex::Autolock _l(mLock);
2220 for (size_t i = 0; i < mTracks.size(); i++) {
2221 sp<Track> track = mTracks[i];
2222 track->invalidate();
2223 }
2224 }
Eric Laurent81784c32012-11-19 14:55:58 -08002225}
2226
2227/*
2228The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002229 - mSinkBufferSize from frame count * frame size
Eric Laurent81784c32012-11-19 14:55:58 -08002230 - activeSleepTime from activeSleepTimeUs()
2231 - idleSleepTime from idleSleepTimeUs()
2232 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
2233 - maxPeriod from frame count and sample rate (MIXER only)
2234
2235The parameters that affect these derived values are:
2236 - frame count
2237 - frame size
2238 - sample rate
2239 - device type: A2DP or not
2240 - device latency
2241 - format: PCM or not
2242 - active sleep time
2243 - idle sleep time
2244*/
2245
2246void AudioFlinger::PlaybackThread::cacheParameters_l()
2247{
Andy Hung25c2dac2014-02-27 14:56:00 -08002248 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002249 activeSleepTime = activeSleepTimeUs();
2250 idleSleepTime = idleSleepTimeUs();
2251}
2252
2253void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2254{
Glenn Kasten7c027242012-12-26 14:43:16 -08002255 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurent81784c32012-11-19 14:55:58 -08002256 this, streamType, mTracks.size());
2257 Mutex::Autolock _l(mLock);
2258
2259 size_t size = mTracks.size();
2260 for (size_t i = 0; i < size; i++) {
2261 sp<Track> t = mTracks[i];
2262 if (t->streamType() == streamType) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002263 t->invalidate();
Eric Laurent81784c32012-11-19 14:55:58 -08002264 }
2265 }
2266}
2267
2268status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2269{
2270 int session = chain->sessionId();
Andy Hung010a1a12014-03-13 13:57:33 -07002271 int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled
2272 ? mEffectBuffer : mSinkBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002273 bool ownsBuffer = false;
2274
2275 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
2276 if (session > 0) {
2277 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002278 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002279 if (mType != DIRECT) {
2280 size_t numSamples = mNormalFrameCount * mChannelCount;
2281 buffer = new int16_t[numSamples];
2282 memset(buffer, 0, numSamples * sizeof(int16_t));
2283 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2284 ownsBuffer = true;
2285 }
2286
2287 // Attach all tracks with same session ID to this chain.
2288 for (size_t i = 0; i < mTracks.size(); ++i) {
2289 sp<Track> track = mTracks[i];
2290 if (session == track->sessionId()) {
2291 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2292 buffer);
2293 track->setMainBuffer(buffer);
2294 chain->incTrackCnt();
2295 }
2296 }
2297
2298 // indicate all active tracks in the chain
2299 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2300 sp<Track> track = mActiveTracks[i].promote();
2301 if (track == 0) {
2302 continue;
2303 }
2304 if (session == track->sessionId()) {
2305 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2306 chain->incActiveTrackCnt();
2307 }
2308 }
2309 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002310 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08002311 chain->setInBuffer(buffer, ownsBuffer);
Andy Hung010a1a12014-03-13 13:57:33 -07002312 chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled
2313 ? mEffectBuffer : mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002314 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
2315 // chains list in order to be processed last as it contains output stage effects
2316 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2317 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
2318 // after track specific effects and before output stage
2319 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
2320 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
2321 // Effect chain for other sessions are inserted at beginning of effect
2322 // chains list to be processed before output mix effects. Relative order between other
2323 // sessions is not important
2324 size_t size = mEffectChains.size();
2325 size_t i = 0;
2326 for (i = 0; i < size; i++) {
2327 if (mEffectChains[i]->sessionId() < session) {
2328 break;
2329 }
2330 }
2331 mEffectChains.insertAt(chain, i);
2332 checkSuspendOnAddEffectChain_l(chain);
2333
2334 return NO_ERROR;
2335}
2336
2337size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2338{
2339 int session = chain->sessionId();
2340
2341 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2342
2343 for (size_t i = 0; i < mEffectChains.size(); i++) {
2344 if (chain == mEffectChains[i]) {
2345 mEffectChains.removeAt(i);
2346 // detach all active tracks from the chain
2347 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2348 sp<Track> track = mActiveTracks[i].promote();
2349 if (track == 0) {
2350 continue;
2351 }
2352 if (session == track->sessionId()) {
2353 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2354 chain.get(), session);
2355 chain->decActiveTrackCnt();
2356 }
2357 }
2358
2359 // detach all tracks with same session ID from this chain
2360 for (size_t i = 0; i < mTracks.size(); ++i) {
2361 sp<Track> track = mTracks[i];
2362 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002363 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002364 chain->decTrackCnt();
2365 }
2366 }
2367 break;
2368 }
2369 }
2370 return mEffectChains.size();
2371}
2372
2373status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2374 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2375{
2376 Mutex::Autolock _l(mLock);
2377 return attachAuxEffect_l(track, EffectId);
2378}
2379
2380status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2381 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2382{
2383 status_t status = NO_ERROR;
2384
2385 if (EffectId == 0) {
2386 track->setAuxBuffer(0, NULL);
2387 } else {
2388 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2389 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2390 if (effect != 0) {
2391 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2392 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2393 } else {
2394 status = INVALID_OPERATION;
2395 }
2396 } else {
2397 status = BAD_VALUE;
2398 }
2399 }
2400 return status;
2401}
2402
2403void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2404{
2405 for (size_t i = 0; i < mTracks.size(); ++i) {
2406 sp<Track> track = mTracks[i];
2407 if (track->auxEffectId() == effectId) {
2408 attachAuxEffect_l(track, 0);
2409 }
2410 }
2411}
2412
2413bool AudioFlinger::PlaybackThread::threadLoop()
2414{
2415 Vector< sp<Track> > tracksToRemove;
2416
2417 standbyTime = systemTime();
2418
2419 // MIXER
2420 nsecs_t lastWarning = 0;
2421
2422 // DUPLICATING
2423 // FIXME could this be made local to while loop?
2424 writeFrames = 0;
2425
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002426 int lastGeneration = 0;
2427
Eric Laurent81784c32012-11-19 14:55:58 -08002428 cacheParameters_l();
2429 sleepTime = idleSleepTime;
2430
2431 if (mType == MIXER) {
2432 sleepTimeShift = 0;
2433 }
2434
2435 CpuStats cpuStats;
2436 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2437
2438 acquireWakeLock();
2439
Glenn Kasten9e58b552013-01-18 15:09:48 -08002440 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2441 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2442 // and then that string will be logged at the next convenient opportunity.
2443 const char *logString = NULL;
2444
Eric Laurent664539d2013-09-23 18:24:31 -07002445 checkSilentMode_l();
2446
Eric Laurent81784c32012-11-19 14:55:58 -08002447 while (!exitPending())
2448 {
2449 cpuStats.sample(myName);
2450
2451 Vector< sp<EffectChain> > effectChains;
2452
Eric Laurent81784c32012-11-19 14:55:58 -08002453 { // scope for mLock
2454
2455 Mutex::Autolock _l(mLock);
2456
Eric Laurent021cf962014-05-13 10:18:14 -07002457 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07002458
Glenn Kasten9e58b552013-01-18 15:09:48 -08002459 if (logString != NULL) {
2460 mNBLogWriter->logTimestamp();
2461 mNBLogWriter->log(logString);
2462 logString = NULL;
2463 }
2464
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002465 // Gather the framesReleased counters for all active tracks,
2466 // and latch them atomically with the timestamp.
2467 // FIXME We're using raw pointers as indices. A unique track ID would be a better index.
2468 mLatchD.mFramesReleased.clear();
2469 size_t size = mActiveTracks.size();
2470 for (size_t i = 0; i < size; i++) {
2471 sp<Track> t = mActiveTracks[i].promote();
2472 if (t != 0) {
2473 mLatchD.mFramesReleased.add(t.get(),
2474 t->mAudioTrackServerProxy->framesReleased());
2475 }
2476 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002477 if (mLatchDValid) {
2478 mLatchQ = mLatchD;
2479 mLatchDValid = false;
2480 mLatchQValid = true;
2481 }
2482
Eric Laurent81784c32012-11-19 14:55:58 -08002483 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002484 if (mSignalPending) {
2485 // A signal was raised while we were unlocked
2486 mSignalPending = false;
2487 } else if (waitingAsyncCallback_l()) {
2488 if (exitPending()) {
2489 break;
2490 }
2491 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002492 mWakeLockUids.clear();
2493 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002494 ALOGV("wait async completion");
2495 mWaitWorkCV.wait(mLock);
2496 ALOGV("async completion/wake");
2497 acquireWakeLock_l();
Eric Laurent972a1732013-09-04 09:42:59 -07002498 standbyTime = systemTime() + standbyDelay;
2499 sleepTime = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002500
2501 continue;
2502 }
2503 if ((!mActiveTracks.size() && systemTime() > standbyTime) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08002504 isSuspended()) {
2505 // put audio hardware into standby after short delay
2506 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002507
2508 threadLoop_standby();
2509
2510 mStandby = true;
2511 }
2512
2513 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2514 // we're about to wait, flush the binder command buffer
2515 IPCThreadState::self()->flushCommands();
2516
2517 clearOutputTracks();
2518
2519 if (exitPending()) {
2520 break;
2521 }
2522
2523 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002524 mWakeLockUids.clear();
2525 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002526 // wait until we have something to do...
2527 ALOGV("%s going to sleep", myName.string());
2528 mWaitWorkCV.wait(mLock);
2529 ALOGV("%s waking up", myName.string());
2530 acquireWakeLock_l();
2531
2532 mMixerStatus = MIXER_IDLE;
2533 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2534 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002535 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002536 checkSilentMode_l();
2537
2538 standbyTime = systemTime() + standbyDelay;
2539 sleepTime = idleSleepTime;
2540 if (mType == MIXER) {
2541 sleepTimeShift = 0;
2542 }
2543
2544 continue;
2545 }
2546 }
Eric Laurent81784c32012-11-19 14:55:58 -08002547 // mMixerStatusIgnoringFastTracks is also updated internally
2548 mMixerStatus = prepareTracks_l(&tracksToRemove);
2549
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002550 // compare with previously applied list
2551 if (lastGeneration != mActiveTracksGeneration) {
2552 // update wakelock
2553 updateWakeLockUids_l(mWakeLockUids);
2554 lastGeneration = mActiveTracksGeneration;
2555 }
2556
Eric Laurent81784c32012-11-19 14:55:58 -08002557 // prevent any changes in effect chain list and in each effect chain
2558 // during mixing and effect process as the audio buffers could be deleted
2559 // or modified if an effect is created or deleted
2560 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002561 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08002562
Eric Laurentbfb1b832013-01-07 09:53:42 -08002563 if (mBytesRemaining == 0) {
2564 mCurrentWriteLength = 0;
2565 if (mMixerStatus == MIXER_TRACKS_READY) {
2566 // threadLoop_mix() sets mCurrentWriteLength
2567 threadLoop_mix();
2568 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
2569 && (mMixerStatus != MIXER_DRAIN_ALL)) {
2570 // threadLoop_sleepTime sets sleepTime to 0 if data
2571 // must be written to HAL
2572 threadLoop_sleepTime();
2573 if (sleepTime == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08002574 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002575 }
2576 }
Andy Hung98ef9782014-03-04 14:46:50 -08002577 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
2578 // mMixerBuffer with data if mMixerBufferValid is true and sleepTime == 0.
2579 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
2580 // or mSinkBuffer (if there are no effects).
2581 //
2582 // This is done pre-effects computation; if effects change to
2583 // support higher precision, this needs to move.
2584 //
2585 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
2586 // TODO use sleepTime == 0 as an additional condition.
2587 if (mMixerBufferValid) {
2588 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
2589 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
2590
2591 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
2592 mNormalFrameCount * mChannelCount);
2593 }
2594
Eric Laurentbfb1b832013-01-07 09:53:42 -08002595 mBytesRemaining = mCurrentWriteLength;
2596 if (isSuspended()) {
2597 sleepTime = suspendSleepTimeUs();
2598 // simulate write to HAL when suspended
Andy Hung25c2dac2014-02-27 14:56:00 -08002599 mBytesWritten += mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002600 mBytesRemaining = 0;
2601 }
Eric Laurent81784c32012-11-19 14:55:58 -08002602
Eric Laurentbfb1b832013-01-07 09:53:42 -08002603 // only process effects if we're going to write
Eric Laurent59fe0102013-09-27 18:48:26 -07002604 if (sleepTime == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002605 for (size_t i = 0; i < effectChains.size(); i ++) {
2606 effectChains[i]->process_l();
2607 }
Eric Laurent81784c32012-11-19 14:55:58 -08002608 }
2609 }
Eric Laurent59fe0102013-09-27 18:48:26 -07002610 // Process effect chains for offloaded thread even if no audio
2611 // was read from audio track: process only updates effect state
2612 // and thus does have to be synchronized with audio writes but may have
2613 // to be called while waiting for async write callback
2614 if (mType == OFFLOAD) {
2615 for (size_t i = 0; i < effectChains.size(); i ++) {
2616 effectChains[i]->process_l();
2617 }
2618 }
Eric Laurent81784c32012-11-19 14:55:58 -08002619
Andy Hung98ef9782014-03-04 14:46:50 -08002620 // Only if the Effects buffer is enabled and there is data in the
2621 // Effects buffer (buffer valid), we need to
2622 // copy into the sink buffer.
2623 // TODO use sleepTime == 0 as an additional condition.
2624 if (mEffectBufferValid) {
2625 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
2626 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
2627 mNormalFrameCount * mChannelCount);
2628 }
2629
Eric Laurent81784c32012-11-19 14:55:58 -08002630 // enable changes in effect chain
2631 unlockEffectChains(effectChains);
2632
Eric Laurentbfb1b832013-01-07 09:53:42 -08002633 if (!waitingAsyncCallback()) {
2634 // sleepTime == 0 means we must write to audio hardware
2635 if (sleepTime == 0) {
2636 if (mBytesRemaining) {
2637 ssize_t ret = threadLoop_write();
2638 if (ret < 0) {
2639 mBytesRemaining = 0;
2640 } else {
2641 mBytesWritten += ret;
2642 mBytesRemaining -= ret;
2643 }
2644 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
2645 (mMixerStatus == MIXER_DRAIN_ALL)) {
2646 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08002647 }
Glenn Kasten4944acb2013-08-19 08:39:20 -07002648 if (mType == MIXER) {
2649 // write blocked detection
2650 nsecs_t now = systemTime();
2651 nsecs_t delta = now - mLastWriteTime;
2652 if (!mStandby && delta > maxPeriod) {
2653 mNumDelayedWrites++;
2654 if ((now - lastWarning) > kWarningThrottleNs) {
2655 ATRACE_NAME("underrun");
2656 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2657 ns2ms(delta), mNumDelayedWrites, this);
2658 lastWarning = now;
2659 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002660 }
2661 }
Eric Laurent81784c32012-11-19 14:55:58 -08002662
Eric Laurentbfb1b832013-01-07 09:53:42 -08002663 } else {
2664 usleep(sleepTime);
2665 }
Eric Laurent81784c32012-11-19 14:55:58 -08002666 }
2667
2668 // Finally let go of removed track(s), without the lock held
2669 // since we can't guarantee the destructors won't acquire that
2670 // same lock. This will also mutate and push a new fast mixer state.
2671 threadLoop_removeTracks(tracksToRemove);
2672 tracksToRemove.clear();
2673
2674 // FIXME I don't understand the need for this here;
2675 // it was in the original code but maybe the
2676 // assignment in saveOutputTracks() makes this unnecessary?
2677 clearOutputTracks();
2678
2679 // Effect chains will be actually deleted here if they were removed from
2680 // mEffectChains list during mixing or effects processing
2681 effectChains.clear();
2682
2683 // FIXME Note that the above .clear() is no longer necessary since effectChains
2684 // is now local to this block, but will keep it for now (at least until merge done).
2685 }
2686
Eric Laurentbfb1b832013-01-07 09:53:42 -08002687 threadLoop_exit();
2688
Eric Laurentcf817a22014-08-04 20:36:31 -07002689 if (!mStandby) {
2690 threadLoop_standby();
2691 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08002692 }
2693
2694 releaseWakeLock();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002695 mWakeLockUids.clear();
2696 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002697
2698 ALOGV("Thread %p type %d exiting", this, mType);
2699 return false;
2700}
2701
Eric Laurentbfb1b832013-01-07 09:53:42 -08002702// removeTracks_l() must be called with ThreadBase::mLock held
2703void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
2704{
2705 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002706 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002707 for (size_t i=0 ; i<count ; i++) {
2708 const sp<Track>& track = tracksToRemove.itemAt(i);
2709 mActiveTracks.remove(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002710 mWakeLockUids.remove(track->uid());
2711 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002712 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
2713 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2714 if (chain != 0) {
2715 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
2716 track->sessionId());
2717 chain->decActiveTrackCnt();
2718 }
2719 if (track->isTerminated()) {
2720 removeTrack_l(track);
2721 }
2722 }
2723 }
2724
2725}
Eric Laurent81784c32012-11-19 14:55:58 -08002726
Eric Laurentaccc1472013-09-20 09:36:34 -07002727status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
2728{
2729 if (mNormalSink != 0) {
2730 return mNormalSink->getTimestamp(timestamp);
2731 }
Andy Hung9a1c8892014-12-03 11:37:42 -08002732 if ((mType == OFFLOAD || mType == DIRECT)
2733 && mOutput != NULL && mOutput->stream->get_presentation_position) {
Eric Laurentaccc1472013-09-20 09:36:34 -07002734 uint64_t position64;
2735 int ret = mOutput->stream->get_presentation_position(
2736 mOutput->stream, &position64, &timestamp.mTime);
2737 if (ret == 0) {
2738 timestamp.mPosition = (uint32_t)position64;
2739 return NO_ERROR;
2740 }
2741 }
2742 return INVALID_OPERATION;
2743}
Eric Laurent1c333e22014-05-20 10:48:17 -07002744
2745status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
2746 audio_patch_handle_t *handle)
2747{
2748 status_t status = NO_ERROR;
2749 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
2750 // store new device and send to effects
2751 audio_devices_t type = AUDIO_DEVICE_NONE;
2752 for (unsigned int i = 0; i < patch->num_sinks; i++) {
2753 type |= patch->sinks[i].ext.device.type;
2754 }
2755 mOutDevice = type;
2756 for (size_t i = 0; i < mEffectChains.size(); i++) {
2757 mEffectChains[i]->setDevice_l(mOutDevice);
2758 }
2759
2760 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
2761 status = hwDevice->create_audio_patch(hwDevice,
2762 patch->num_sources,
2763 patch->sources,
2764 patch->num_sinks,
2765 patch->sinks,
2766 handle);
2767 } else {
2768 ALOG_ASSERT(false, "createAudioPatch_l() called on a pre 3.0 HAL");
2769 }
2770 return status;
2771}
2772
2773status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
2774{
2775 status_t status = NO_ERROR;
2776 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
2777 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
2778 status = hwDevice->release_audio_patch(hwDevice, handle);
2779 } else {
2780 ALOG_ASSERT(false, "releaseAudioPatch_l() called on a pre 3.0 HAL");
2781 }
2782 return status;
2783}
2784
Eric Laurent83b88082014-06-20 18:31:16 -07002785void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
2786{
2787 Mutex::Autolock _l(mLock);
2788 mTracks.add(track);
2789}
2790
2791void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
2792{
2793 Mutex::Autolock _l(mLock);
2794 destroyTrack_l(track);
2795}
2796
2797void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
2798{
2799 ThreadBase::getAudioPortConfig(config);
2800 config->role = AUDIO_PORT_ROLE_SOURCE;
2801 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
2802 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
2803}
2804
Eric Laurent81784c32012-11-19 14:55:58 -08002805// ----------------------------------------------------------------------------
2806
2807AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
2808 audio_io_handle_t id, audio_devices_t device, type_t type)
2809 : PlaybackThread(audioFlinger, output, id, device, type),
2810 // mAudioMixer below
2811 // mFastMixer below
2812 mFastMixerFutex(0)
2813 // mOutputSink below
2814 // mPipeSink below
2815 // mNormalSink below
2816{
2817 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07002818 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, "
Eric Laurent81784c32012-11-19 14:55:58 -08002819 "mFrameCount=%d, mNormalFrameCount=%d",
2820 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2821 mNormalFrameCount);
2822 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2823
Eric Laurent81784c32012-11-19 14:55:58 -08002824 // create an NBAIO sink for the HAL output stream, and negotiate
2825 mOutputSink = new AudioStreamOutSink(output->stream);
2826 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08002827 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Eric Laurent81784c32012-11-19 14:55:58 -08002828 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2829 ALOG_ASSERT(index == 0);
2830
2831 // initialize fast mixer depending on configuration
2832 bool initFastMixer;
2833 switch (kUseFastMixer) {
2834 case FastMixer_Never:
2835 initFastMixer = false;
2836 break;
2837 case FastMixer_Always:
2838 initFastMixer = true;
2839 break;
2840 case FastMixer_Static:
2841 case FastMixer_Dynamic:
2842 initFastMixer = mFrameCount < mNormalFrameCount;
2843 break;
2844 }
2845 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07002846 audio_format_t fastMixerFormat;
2847 if (mMixerBufferEnabled && mEffectBufferEnabled) {
2848 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
2849 } else {
2850 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
2851 }
2852 if (mFormat != fastMixerFormat) {
2853 // change our Sink format to accept our intermediate precision
2854 mFormat = fastMixerFormat;
2855 free(mSinkBuffer);
2856 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2857 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
2858 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
2859 }
Eric Laurent81784c32012-11-19 14:55:58 -08002860
2861 // create a MonoPipe to connect our submix to FastMixer
2862 NBAIO_Format format = mOutputSink->format();
Glenn Kastenba0b34c2014-09-28 13:06:06 -07002863 NBAIO_Format origformat = format;
Andy Hung1258c1a2014-05-23 21:22:17 -07002864 // adjust format to match that of the Fast Mixer
2865 format.mFormat = fastMixerFormat;
2866 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
2867
Eric Laurent81784c32012-11-19 14:55:58 -08002868 // This pipe depth compensates for scheduling latency of the normal mixer thread.
2869 // When it wakes up after a maximum latency, it runs a few cycles quickly before
2870 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
2871 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
2872 const NBAIO_Format offers[1] = {format};
2873 size_t numCounterOffers = 0;
2874 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2875 ALOG_ASSERT(index == 0);
2876 monoPipe->setAvgFrames((mScreenState & 1) ?
2877 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2878 mPipeSink = monoPipe;
2879
Glenn Kasten46909e72013-02-26 09:20:22 -08002880#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08002881 if (mTeeSinkOutputEnabled) {
2882 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07002883 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
2884 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08002885 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07002886 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08002887 ALOG_ASSERT(index == 0);
2888 mTeeSink = teeSink;
2889 PipeReader *teeSource = new PipeReader(*teeSink);
2890 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07002891 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08002892 ALOG_ASSERT(index == 0);
2893 mTeeSource = teeSource;
2894 }
Glenn Kasten46909e72013-02-26 09:20:22 -08002895#endif
Eric Laurent81784c32012-11-19 14:55:58 -08002896
2897 // create fast mixer and configure it initially with just one fast track for our submix
2898 mFastMixer = new FastMixer();
2899 FastMixerStateQueue *sq = mFastMixer->sq();
2900#ifdef STATE_QUEUE_DUMP
2901 sq->setObserverDump(&mStateQueueObserverDump);
2902 sq->setMutatorDump(&mStateQueueMutatorDump);
2903#endif
2904 FastMixerState *state = sq->begin();
2905 FastTrack *fastTrack = &state->mFastTracks[0];
2906 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2907 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2908 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07002909 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
2910 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08002911 fastTrack->mGeneration++;
2912 state->mFastTracksGen++;
2913 state->mTrackMask = 1;
2914 // fast mixer will use the HAL output sink
2915 state->mOutputSink = mOutputSink.get();
2916 state->mOutputSinkGen++;
2917 state->mFrameCount = mFrameCount;
2918 state->mCommand = FastMixerState::COLD_IDLE;
2919 // already done in constructor initialization list
2920 //mFastMixerFutex = 0;
2921 state->mColdFutexAddr = &mFastMixerFutex;
2922 state->mColdGen++;
2923 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08002924#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08002925 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08002926#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08002927 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
2928 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08002929 sq->end();
2930 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2931
2932 // start the fast mixer
2933 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
2934 pid_t tid = mFastMixer->getTid();
2935 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2936 if (err != 0) {
2937 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2938 kPriorityFastMixer, getpid_cached, tid, err);
2939 }
2940
2941#ifdef AUDIO_WATCHDOG
2942 // create and start the watchdog
2943 mAudioWatchdog = new AudioWatchdog();
2944 mAudioWatchdog->setDump(&mAudioWatchdogDump);
2945 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
2946 tid = mAudioWatchdog->getTid();
2947 err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2948 if (err != 0) {
2949 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2950 kPriorityFastMixer, getpid_cached, tid, err);
2951 }
2952#endif
2953
Eric Laurent81784c32012-11-19 14:55:58 -08002954 }
2955
2956 switch (kUseFastMixer) {
2957 case FastMixer_Never:
2958 case FastMixer_Dynamic:
2959 mNormalSink = mOutputSink;
2960 break;
2961 case FastMixer_Always:
2962 mNormalSink = mPipeSink;
2963 break;
2964 case FastMixer_Static:
2965 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2966 break;
2967 }
2968}
2969
2970AudioFlinger::MixerThread::~MixerThread()
2971{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07002972 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002973 FastMixerStateQueue *sq = mFastMixer->sq();
2974 FastMixerState *state = sq->begin();
2975 if (state->mCommand == FastMixerState::COLD_IDLE) {
2976 int32_t old = android_atomic_inc(&mFastMixerFutex);
2977 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07002978 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08002979 }
2980 }
2981 state->mCommand = FastMixerState::EXIT;
2982 sq->end();
2983 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2984 mFastMixer->join();
2985 // Though the fast mixer thread has exited, it's state queue is still valid.
2986 // We'll use that extract the final state which contains one remaining fast track
2987 // corresponding to our sub-mix.
2988 state = sq->begin();
2989 ALOG_ASSERT(state->mTrackMask == 1);
2990 FastTrack *fastTrack = &state->mFastTracks[0];
2991 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2992 delete fastTrack->mBufferProvider;
2993 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07002994 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08002995#ifdef AUDIO_WATCHDOG
2996 if (mAudioWatchdog != 0) {
2997 mAudioWatchdog->requestExit();
2998 mAudioWatchdog->requestExitAndWait();
2999 mAudioWatchdog.clear();
3000 }
3001#endif
3002 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003003 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003004 delete mAudioMixer;
3005}
3006
3007
3008uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3009{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003010 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003011 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3012 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3013 }
3014 return latency;
3015}
3016
3017
3018void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3019{
3020 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3021}
3022
Eric Laurentbfb1b832013-01-07 09:53:42 -08003023ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003024{
3025 // FIXME we should only do one push per cycle; confirm this is true
3026 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003027 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003028 FastMixerStateQueue *sq = mFastMixer->sq();
3029 FastMixerState *state = sq->begin();
3030 if (state->mCommand != FastMixerState::MIX_WRITE &&
3031 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3032 if (state->mCommand == FastMixerState::COLD_IDLE) {
3033 int32_t old = android_atomic_inc(&mFastMixerFutex);
3034 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003035 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003036 }
3037#ifdef AUDIO_WATCHDOG
3038 if (mAudioWatchdog != 0) {
3039 mAudioWatchdog->resume();
3040 }
3041#endif
3042 }
3043 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003044 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
3045 FastMixerDumpState::kSamplingNforLowRamDevice : FastMixerDumpState::kSamplingN);
Eric Laurent81784c32012-11-19 14:55:58 -08003046 sq->end();
3047 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3048 if (kUseFastMixer == FastMixer_Dynamic) {
3049 mNormalSink = mPipeSink;
3050 }
3051 } else {
3052 sq->end(false /*didModify*/);
3053 }
3054 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003055 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003056}
3057
3058void AudioFlinger::MixerThread::threadLoop_standby()
3059{
3060 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003061 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003062 FastMixerStateQueue *sq = mFastMixer->sq();
3063 FastMixerState *state = sq->begin();
3064 if (!(state->mCommand & FastMixerState::IDLE)) {
3065 state->mCommand = FastMixerState::COLD_IDLE;
3066 state->mColdFutexAddr = &mFastMixerFutex;
3067 state->mColdGen++;
3068 mFastMixerFutex = 0;
3069 sq->end();
3070 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3071 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3072 if (kUseFastMixer == FastMixer_Dynamic) {
3073 mNormalSink = mOutputSink;
3074 }
3075#ifdef AUDIO_WATCHDOG
3076 if (mAudioWatchdog != 0) {
3077 mAudioWatchdog->pause();
3078 }
3079#endif
3080 } else {
3081 sq->end(false /*didModify*/);
3082 }
3083 }
3084 PlaybackThread::threadLoop_standby();
3085}
3086
Eric Laurentbfb1b832013-01-07 09:53:42 -08003087bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3088{
3089 return false;
3090}
3091
3092bool AudioFlinger::PlaybackThread::shouldStandby_l()
3093{
3094 return !mStandby;
3095}
3096
3097bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3098{
3099 Mutex::Autolock _l(mLock);
3100 return waitingAsyncCallback_l();
3101}
3102
Eric Laurent81784c32012-11-19 14:55:58 -08003103// shared by MIXER and DIRECT, overridden by DUPLICATING
3104void AudioFlinger::PlaybackThread::threadLoop_standby()
3105{
3106 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
3107 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003108 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003109 // discard any pending drain or write ack by incrementing sequence
3110 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3111 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003112 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003113 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3114 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003115 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003116 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003117}
3118
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003119void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3120{
3121 ALOGV("signal playback thread");
3122 broadcast_l();
3123}
3124
Eric Laurent81784c32012-11-19 14:55:58 -08003125void AudioFlinger::MixerThread::threadLoop_mix()
3126{
3127 // obtain the presentation timestamp of the next output buffer
3128 int64_t pts;
3129 status_t status = INVALID_OPERATION;
3130
3131 if (mNormalSink != 0) {
3132 status = mNormalSink->getNextWriteTimestamp(&pts);
3133 } else {
3134 status = mOutputSink->getNextWriteTimestamp(&pts);
3135 }
3136
3137 if (status != NO_ERROR) {
3138 pts = AudioBufferProvider::kInvalidPTS;
3139 }
3140
3141 // mix buffers...
3142 mAudioMixer->process(pts);
Andy Hung25c2dac2014-02-27 14:56:00 -08003143 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003144 // increase sleep time progressively when application underrun condition clears.
3145 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3146 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3147 // such that we would underrun the audio HAL.
3148 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
3149 sleepTimeShift--;
3150 }
3151 sleepTime = 0;
3152 standbyTime = systemTime() + standbyDelay;
3153 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003154
Eric Laurent81784c32012-11-19 14:55:58 -08003155}
3156
3157void AudioFlinger::MixerThread::threadLoop_sleepTime()
3158{
3159 // If no tracks are ready, sleep once for the duration of an output
3160 // buffer size, then write 0s to the output
3161 if (sleepTime == 0) {
3162 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3163 sleepTime = activeSleepTime >> sleepTimeShift;
3164 if (sleepTime < kMinThreadSleepTimeUs) {
3165 sleepTime = kMinThreadSleepTimeUs;
3166 }
3167 // reduce sleep time in case of consecutive application underruns to avoid
3168 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3169 // duration we would end up writing less data than needed by the audio HAL if
3170 // the condition persists.
3171 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3172 sleepTimeShift++;
3173 }
3174 } else {
3175 sleepTime = idleSleepTime;
3176 }
3177 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003178 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3179 // before effects processing or output.
3180 if (mMixerBufferValid) {
3181 memset(mMixerBuffer, 0, mMixerBufferSize);
3182 } else {
3183 memset(mSinkBuffer, 0, mSinkBufferSize);
3184 }
Eric Laurent81784c32012-11-19 14:55:58 -08003185 sleepTime = 0;
3186 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3187 "anticipated start");
3188 }
3189 // TODO add standby time extension fct of effect tail
3190}
3191
3192// prepareTracks_l() must be called with ThreadBase::mLock held
3193AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3194 Vector< sp<Track> > *tracksToRemove)
3195{
3196
3197 mixer_state mixerStatus = MIXER_IDLE;
3198 // find out which tracks need to be processed
3199 size_t count = mActiveTracks.size();
3200 size_t mixedTracks = 0;
3201 size_t tracksWithEffect = 0;
3202 // counts only _active_ fast tracks
3203 size_t fastTracks = 0;
3204 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
3205
3206 float masterVolume = mMasterVolume;
3207 bool masterMute = mMasterMute;
3208
3209 if (masterMute) {
3210 masterVolume = 0;
3211 }
3212 // Delegate master volume control to effect in output mix effect chain if needed
3213 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3214 if (chain != 0) {
3215 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
3216 chain->setVolume_l(&v, &v);
3217 masterVolume = (float)((v + (1 << 23)) >> 24);
3218 chain.clear();
3219 }
3220
3221 // prepare a new state to push
3222 FastMixerStateQueue *sq = NULL;
3223 FastMixerState *state = NULL;
3224 bool didModify = false;
3225 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003226 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003227 sq = mFastMixer->sq();
3228 state = sq->begin();
3229 }
3230
Andy Hung69aed5f2014-02-25 17:24:40 -08003231 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08003232 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08003233
Eric Laurent81784c32012-11-19 14:55:58 -08003234 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003235 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003236 if (t == 0) {
3237 continue;
3238 }
3239
3240 // this const just means the local variable doesn't change
3241 Track* const track = t.get();
3242
3243 // process fast tracks
3244 if (track->isFastTrack()) {
3245
3246 // It's theoretically possible (though unlikely) for a fast track to be created
3247 // and then removed within the same normal mix cycle. This is not a problem, as
3248 // the track never becomes active so it's fast mixer slot is never touched.
3249 // The converse, of removing an (active) track and then creating a new track
3250 // at the identical fast mixer slot within the same normal mix cycle,
3251 // is impossible because the slot isn't marked available until the end of each cycle.
3252 int j = track->mFastIndex;
3253 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
3254 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
3255 FastTrack *fastTrack = &state->mFastTracks[j];
3256
3257 // Determine whether the track is currently in underrun condition,
3258 // and whether it had a recent underrun.
3259 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
3260 FastTrackUnderruns underruns = ftDump->mUnderruns;
3261 uint32_t recentFull = (underruns.mBitFields.mFull -
3262 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
3263 uint32_t recentPartial = (underruns.mBitFields.mPartial -
3264 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
3265 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
3266 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
3267 uint32_t recentUnderruns = recentPartial + recentEmpty;
3268 track->mObservedUnderruns = underruns;
3269 // don't count underruns that occur while stopping or pausing
3270 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07003271 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
3272 recentUnderruns > 0) {
3273 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
3274 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003275 }
3276
3277 // This is similar to the state machine for normal tracks,
3278 // with a few modifications for fast tracks.
3279 bool isActive = true;
3280 switch (track->mState) {
3281 case TrackBase::STOPPING_1:
3282 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08003283 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003284 track->mState = TrackBase::STOPPING_2;
3285 }
3286 break;
3287 case TrackBase::PAUSING:
3288 // ramp down is not yet implemented
3289 track->setPaused();
3290 break;
3291 case TrackBase::RESUMING:
3292 // ramp up is not yet implemented
3293 track->mState = TrackBase::ACTIVE;
3294 break;
3295 case TrackBase::ACTIVE:
3296 if (recentFull > 0 || recentPartial > 0) {
3297 // track has provided at least some frames recently: reset retry count
3298 track->mRetryCount = kMaxTrackRetries;
3299 }
3300 if (recentUnderruns == 0) {
3301 // no recent underruns: stay active
3302 break;
3303 }
3304 // there has recently been an underrun of some kind
3305 if (track->sharedBuffer() == 0) {
3306 // were any of the recent underruns "empty" (no frames available)?
3307 if (recentEmpty == 0) {
3308 // no, then ignore the partial underruns as they are allowed indefinitely
3309 break;
3310 }
3311 // there has recently been an "empty" underrun: decrement the retry counter
3312 if (--(track->mRetryCount) > 0) {
3313 break;
3314 }
3315 // indicate to client process that the track was disabled because of underrun;
3316 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003317 android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003318 // remove from active list, but state remains ACTIVE [confusing but true]
3319 isActive = false;
3320 break;
3321 }
3322 // fall through
3323 case TrackBase::STOPPING_2:
3324 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003325 case TrackBase::STOPPED:
3326 case TrackBase::FLUSHED: // flush() while active
3327 // Check for presentation complete if track is inactive
3328 // We have consumed all the buffers of this track.
3329 // This would be incomplete if we auto-paused on underrun
3330 {
3331 size_t audioHALFrames =
3332 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3333 size_t framesWritten = mBytesWritten / mFrameSize;
3334 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
3335 // track stays in active list until presentation is complete
3336 break;
3337 }
3338 }
3339 if (track->isStopping_2()) {
3340 track->mState = TrackBase::STOPPED;
3341 }
3342 if (track->isStopped()) {
3343 // Can't reset directly, as fast mixer is still polling this track
3344 // track->reset();
3345 // So instead mark this track as needing to be reset after push with ack
3346 resetMask |= 1 << i;
3347 }
3348 isActive = false;
3349 break;
3350 case TrackBase::IDLE:
3351 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08003352 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08003353 }
3354
3355 if (isActive) {
3356 // was it previously inactive?
3357 if (!(state->mTrackMask & (1 << j))) {
3358 ExtendedAudioBufferProvider *eabp = track;
3359 VolumeProvider *vp = track;
3360 fastTrack->mBufferProvider = eabp;
3361 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08003362 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003363 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08003364 fastTrack->mGeneration++;
3365 state->mTrackMask |= 1 << j;
3366 didModify = true;
3367 // no acknowledgement required for newly active tracks
3368 }
3369 // cache the combined master volume and stream type volume for fast mixer; this
3370 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08003371 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08003372 ++fastTracks;
3373 } else {
3374 // was it previously active?
3375 if (state->mTrackMask & (1 << j)) {
3376 fastTrack->mBufferProvider = NULL;
3377 fastTrack->mGeneration++;
3378 state->mTrackMask &= ~(1 << j);
3379 didModify = true;
3380 // If any fast tracks were removed, we must wait for acknowledgement
3381 // because we're about to decrement the last sp<> on those tracks.
3382 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3383 } else {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003384 LOG_ALWAYS_FATAL("fast track %d should have been active", j);
Eric Laurent81784c32012-11-19 14:55:58 -08003385 }
3386 tracksToRemove->add(track);
3387 // Avoids a misleading display in dumpsys
3388 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
3389 }
3390 continue;
3391 }
3392
3393 { // local variable scope to avoid goto warning
3394
3395 audio_track_cblk_t* cblk = track->cblk();
3396
3397 // The first time a track is added we wait
3398 // for all its buffers to be filled before processing it
3399 int name = track->name();
3400 // make sure that we have enough frames to mix one full buffer.
3401 // enforce this condition only once to enable draining the buffer in case the client
3402 // app does not call stop() and relies on underrun to stop:
3403 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
3404 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003405 size_t desiredFrames;
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003406 uint32_t sr = track->sampleRate();
3407 if (sr == mSampleRate) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003408 desiredFrames = mNormalFrameCount;
3409 } else {
3410 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003411 desiredFrames = (mNormalFrameCount * sr) / mSampleRate + 1 + 1;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003412 // add frames already consumed but not yet released by the resampler
Glenn Kasten2fc14732013-08-05 14:58:14 -07003413 // because mAudioTrackServerProxy->framesReady() will include these frames
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003414 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
Glenn Kasten74935e42013-12-19 08:56:45 -08003415#if 0
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003416 // the minimum track buffer size is normally twice the number of frames necessary
3417 // to fill one buffer and the resampler should not leave more than one buffer worth
3418 // of unreleased frames after each pass, but just in case...
3419 ALOG_ASSERT(desiredFrames <= cblk->frameCount_);
Glenn Kasten74935e42013-12-19 08:56:45 -08003420#endif
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003421 }
Eric Laurent81784c32012-11-19 14:55:58 -08003422 uint32_t minFrames = 1;
3423 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
3424 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003425 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08003426 }
Eric Laurent13e4c962013-12-20 17:36:01 -08003427
3428 size_t framesReady = track->framesReady();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003429 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08003430 !track->isPaused() && !track->isTerminated())
3431 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003432 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003433
3434 mixedTracks++;
3435
Andy Hung69aed5f2014-02-25 17:24:40 -08003436 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
3437 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08003438 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08003439 if (track->mainBuffer() != mSinkBuffer &&
3440 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08003441 if (mEffectBufferEnabled) {
3442 mEffectBufferValid = true; // Later can set directly.
3443 }
Eric Laurent81784c32012-11-19 14:55:58 -08003444 chain = getEffectChain_l(track->sessionId());
3445 // Delegate volume control to effect in track effect chain if needed
3446 if (chain != 0) {
3447 tracksWithEffect++;
3448 } else {
3449 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
3450 "session %d",
3451 name, track->sessionId());
3452 }
3453 }
3454
3455
3456 int param = AudioMixer::VOLUME;
3457 if (track->mFillingUpStatus == Track::FS_FILLED) {
3458 // no ramp for the first volume setting
3459 track->mFillingUpStatus = Track::FS_ACTIVE;
3460 if (track->mState == TrackBase::RESUMING) {
3461 track->mState = TrackBase::ACTIVE;
3462 param = AudioMixer::RAMP_VOLUME;
3463 }
3464 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003465 // FIXME should not make a decision based on mServer
3466 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003467 // If the track is stopped before the first frame was mixed,
3468 // do not apply ramp
3469 param = AudioMixer::RAMP_VOLUME;
3470 }
3471
3472 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07003473 uint32_t vl, vr; // in U8.24 integer format
3474 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08003475 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07003476 vl = vr = 0;
3477 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08003478 if (track->isPausing()) {
3479 track->setPaused();
3480 }
3481 } else {
3482
3483 // read original volumes with volume control
3484 float typeVolume = mStreamTypes[track->streamType()].volume;
3485 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003486 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07003487 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07003488 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
3489 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08003490 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07003491 if (vlf > GAIN_FLOAT_UNITY) {
3492 ALOGV("Track left volume out of range: %.3g", vlf);
3493 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003494 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07003495 if (vrf > GAIN_FLOAT_UNITY) {
3496 ALOGV("Track right volume out of range: %.3g", vrf);
3497 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003498 }
3499 // now apply the master volume and stream type volume
Andy Hung6be49402014-05-30 10:42:03 -07003500 vlf *= v;
3501 vrf *= v;
Eric Laurent81784c32012-11-19 14:55:58 -08003502 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07003503 // then derive vl and vr as U8.24 versions for the effect chain
3504 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
3505 vl = (uint32_t) (scaleto8_24 * vlf);
3506 vr = (uint32_t) (scaleto8_24 * vrf);
3507 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08003508 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08003509 // send level comes from shared memory and so may be corrupt
3510 if (sendLevel > MAX_GAIN_INT) {
3511 ALOGV("Track send level out of range: %04X", sendLevel);
3512 sendLevel = MAX_GAIN_INT;
3513 }
Andy Hung6be49402014-05-30 10:42:03 -07003514 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
3515 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08003516 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003517
Eric Laurent81784c32012-11-19 14:55:58 -08003518 // Delegate volume control to effect in track effect chain if needed
3519 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3520 // Do not ramp volume if volume is controlled by effect
3521 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08003522 // Update remaining floating point volume levels
3523 vlf = (float)vl / (1 << 24);
3524 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08003525 track->mHasVolumeController = true;
3526 } else {
3527 // force no volume ramp when volume controller was just disabled or removed
3528 // from effect chain to avoid volume spike
3529 if (track->mHasVolumeController) {
3530 param = AudioMixer::VOLUME;
3531 }
3532 track->mHasVolumeController = false;
3533 }
3534
Eric Laurent81784c32012-11-19 14:55:58 -08003535 // XXX: these things DON'T need to be done each time
3536 mAudioMixer->setBufferProvider(name, track);
3537 mAudioMixer->enable(name);
3538
Andy Hung6be49402014-05-30 10:42:03 -07003539 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
3540 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
3541 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08003542 mAudioMixer->setParameter(
3543 name,
3544 AudioMixer::TRACK,
3545 AudioMixer::FORMAT, (void *)track->format());
3546 mAudioMixer->setParameter(
3547 name,
3548 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003549 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07003550 mAudioMixer->setParameter(
3551 name,
3552 AudioMixer::TRACK,
3553 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08003554 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07003555 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003556 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08003557 if (reqSampleRate == 0) {
3558 reqSampleRate = mSampleRate;
3559 } else if (reqSampleRate > maxSampleRate) {
3560 reqSampleRate = maxSampleRate;
3561 }
Eric Laurent81784c32012-11-19 14:55:58 -08003562 mAudioMixer->setParameter(
3563 name,
3564 AudioMixer::RESAMPLE,
3565 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003566 (void *)(uintptr_t)reqSampleRate);
Andy Hung69aed5f2014-02-25 17:24:40 -08003567 /*
3568 * Select the appropriate output buffer for the track.
3569 *
Andy Hung98ef9782014-03-04 14:46:50 -08003570 * Tracks with effects go into their own effects chain buffer
3571 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08003572 *
3573 * Other tracks can use mMixerBuffer for higher precision
3574 * channel accumulation. If this buffer is enabled
3575 * (mMixerBufferEnabled true), then selected tracks will accumulate
3576 * into it.
3577 *
3578 */
3579 if (mMixerBufferEnabled
3580 && (track->mainBuffer() == mSinkBuffer
3581 || track->mainBuffer() == mMixerBuffer)) {
3582 mAudioMixer->setParameter(
3583 name,
3584 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08003585 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08003586 mAudioMixer->setParameter(
3587 name,
3588 AudioMixer::TRACK,
3589 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
3590 // TODO: override track->mainBuffer()?
3591 mMixerBufferValid = true;
3592 } else {
3593 mAudioMixer->setParameter(
3594 name,
3595 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08003596 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08003597 mAudioMixer->setParameter(
3598 name,
3599 AudioMixer::TRACK,
3600 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3601 }
Eric Laurent81784c32012-11-19 14:55:58 -08003602 mAudioMixer->setParameter(
3603 name,
3604 AudioMixer::TRACK,
3605 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3606
3607 // reset retry count
3608 track->mRetryCount = kMaxTrackRetries;
3609
3610 // If one track is ready, set the mixer ready if:
3611 // - the mixer was not ready during previous round OR
3612 // - no other track is not ready
3613 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
3614 mixerStatus != MIXER_TRACKS_ENABLED) {
3615 mixerStatus = MIXER_TRACKS_READY;
3616 }
3617 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003618 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Glenn Kasten82aaf942013-07-17 16:05:07 -07003619 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003620 }
Eric Laurent81784c32012-11-19 14:55:58 -08003621 // clear effect chain input buffer if an active track underruns to avoid sending
3622 // previous audio buffer again to effects
3623 chain = getEffectChain_l(track->sessionId());
3624 if (chain != 0) {
3625 chain->clearInputBuffer();
3626 }
3627
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003628 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003629 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3630 track->isStopped() || track->isPaused()) {
3631 // We have consumed all the buffers of this track.
3632 // Remove it from the list of active tracks.
3633 // TODO: use actual buffer filling status instead of latency when available from
3634 // audio HAL
3635 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3636 size_t framesWritten = mBytesWritten / mFrameSize;
3637 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
3638 if (track->isStopped()) {
3639 track->reset();
3640 }
3641 tracksToRemove->add(track);
3642 }
3643 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08003644 // No buffers for this track. Give it a few chances to
3645 // fill a buffer, then remove it from active list.
3646 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08003647 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003648 tracksToRemove->add(track);
3649 // indicate to client process that the track was disabled because of underrun;
3650 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003651 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003652 // If one track is not ready, mark the mixer also not ready if:
3653 // - the mixer was ready during previous round OR
3654 // - no other track is ready
3655 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
3656 mixerStatus != MIXER_TRACKS_READY) {
3657 mixerStatus = MIXER_TRACKS_ENABLED;
3658 }
3659 }
3660 mAudioMixer->disable(name);
3661 }
3662
3663 } // local variable scope to avoid goto warning
3664track_is_ready: ;
3665
3666 }
3667
3668 // Push the new FastMixer state if necessary
3669 bool pauseAudioWatchdog = false;
3670 if (didModify) {
3671 state->mFastTracksGen++;
3672 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3673 if (kUseFastMixer == FastMixer_Dynamic &&
3674 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3675 state->mCommand = FastMixerState::COLD_IDLE;
3676 state->mColdFutexAddr = &mFastMixerFutex;
3677 state->mColdGen++;
3678 mFastMixerFutex = 0;
3679 if (kUseFastMixer == FastMixer_Dynamic) {
3680 mNormalSink = mOutputSink;
3681 }
3682 // If we go into cold idle, need to wait for acknowledgement
3683 // so that fast mixer stops doing I/O.
3684 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3685 pauseAudioWatchdog = true;
3686 }
Eric Laurent81784c32012-11-19 14:55:58 -08003687 }
3688 if (sq != NULL) {
3689 sq->end(didModify);
3690 sq->push(block);
3691 }
3692#ifdef AUDIO_WATCHDOG
3693 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3694 mAudioWatchdog->pause();
3695 }
3696#endif
3697
3698 // Now perform the deferred reset on fast tracks that have stopped
3699 while (resetMask != 0) {
3700 size_t i = __builtin_ctz(resetMask);
3701 ALOG_ASSERT(i < count);
3702 resetMask &= ~(1 << i);
3703 sp<Track> t = mActiveTracks[i].promote();
3704 if (t == 0) {
3705 continue;
3706 }
3707 Track* track = t.get();
3708 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3709 track->reset();
3710 }
3711
3712 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08003713 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08003714
Eric Laurent97d547d2014-09-02 14:45:53 -07003715 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
3716 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07003717 }
3718
3719 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07003720 // as long as there are effects we should clear the effects buffer, to avoid
3721 // passing a non-clean buffer to the effect chain
3722 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07003723 }
Andy Hung69aed5f2014-02-25 17:24:40 -08003724 // sink or mix buffer must be cleared if all tracks are connected to an
3725 // effect chain as in this case the mixer will not write to the sink or mix buffer
3726 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08003727 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3728 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08003729 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08003730 if (mMixerBufferValid) {
3731 memset(mMixerBuffer, 0, mMixerBufferSize);
3732 // TODO: In testing, mSinkBuffer below need not be cleared because
3733 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
3734 // after mixing.
3735 //
3736 // To enforce this guarantee:
3737 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3738 // (mixedTracks == 0 && fastTracks > 0))
3739 // must imply MIXER_TRACKS_READY.
3740 // Later, we may clear buffers regardless, and skip much of this logic.
3741 }
Andy Hung98ef9782014-03-04 14:46:50 -08003742 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07003743 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003744 }
3745
3746 // if any fast tracks, then status is ready
3747 mMixerStatusIgnoringFastTracks = mixerStatus;
3748 if (fastTracks > 0) {
3749 mixerStatus = MIXER_TRACKS_READY;
3750 }
3751 return mixerStatus;
3752}
3753
3754// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07003755int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
3756 audio_format_t format, int sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08003757{
Andy Hunge8a1ced2014-05-09 15:02:21 -07003758 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08003759}
3760
3761// deleteTrackName_l() must be called with ThreadBase::mLock held
3762void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3763{
3764 ALOGV("remove track (%d) and delete from mixer", name);
3765 mAudioMixer->deleteTrackName(name);
3766}
3767
Eric Laurent10351942014-05-08 18:49:52 -07003768// checkForNewParameter_l() must be called with ThreadBase::mLock held
3769bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
3770 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08003771{
Eric Laurent81784c32012-11-19 14:55:58 -08003772 bool reconfig = false;
3773
Eric Laurent10351942014-05-08 18:49:52 -07003774 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08003775
Eric Laurent10351942014-05-08 18:49:52 -07003776 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3777 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003778 if (mFastMixer != 0) {
Eric Laurent10351942014-05-08 18:49:52 -07003779 FastMixerStateQueue *sq = mFastMixer->sq();
3780 FastMixerState *state = sq->begin();
3781 if (!(state->mCommand & FastMixerState::IDLE)) {
3782 previousCommand = state->mCommand;
3783 state->mCommand = FastMixerState::HOT_IDLE;
3784 sq->end();
3785 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3786 } else {
3787 sq->end(false /*didModify*/);
Eric Laurent81784c32012-11-19 14:55:58 -08003788 }
Eric Laurent10351942014-05-08 18:49:52 -07003789 }
Eric Laurent81784c32012-11-19 14:55:58 -08003790
Eric Laurent10351942014-05-08 18:49:52 -07003791 AudioParameter param = AudioParameter(keyValuePair);
3792 int value;
3793 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3794 reconfig = true;
3795 }
3796 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07003797 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07003798 status = BAD_VALUE;
3799 } else {
3800 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08003801 reconfig = true;
3802 }
Eric Laurent10351942014-05-08 18:49:52 -07003803 }
3804 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07003805 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07003806 status = BAD_VALUE;
3807 } else {
3808 // no need to save value, since it's constant
3809 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003810 }
Eric Laurent10351942014-05-08 18:49:52 -07003811 }
3812 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3813 // do not accept frame count changes if tracks are open as the track buffer
3814 // size depends on frame count and correct behavior would not be guaranteed
3815 // if frame count is changed after track creation
3816 if (!mTracks.isEmpty()) {
3817 status = INVALID_OPERATION;
3818 } else {
3819 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003820 }
Eric Laurent10351942014-05-08 18:49:52 -07003821 }
3822 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08003823#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07003824 // when changing the audio output device, call addBatteryData to notify
3825 // the change
3826 if (mOutDevice != value) {
3827 uint32_t params = 0;
3828 // check whether speaker is on
3829 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
3830 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08003831 }
Eric Laurent10351942014-05-08 18:49:52 -07003832
3833 audio_devices_t deviceWithoutSpeaker
3834 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3835 // check if any other device (except speaker) is on
3836 if (value & deviceWithoutSpeaker ) {
3837 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3838 }
3839
3840 if (params != 0) {
3841 addBatteryData(params);
3842 }
3843 }
Eric Laurent81784c32012-11-19 14:55:58 -08003844#endif
3845
Eric Laurent10351942014-05-08 18:49:52 -07003846 // forward device change to effects that have requested to be
3847 // aware of attached audio device.
3848 if (value != AUDIO_DEVICE_NONE) {
3849 mOutDevice = value;
3850 for (size_t i = 0; i < mEffectChains.size(); i++) {
3851 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08003852 }
3853 }
Eric Laurent10351942014-05-08 18:49:52 -07003854 }
Eric Laurent81784c32012-11-19 14:55:58 -08003855
Eric Laurent10351942014-05-08 18:49:52 -07003856 if (status == NO_ERROR) {
3857 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3858 keyValuePair.string());
3859 if (!mStandby && status == INVALID_OPERATION) {
3860 mOutput->stream->common.standby(&mOutput->stream->common);
3861 mStandby = true;
3862 mBytesWritten = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003863 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Eric Laurent10351942014-05-08 18:49:52 -07003864 keyValuePair.string());
Eric Laurent81784c32012-11-19 14:55:58 -08003865 }
Eric Laurent10351942014-05-08 18:49:52 -07003866 if (status == NO_ERROR && reconfig) {
3867 readOutputParameters_l();
3868 delete mAudioMixer;
3869 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3870 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07003871 int name = getTrackName_l(mTracks[i]->mChannelMask,
3872 mTracks[i]->mFormat, mTracks[i]->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07003873 if (name < 0) {
3874 break;
3875 }
3876 mTracks[i]->mName = name;
3877 }
3878 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3879 }
Eric Laurent81784c32012-11-19 14:55:58 -08003880 }
3881
3882 if (!(previousCommand & FastMixerState::IDLE)) {
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003883 ALOG_ASSERT(mFastMixer != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08003884 FastMixerStateQueue *sq = mFastMixer->sq();
3885 FastMixerState *state = sq->begin();
3886 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3887 state->mCommand = previousCommand;
3888 sq->end();
3889 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3890 }
3891
3892 return reconfig;
3893}
3894
3895
3896void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
3897{
3898 const size_t SIZE = 256;
3899 char buffer[SIZE];
3900 String8 result;
3901
3902 PlaybackThread::dumpInternals(fd, args);
3903
Elliott Hughes87cebad2014-05-22 10:14:43 -07003904 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Eric Laurent81784c32012-11-19 14:55:58 -08003905
3906 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003907 const FastMixerDumpState copy(mFastMixerDumpState);
Eric Laurent81784c32012-11-19 14:55:58 -08003908 copy.dump(fd);
3909
3910#ifdef STATE_QUEUE_DUMP
3911 // Similar for state queue
3912 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
3913 observerCopy.dump(fd);
3914 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
3915 mutatorCopy.dump(fd);
3916#endif
3917
Glenn Kasten46909e72013-02-26 09:20:22 -08003918#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003919 // Write the tee output to a .wav file
3920 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08003921#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003922
3923#ifdef AUDIO_WATCHDOG
3924 if (mAudioWatchdog != 0) {
3925 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
3926 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
3927 wdCopy.dump(fd);
3928 }
3929#endif
3930}
3931
3932uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
3933{
3934 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
3935}
3936
3937uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
3938{
3939 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3940}
3941
3942void AudioFlinger::MixerThread::cacheParameters_l()
3943{
3944 PlaybackThread::cacheParameters_l();
3945
3946 // FIXME: Relaxed timing because of a certain device that can't meet latency
3947 // Should be reduced to 2x after the vendor fixes the driver issue
3948 // increase threshold again due to low power audio mode. The way this warning
3949 // threshold is calculated and its usefulness should be reconsidered anyway.
3950 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
3951}
3952
3953// ----------------------------------------------------------------------------
3954
3955AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3956 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
3957 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
3958 // mLeftVolFloat, mRightVolFloat
3959{
3960}
3961
Eric Laurentbfb1b832013-01-07 09:53:42 -08003962AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3963 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
3964 ThreadBase::type_t type)
3965 : PlaybackThread(audioFlinger, output, id, device, type)
3966 // mLeftVolFloat, mRightVolFloat
3967{
3968}
3969
Eric Laurent81784c32012-11-19 14:55:58 -08003970AudioFlinger::DirectOutputThread::~DirectOutputThread()
3971{
3972}
3973
Eric Laurentbfb1b832013-01-07 09:53:42 -08003974void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
3975{
3976 audio_track_cblk_t* cblk = track->cblk();
3977 float left, right;
3978
3979 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
3980 left = right = 0;
3981 } else {
3982 float typeVolume = mStreamTypes[track->streamType()].volume;
3983 float v = mMasterVolume * typeVolume;
3984 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07003985 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
3986 left = float_from_gain(gain_minifloat_unpack_left(vlr));
3987 if (left > GAIN_FLOAT_UNITY) {
3988 left = GAIN_FLOAT_UNITY;
3989 }
3990 left *= v;
3991 right = float_from_gain(gain_minifloat_unpack_right(vlr));
3992 if (right > GAIN_FLOAT_UNITY) {
3993 right = GAIN_FLOAT_UNITY;
3994 }
3995 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003996 }
3997
3998 if (lastTrack) {
3999 if (left != mLeftVolFloat || right != mRightVolFloat) {
4000 mLeftVolFloat = left;
4001 mRightVolFloat = right;
4002
4003 // Convert volumes from float to 8.24
4004 uint32_t vl = (uint32_t)(left * (1 << 24));
4005 uint32_t vr = (uint32_t)(right * (1 << 24));
4006
4007 // Delegate volume control to effect in track effect chain if needed
4008 // only one effect chain can be present on DirectOutputThread, so if
4009 // there is one, the track is connected to it
4010 if (!mEffectChains.isEmpty()) {
4011 mEffectChains[0]->setVolume_l(&vl, &vr);
4012 left = (float)vl / (1 << 24);
4013 right = (float)vr / (1 << 24);
4014 }
4015 if (mOutput->stream->set_volume) {
4016 mOutput->stream->set_volume(mOutput->stream, left, right);
4017 }
4018 }
4019 }
4020}
4021
4022
Eric Laurent81784c32012-11-19 14:55:58 -08004023AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4024 Vector< sp<Track> > *tracksToRemove
4025)
4026{
Eric Laurentd595b7c2013-04-03 17:27:56 -07004027 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08004028 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004029 bool doHwPause = false;
4030 bool doHwResume = false;
4031 bool flushPending = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004032
4033 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07004034 for (size_t i = 0; i < count; i++) {
4035 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08004036 // The track died recently
4037 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004038 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08004039 }
4040
4041 Track* const track = t.get();
4042 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07004043 // Only consider last track started for volume and mixer state control.
4044 // In theory an older track could underrun and restart after the new one starts
4045 // but as we only care about the transition phase between two tracks on a
4046 // direct output, it is not a problem to ignore the underrun case.
4047 sp<Track> l = mLatestActiveTrack.promote();
4048 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08004049
Eric Laurentd1f69b02014-12-15 14:33:13 -08004050 if (mHwSupportsPause && track->isPausing()) {
4051 track->setPaused();
4052 if (last && !mHwPaused) {
4053 doHwPause = true;
4054 mHwPaused = true;
4055 }
4056 tracksToRemove->add(track);
4057 } else if (track->isFlushPending()) {
4058 track->flushAck();
4059 if (last) {
4060 flushPending = true;
4061 }
4062 } else if (mHwSupportsPause && track->isResumePending()){
4063 track->resumeAck();
4064 if (last) {
4065 if (mHwPaused) {
4066 doHwResume = true;
4067 mHwPaused = false;
4068 }
4069 }
4070 }
4071
Eric Laurent81784c32012-11-19 14:55:58 -08004072 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08004073 // for all its buffers to be filled before processing it.
4074 // Allow draining the buffer in case the client
4075 // app does not call stop() and relies on underrun to stop:
4076 // hence the test on (track->mRetryCount > 1).
4077 // If retryCount<=1 then track is about to underrun and be removed.
Eric Laurent81784c32012-11-19 14:55:58 -08004078 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08004079 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
4080 && (track->mRetryCount > 1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004081 minFrames = mNormalFrameCount;
4082 } else {
4083 minFrames = 1;
4084 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004085
Eric Laurentab5cdba2014-06-09 17:22:27 -07004086 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4087 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08004088 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004089 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08004090
4091 if (track->mFillingUpStatus == Track::FS_FILLED) {
4092 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004093 // make sure processVolume_l() will apply new volume even if 0
4094 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004095 if (!mHwSupportsPause) {
4096 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08004097 }
4098 }
4099
4100 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004101 processVolume_l(track, last);
4102 if (last) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004103 // reset retry count
4104 track->mRetryCount = kMaxTrackRetriesDirect;
4105 mActiveTrack = t;
4106 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004107 if (usesHwAvSync() && mHwPaused) {
4108 doHwResume = true;
4109 mHwPaused = false;
4110 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004111 }
Eric Laurent81784c32012-11-19 14:55:58 -08004112 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004113 // clear effect chain input buffer if the last active track started underruns
4114 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07004115 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004116 mEffectChains[0]->clearInputBuffer();
4117 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004118 if (track->isStopping_1()) {
4119 track->mState = TrackBase::STOPPING_2;
4120 }
4121 if ((track->sharedBuffer() != 0) || track->isStopped() ||
4122 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004123 // We have consumed all the buffers of this track.
4124 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07004125 size_t audioHALFrames;
4126 if (audio_is_linear_pcm(mFormat)) {
4127 audioHALFrames = (latency_l() * mSampleRate) / 1000;
4128 } else {
4129 audioHALFrames = 0;
4130 }
4131
Eric Laurent81784c32012-11-19 14:55:58 -08004132 size_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07004133 if (mStandby || !last ||
4134 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004135 if (track->isStopping_2()) {
4136 track->mState = TrackBase::STOPPED;
4137 }
Eric Laurent81784c32012-11-19 14:55:58 -08004138 if (track->isStopped()) {
4139 track->reset();
4140 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004141 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08004142 }
4143 } else {
4144 // No buffers for this track. Give it a few chances to
4145 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07004146 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08004147 if (--(track->mRetryCount) <= 0) {
4148 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07004149 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004150 // indicate to client process that the track was disabled because of underrun;
4151 // it will then automatically call start() when data is available
4152 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004153 } else if (last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004154 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004155 if (usesHwAvSync() && !mHwPaused && !mStandby) {
4156 doHwPause = true;
4157 mHwPaused = true;
4158 }
Eric Laurent81784c32012-11-19 14:55:58 -08004159 }
4160 }
4161 }
4162 }
4163
Eric Laurentd1f69b02014-12-15 14:33:13 -08004164 // if an active track did not command a flush, check for pending flush on stopped tracks
4165 if (!flushPending) {
4166 for (size_t i = 0; i < mTracks.size(); i++) {
4167 if (mTracks[i]->isFlushPending()) {
4168 mTracks[i]->flushAck();
4169 flushPending = true;
4170 }
4171 }
4172 }
4173
4174 // make sure the pause/flush/resume sequence is executed in the right order.
4175 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4176 // before flush and then resume HW. This can happen in case of pause/flush/resume
4177 // if resume is received before pause is executed.
4178 if (mHwSupportsPause && !mStandby &&
4179 (doHwPause || (flushPending && !mHwPaused && (count != 0)))) {
4180 mOutput->stream->pause(mOutput->stream);
4181 }
4182 if (flushPending) {
4183 flushHw_l();
4184 }
4185 if (mHwSupportsPause && !mStandby && doHwResume) {
4186 mOutput->stream->resume(mOutput->stream);
4187 }
Eric Laurent81784c32012-11-19 14:55:58 -08004188 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004189 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004190
4191 return mixerStatus;
4192}
4193
4194void AudioFlinger::DirectOutputThread::threadLoop_mix()
4195{
Eric Laurent81784c32012-11-19 14:55:58 -08004196 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08004197 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004198 // output audio to hardware
4199 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07004200 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004201 buffer.frameCount = frameCount;
4202 mActiveTrack->getNextBuffer(&buffer);
Glenn Kastenfa319e62013-07-29 17:17:38 -07004203 if (buffer.raw == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08004204 memset(curBuf, 0, frameCount * mFrameSize);
4205 break;
4206 }
4207 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
4208 frameCount -= buffer.frameCount;
4209 curBuf += buffer.frameCount * mFrameSize;
4210 mActiveTrack->releaseBuffer(&buffer);
4211 }
Andy Hung2098f272014-02-27 14:00:06 -08004212 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004213 sleepTime = 0;
4214 standbyTime = systemTime() + standbyDelay;
4215 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004216}
4217
4218void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
4219{
Eric Laurentd1f69b02014-12-15 14:33:13 -08004220 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004221 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004222 sleepTime = idleSleepTime;
4223 return;
4224 }
Eric Laurent81784c32012-11-19 14:55:58 -08004225 if (sleepTime == 0) {
4226 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4227 sleepTime = activeSleepTime;
4228 } else {
4229 sleepTime = idleSleepTime;
4230 }
4231 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08004232 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004233 sleepTime = 0;
4234 }
4235}
4236
Eric Laurentd1f69b02014-12-15 14:33:13 -08004237void AudioFlinger::DirectOutputThread::threadLoop_exit()
4238{
4239 {
4240 Mutex::Autolock _l(mLock);
4241 bool flushPending = false;
4242 for (size_t i = 0; i < mTracks.size(); i++) {
4243 if (mTracks[i]->isFlushPending()) {
4244 mTracks[i]->flushAck();
4245 flushPending = true;
4246 }
4247 }
4248 if (flushPending) {
4249 flushHw_l();
4250 }
4251 }
4252 PlaybackThread::threadLoop_exit();
4253}
4254
4255// must be called with thread mutex locked
4256bool AudioFlinger::DirectOutputThread::shouldStandby_l()
4257{
4258 bool trackPaused = false;
4259
4260 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4261 // after a timeout and we will enter standby then.
4262 if (mTracks.size() > 0) {
4263 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
4264 }
4265
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004266 return !mStandby && !(trackPaused || (usesHwAvSync() && mHwPaused));
Eric Laurentd1f69b02014-12-15 14:33:13 -08004267}
4268
Eric Laurent81784c32012-11-19 14:55:58 -08004269// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004270int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Andy Hunge8a1ced2014-05-09 15:02:21 -07004271 audio_format_t format __unused, int sessionId __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004272{
4273 return 0;
4274}
4275
4276// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004277void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004278{
4279}
4280
Eric Laurent10351942014-05-08 18:49:52 -07004281// checkForNewParameter_l() must be called with ThreadBase::mLock held
4282bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
4283 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004284{
4285 bool reconfig = false;
4286
Eric Laurent10351942014-05-08 18:49:52 -07004287 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004288
Eric Laurent10351942014-05-08 18:49:52 -07004289 AudioParameter param = AudioParameter(keyValuePair);
4290 int value;
4291 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4292 // forward device change to effects that have requested to be
4293 // aware of attached audio device.
4294 if (value != AUDIO_DEVICE_NONE) {
4295 mOutDevice = value;
4296 for (size_t i = 0; i < mEffectChains.size(); i++) {
4297 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07004298 }
4299 }
Eric Laurent81784c32012-11-19 14:55:58 -08004300 }
Eric Laurent10351942014-05-08 18:49:52 -07004301 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4302 // do not accept frame count changes if tracks are open as the track buffer
4303 // size depends on frame count and correct behavior would not be garantied
4304 // if frame count is changed after track creation
4305 if (!mTracks.isEmpty()) {
4306 status = INVALID_OPERATION;
4307 } else {
4308 reconfig = true;
4309 }
4310 }
4311 if (status == NO_ERROR) {
4312 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4313 keyValuePair.string());
4314 if (!mStandby && status == INVALID_OPERATION) {
4315 mOutput->stream->common.standby(&mOutput->stream->common);
4316 mStandby = true;
4317 mBytesWritten = 0;
4318 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4319 keyValuePair.string());
4320 }
4321 if (status == NO_ERROR && reconfig) {
4322 readOutputParameters_l();
4323 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
4324 }
4325 }
4326
Eric Laurent81784c32012-11-19 14:55:58 -08004327 return reconfig;
4328}
4329
4330uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
4331{
4332 uint32_t time;
4333 if (audio_is_linear_pcm(mFormat)) {
4334 time = PlaybackThread::activeSleepTimeUs();
4335 } else {
4336 time = 10000;
4337 }
4338 return time;
4339}
4340
4341uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
4342{
4343 uint32_t time;
4344 if (audio_is_linear_pcm(mFormat)) {
4345 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
4346 } else {
4347 time = 10000;
4348 }
4349 return time;
4350}
4351
4352uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
4353{
4354 uint32_t time;
4355 if (audio_is_linear_pcm(mFormat)) {
4356 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
4357 } else {
4358 time = 10000;
4359 }
4360 return time;
4361}
4362
4363void AudioFlinger::DirectOutputThread::cacheParameters_l()
4364{
4365 PlaybackThread::cacheParameters_l();
4366
4367 // use shorter standby delay as on normal output to release
4368 // hardware resources as soon as possible
Eric Laurent972a1732013-09-04 09:42:59 -07004369 if (audio_is_linear_pcm(mFormat)) {
4370 standbyDelay = microseconds(activeSleepTime*2);
4371 } else {
4372 standbyDelay = kOffloadStandbyDelayNs;
4373 }
Eric Laurent81784c32012-11-19 14:55:58 -08004374}
4375
Eric Laurente659ef42014-09-29 13:06:46 -07004376void AudioFlinger::DirectOutputThread::flushHw_l()
4377{
Eric Laurentd1f69b02014-12-15 14:33:13 -08004378 if (mOutput->stream->flush != NULL) {
Eric Laurente659ef42014-09-29 13:06:46 -07004379 mOutput->stream->flush(mOutput->stream);
Eric Laurentd1f69b02014-12-15 14:33:13 -08004380 }
4381 mHwPaused = false;
Eric Laurente659ef42014-09-29 13:06:46 -07004382}
4383
Eric Laurent81784c32012-11-19 14:55:58 -08004384// ----------------------------------------------------------------------------
4385
Eric Laurentbfb1b832013-01-07 09:53:42 -08004386AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07004387 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004388 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07004389 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07004390 mWriteAckSequence(0),
4391 mDrainSequence(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004392{
4393}
4394
4395AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
4396{
4397}
4398
4399void AudioFlinger::AsyncCallbackThread::onFirstRef()
4400{
4401 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
4402}
4403
4404bool AudioFlinger::AsyncCallbackThread::threadLoop()
4405{
4406 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004407 uint32_t writeAckSequence;
4408 uint32_t drainSequence;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004409
4410 {
4411 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08004412 while (!((mWriteAckSequence & 1) ||
4413 (mDrainSequence & 1) ||
4414 exitPending())) {
4415 mWaitWorkCV.wait(mLock);
4416 }
4417
Eric Laurentbfb1b832013-01-07 09:53:42 -08004418 if (exitPending()) {
4419 break;
4420 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004421 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
4422 mWriteAckSequence, mDrainSequence);
4423 writeAckSequence = mWriteAckSequence;
4424 mWriteAckSequence &= ~1;
4425 drainSequence = mDrainSequence;
4426 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004427 }
4428 {
Eric Laurent4de95592013-09-26 15:28:21 -07004429 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
4430 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004431 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004432 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004433 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004434 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004435 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004436 }
4437 }
4438 }
4439 }
4440 return false;
4441}
4442
4443void AudioFlinger::AsyncCallbackThread::exit()
4444{
4445 ALOGV("AsyncCallbackThread::exit");
4446 Mutex::Autolock _l(mLock);
4447 requestExit();
4448 mWaitWorkCV.broadcast();
4449}
4450
Eric Laurent3b4529e2013-09-05 18:09:19 -07004451void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004452{
4453 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004454 // bit 0 is cleared
4455 mWriteAckSequence = sequence << 1;
4456}
4457
4458void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
4459{
4460 Mutex::Autolock _l(mLock);
4461 // ignore unexpected callbacks
4462 if (mWriteAckSequence & 2) {
4463 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004464 mWaitWorkCV.signal();
4465 }
4466}
4467
Eric Laurent3b4529e2013-09-05 18:09:19 -07004468void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004469{
4470 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004471 // bit 0 is cleared
4472 mDrainSequence = sequence << 1;
4473}
4474
4475void AudioFlinger::AsyncCallbackThread::resetDraining()
4476{
4477 Mutex::Autolock _l(mLock);
4478 // ignore unexpected callbacks
4479 if (mDrainSequence & 2) {
4480 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004481 mWaitWorkCV.signal();
4482 }
4483}
4484
4485
4486// ----------------------------------------------------------------------------
4487AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
4488 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
4489 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD),
Eric Laurentd7e59222013-11-15 12:02:28 -08004490 mPausedBytesRemaining(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004491{
Eric Laurentfd477972013-10-25 18:10:40 -07004492 //FIXME: mStandby should be set to true by ThreadBase constructor
4493 mStandby = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004494}
4495
Eric Laurentbfb1b832013-01-07 09:53:42 -08004496void AudioFlinger::OffloadThread::threadLoop_exit()
4497{
4498 if (mFlushPending || mHwPaused) {
4499 // If a flush is pending or track was paused, just discard buffered data
4500 flushHw_l();
4501 } else {
4502 mMixerStatus = MIXER_DRAIN_ALL;
4503 threadLoop_drain();
4504 }
Uday Gupta56604aa2014-05-13 11:19:17 -07004505 if (mUseAsyncWrite) {
4506 ALOG_ASSERT(mCallbackThread != 0);
4507 mCallbackThread->exit();
4508 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004509 PlaybackThread::threadLoop_exit();
4510}
4511
4512AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
4513 Vector< sp<Track> > *tracksToRemove
4514)
4515{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004516 size_t count = mActiveTracks.size();
4517
4518 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07004519 bool doHwPause = false;
4520 bool doHwResume = false;
4521
Eric Laurentede6c3b2013-09-19 14:37:46 -07004522 ALOGV("OffloadThread::prepareTracks_l active tracks %d", count);
4523
Eric Laurentbfb1b832013-01-07 09:53:42 -08004524 // find out which tracks need to be processed
4525 for (size_t i = 0; i < count; i++) {
4526 sp<Track> t = mActiveTracks[i].promote();
4527 // The track died recently
4528 if (t == 0) {
4529 continue;
4530 }
4531 Track* const track = t.get();
4532 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07004533 // Only consider last track started for volume and mixer state control.
4534 // In theory an older track could underrun and restart after the new one starts
4535 // but as we only care about the transition phase between two tracks on a
4536 // direct output, it is not a problem to ignore the underrun case.
4537 sp<Track> l = mLatestActiveTrack.promote();
4538 bool last = l.get() == track;
4539
Haynes Mathew George7844f672014-01-15 12:32:55 -08004540 if (track->isInvalid()) {
4541 ALOGW("An invalidated track shouldn't be in active list");
4542 tracksToRemove->add(track);
4543 continue;
4544 }
4545
4546 if (track->mState == TrackBase::IDLE) {
4547 ALOGW("An idle track shouldn't be in active list");
4548 continue;
4549 }
4550
Eric Laurentbfb1b832013-01-07 09:53:42 -08004551 if (track->isPausing()) {
4552 track->setPaused();
4553 if (last) {
4554 if (!mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07004555 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004556 mHwPaused = true;
4557 }
4558 // If we were part way through writing the mixbuffer to
4559 // the HAL we must save this until we resume
4560 // BUG - this will be wrong if a different track is made active,
4561 // in that case we want to discard the pending data in the
4562 // mixbuffer and tell the client to present it again when the
4563 // track is resumed
4564 mPausedWriteLength = mCurrentWriteLength;
4565 mPausedBytesRemaining = mBytesRemaining;
4566 mBytesRemaining = 0; // stop writing
4567 }
4568 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08004569 } else if (track->isFlushPending()) {
4570 track->flushAck();
4571 if (last) {
4572 mFlushPending = true;
4573 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08004574 } else if (track->isResumePending()){
4575 track->resumeAck();
4576 if (last) {
4577 if (mPausedBytesRemaining) {
4578 // Need to continue write that was interrupted
4579 mCurrentWriteLength = mPausedWriteLength;
4580 mBytesRemaining = mPausedBytesRemaining;
4581 mPausedBytesRemaining = 0;
4582 }
4583 if (mHwPaused) {
4584 doHwResume = true;
4585 mHwPaused = false;
4586 // threadLoop_mix() will handle the case that we need to
4587 // resume an interrupted write
4588 }
4589 // enable write to audio HAL
4590 sleepTime = 0;
4591
4592 // Do not handle new data in this iteration even if track->framesReady()
4593 mixerStatus = MIXER_TRACKS_ENABLED;
4594 }
4595 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07004596 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004597 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004598 if (track->mFillingUpStatus == Track::FS_FILLED) {
4599 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004600 // make sure processVolume_l() will apply new volume even if 0
4601 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004602 }
4603
4604 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08004605 sp<Track> previousTrack = mPreviousTrack.promote();
4606 if (previousTrack != 0) {
4607 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08004608 // Flush any data still being written from last track
4609 mBytesRemaining = 0;
4610 if (mPausedBytesRemaining) {
4611 // Last track was paused so we also need to flush saved
4612 // mixbuffer state and invalidate track so that it will
4613 // re-submit that unwritten data when it is next resumed
4614 mPausedBytesRemaining = 0;
4615 // Invalidate is a bit drastic - would be more efficient
4616 // to have a flag to tell client that some of the
4617 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08004618 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004619 }
4620 // flush data already sent to the DSP if changing audio session as audio
4621 // comes from a different source. Also invalidate previous track to force a
4622 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08004623 if (previousTrack->sessionId() != track->sessionId()) {
4624 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004625 }
4626 }
4627 }
4628 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004629 // reset retry count
4630 track->mRetryCount = kMaxTrackRetriesOffload;
4631 mActiveTrack = t;
4632 mixerStatus = MIXER_TRACKS_READY;
4633 }
4634 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004635 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004636 if (track->isStopping_1()) {
4637 // Hardware buffer can hold a large amount of audio so we must
4638 // wait for all current track's data to drain before we say
4639 // that the track is stopped.
4640 if (mBytesRemaining == 0) {
4641 // Only start draining when all data in mixbuffer
4642 // has been written
4643 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
4644 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004645 // do not drain if no data was ever sent to HAL (mStandby == true)
4646 if (last && !mStandby) {
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004647 // do not modify drain sequence if we are already draining. This happens
4648 // when resuming from pause after drain.
4649 if ((mDrainSequence & 1) == 0) {
4650 sleepTime = 0;
4651 standbyTime = systemTime() + standbyDelay;
4652 mixerStatus = MIXER_DRAIN_TRACK;
4653 mDrainSequence += 2;
4654 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004655 if (mHwPaused) {
4656 // It is possible to move from PAUSED to STOPPING_1 without
4657 // a resume so we must ensure hardware is running
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004658 doHwResume = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004659 mHwPaused = false;
4660 }
4661 }
4662 }
4663 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004664 // Drain has completed or we are in standby, signal presentation complete
4665 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004666 track->mState = TrackBase::STOPPED;
4667 size_t audioHALFrames =
4668 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
4669 size_t framesWritten =
Eric Laurent665470b2014-07-03 16:37:08 -07004670 mBytesWritten / audio_stream_out_frame_size(mOutput->stream);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004671 track->presentationComplete(framesWritten, audioHALFrames);
4672 track->reset();
4673 tracksToRemove->add(track);
4674 }
4675 } else {
4676 // No buffers for this track. Give it a few chances to
4677 // fill a buffer, then remove it from active list.
4678 if (--(track->mRetryCount) <= 0) {
4679 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
4680 track->name());
4681 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004682 // indicate to client process that the track was disabled because of underrun;
4683 // it will then automatically call start() when data is available
4684 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004685 } else if (last){
4686 mixerStatus = MIXER_TRACKS_ENABLED;
4687 }
4688 }
4689 }
4690 // compute volume for this track
4691 processVolume_l(track, last);
4692 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004693
Eric Laurentea0fade2013-10-04 16:23:48 -07004694 // make sure the pause/flush/resume sequence is executed in the right order.
4695 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4696 // before flush and then resume HW. This can happen in case of pause/flush/resume
4697 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07004698 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurent972a1732013-09-04 09:42:59 -07004699 mOutput->stream->pause(mOutput->stream);
4700 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004701 if (mFlushPending) {
4702 flushHw_l();
4703 mFlushPending = false;
4704 }
Eric Laurentfd477972013-10-25 18:10:40 -07004705 if (!mStandby && doHwResume) {
Eric Laurent972a1732013-09-04 09:42:59 -07004706 mOutput->stream->resume(mOutput->stream);
4707 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004708
Eric Laurentbfb1b832013-01-07 09:53:42 -08004709 // remove all the tracks that need to be...
4710 removeTracks_l(*tracksToRemove);
4711
4712 return mixerStatus;
4713}
4714
Eric Laurentbfb1b832013-01-07 09:53:42 -08004715// must be called with thread mutex locked
4716bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
4717{
Eric Laurent3b4529e2013-09-05 18:09:19 -07004718 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
4719 mWriteAckSequence, mDrainSequence);
4720 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004721 return true;
4722 }
4723 return false;
4724}
4725
Eric Laurentbfb1b832013-01-07 09:53:42 -08004726bool AudioFlinger::OffloadThread::waitingAsyncCallback()
4727{
4728 Mutex::Autolock _l(mLock);
4729 return waitingAsyncCallback_l();
4730}
4731
4732void AudioFlinger::OffloadThread::flushHw_l()
4733{
Eric Laurente659ef42014-09-29 13:06:46 -07004734 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004735 // Flush anything still waiting in the mixbuffer
4736 mCurrentWriteLength = 0;
4737 mBytesRemaining = 0;
4738 mPausedWriteLength = 0;
4739 mPausedBytesRemaining = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08004740
Eric Laurentbfb1b832013-01-07 09:53:42 -08004741 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004742 // discard any pending drain or write ack by incrementing sequence
4743 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4744 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004745 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004746 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4747 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004748 }
4749}
4750
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08004751void AudioFlinger::OffloadThread::onAddNewTrack_l()
4752{
4753 sp<Track> previousTrack = mPreviousTrack.promote();
4754 sp<Track> latestTrack = mLatestActiveTrack.promote();
4755
4756 if (previousTrack != 0 && latestTrack != 0 &&
4757 (previousTrack->sessionId() != latestTrack->sessionId())) {
4758 mFlushPending = true;
4759 }
4760 PlaybackThread::onAddNewTrack_l();
4761}
4762
Eric Laurentbfb1b832013-01-07 09:53:42 -08004763// ----------------------------------------------------------------------------
4764
Eric Laurent81784c32012-11-19 14:55:58 -08004765AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
4766 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
4767 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
4768 DUPLICATING),
4769 mWaitTimeMs(UINT_MAX)
4770{
4771 addOutputTrack(mainThread);
4772}
4773
4774AudioFlinger::DuplicatingThread::~DuplicatingThread()
4775{
4776 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4777 mOutputTracks[i]->destroy();
4778 }
4779}
4780
4781void AudioFlinger::DuplicatingThread::threadLoop_mix()
4782{
4783 // mix buffers...
4784 if (outputsReady(outputTracks)) {
4785 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
4786 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08004787 if (mMixerBufferValid) {
4788 memset(mMixerBuffer, 0, mMixerBufferSize);
4789 } else {
4790 memset(mSinkBuffer, 0, mSinkBufferSize);
4791 }
Eric Laurent81784c32012-11-19 14:55:58 -08004792 }
4793 sleepTime = 0;
4794 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08004795 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004796 standbyTime = systemTime() + standbyDelay;
4797}
4798
4799void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
4800{
4801 if (sleepTime == 0) {
4802 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4803 sleepTime = activeSleepTime;
4804 } else {
4805 sleepTime = idleSleepTime;
4806 }
4807 } else if (mBytesWritten != 0) {
4808 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4809 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08004810 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004811 } else {
4812 // flush remaining overflow buffers in output tracks
4813 writeFrames = 0;
4814 }
4815 sleepTime = 0;
4816 }
4817}
4818
Eric Laurentbfb1b832013-01-07 09:53:42 -08004819ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004820{
Haynes Mathew Georgeec0eeaf2014-11-20 11:32:27 -08004821 // We convert the duplicating thread format to AUDIO_FORMAT_PCM_16_BIT
4822 // for delivery downstream as needed. This in-place conversion is safe as
4823 // AUDIO_FORMAT_PCM_16_BIT is smaller than any other supported format
4824 // (AUDIO_FORMAT_PCM_8_BIT is not allowed here).
4825 if (mFormat != AUDIO_FORMAT_PCM_16_BIT) {
4826 memcpy_by_audio_format(mSinkBuffer, AUDIO_FORMAT_PCM_16_BIT,
4827 mSinkBuffer, mFormat, writeFrames * mChannelCount);
4828 }
Eric Laurent81784c32012-11-19 14:55:58 -08004829 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung010a1a12014-03-13 13:57:33 -07004830 outputTracks[i]->write(reinterpret_cast<int16_t*>(mSinkBuffer), writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08004831 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07004832 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08004833 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004834}
4835
4836void AudioFlinger::DuplicatingThread::threadLoop_standby()
4837{
4838 // DuplicatingThread implements standby by stopping all tracks
4839 for (size_t i = 0; i < outputTracks.size(); i++) {
4840 outputTracks[i]->stop();
4841 }
4842}
4843
4844void AudioFlinger::DuplicatingThread::saveOutputTracks()
4845{
4846 outputTracks = mOutputTracks;
4847}
4848
4849void AudioFlinger::DuplicatingThread::clearOutputTracks()
4850{
4851 outputTracks.clear();
4852}
4853
4854void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
4855{
4856 Mutex::Autolock _l(mLock);
4857 // FIXME explain this formula
4858 size_t frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
Andy Hung010a1a12014-03-13 13:57:33 -07004859 // OutputTrack is forced to AUDIO_FORMAT_PCM_16_BIT regardless of mFormat
4860 // due to current usage case and restrictions on the AudioBufferProvider.
4861 // Actual buffer conversion is done in threadLoop_write().
4862 //
4863 // TODO: This may change in the future, depending on multichannel
4864 // (and non int16_t*) support on AF::PlaybackThread::OutputTrack
Eric Laurent81784c32012-11-19 14:55:58 -08004865 OutputTrack *outputTrack = new OutputTrack(thread,
4866 this,
4867 mSampleRate,
Andy Hung010a1a12014-03-13 13:57:33 -07004868 AUDIO_FORMAT_PCM_16_BIT,
Eric Laurent81784c32012-11-19 14:55:58 -08004869 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004870 frameCount,
4871 IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08004872 if (outputTrack->cblk() != NULL) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004873 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
Eric Laurent81784c32012-11-19 14:55:58 -08004874 mOutputTracks.add(outputTrack);
4875 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
4876 updateWaitTime_l();
4877 }
4878}
4879
4880void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
4881{
4882 Mutex::Autolock _l(mLock);
4883 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4884 if (mOutputTracks[i]->thread() == thread) {
4885 mOutputTracks[i]->destroy();
4886 mOutputTracks.removeAt(i);
4887 updateWaitTime_l();
Eric Laurentb97ee932015-05-08 10:50:03 -07004888 if (thread->getOutput() == mOutput) {
4889 mOutput = NULL;
4890 }
Eric Laurent81784c32012-11-19 14:55:58 -08004891 return;
4892 }
4893 }
Eric Laurentb97ee932015-05-08 10:50:03 -07004894 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08004895}
4896
4897// caller must hold mLock
4898void AudioFlinger::DuplicatingThread::updateWaitTime_l()
4899{
4900 mWaitTimeMs = UINT_MAX;
4901 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4902 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
4903 if (strong != 0) {
4904 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4905 if (waitTimeMs < mWaitTimeMs) {
4906 mWaitTimeMs = waitTimeMs;
4907 }
4908 }
4909 }
4910}
4911
4912
4913bool AudioFlinger::DuplicatingThread::outputsReady(
4914 const SortedVector< sp<OutputTrack> > &outputTracks)
4915{
4916 for (size_t i = 0; i < outputTracks.size(); i++) {
4917 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
4918 if (thread == 0) {
4919 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
4920 outputTracks[i].get());
4921 return false;
4922 }
4923 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4924 // see note at standby() declaration
4925 if (playbackThread->standby() && !playbackThread->isSuspended()) {
4926 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
4927 thread.get());
4928 return false;
4929 }
4930 }
4931 return true;
4932}
4933
4934uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
4935{
4936 return (mWaitTimeMs * 1000) / 2;
4937}
4938
4939void AudioFlinger::DuplicatingThread::cacheParameters_l()
4940{
4941 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
4942 updateWaitTime_l();
4943
4944 MixerThread::cacheParameters_l();
4945}
4946
4947// ----------------------------------------------------------------------------
4948// Record
4949// ----------------------------------------------------------------------------
4950
4951AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4952 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08004953 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08004954 audio_devices_t outDevice,
Glenn Kasten46909e72013-02-26 09:20:22 -08004955 audio_devices_t inDevice
4956#ifdef TEE_SINK
4957 , const sp<NBAIO_Sink>& teeSink
4958#endif
4959 ) :
Eric Laurentd3922f72013-02-01 17:57:04 -08004960 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD),
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004961 mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
Glenn Kastendeca2ae2014-02-07 10:25:56 -08004962 // mRsmpInFrames and mRsmpInFramesP2 are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08004963 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08004964#ifdef TEE_SINK
4965 , mTeeSink(teeSink)
4966#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07004967 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
4968 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07004969 // mFastCapture below
4970 , mFastCaptureFutex(0)
4971 // mInputSource
4972 // mPipeSink
4973 // mPipeSource
4974 , mPipeFramesP2(0)
4975 // mPipeMemory
4976 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07004977 , mFastTrackAvail(false)
Eric Laurent81784c32012-11-19 14:55:58 -08004978{
4979 snprintf(mName, kNameLength, "AudioIn_%X", id);
Glenn Kasten481fb672013-09-30 14:39:28 -07004980 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mName);
Eric Laurent81784c32012-11-19 14:55:58 -08004981
Glenn Kastendeca2ae2014-02-07 10:25:56 -08004982 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07004983
4984 // create an NBAIO source for the HAL input stream, and negotiate
4985 mInputSource = new AudioStreamInSource(input->stream);
4986 size_t numCounterOffers = 0;
4987 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
4988 ssize_t index = mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
4989 ALOG_ASSERT(index == 0);
4990
4991 // initialize fast capture depending on configuration
4992 bool initFastCapture;
4993 switch (kUseFastCapture) {
4994 case FastCapture_Never:
4995 initFastCapture = false;
4996 break;
4997 case FastCapture_Always:
4998 initFastCapture = true;
4999 break;
5000 case FastCapture_Static:
5001 uint32_t primaryOutputSampleRate;
5002 {
5003 AutoMutex _l(audioFlinger->mHardwareLock);
5004 primaryOutputSampleRate = audioFlinger->mPrimaryOutputSampleRate;
5005 }
5006 initFastCapture =
5007 // either capture sample rate is same as (a reasonable) primary output sample rate
5008 (((primaryOutputSampleRate == 44100 || primaryOutputSampleRate == 48000) &&
5009 (mSampleRate == primaryOutputSampleRate)) ||
5010 // or primary output sample rate is unknown, and capture sample rate is reasonable
5011 ((primaryOutputSampleRate == 0) &&
5012 ((mSampleRate == 44100 || mSampleRate == 48000)))) &&
Glenn Kasten9f81de32014-07-27 15:02:23 -07005013 // and the buffer size is < 12 ms
5014 (mFrameCount * 1000) / mSampleRate < 12;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005015 break;
5016 // case FastCapture_Dynamic:
5017 }
5018
5019 if (initFastCapture) {
5020 // create a Pipe for FastMixer to write to, and for us and fast tracks to read from
5021 NBAIO_Format format = mInputSource->format();
Glenn Kasten49d00ad2014-07-21 11:22:03 -07005022 size_t pipeFramesP2 = roundup(mSampleRate / 25); // double-buffering of 20 ms each
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005023 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
5024 void *pipeBuffer;
5025 const sp<MemoryDealer> roHeap(readOnlyHeap());
5026 sp<IMemory> pipeMemory;
5027 if ((roHeap == 0) ||
5028 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
5029 (pipeBuffer = pipeMemory->pointer()) == NULL) {
5030 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
5031 goto failed;
5032 }
5033 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
5034 memset(pipeBuffer, 0, pipeSize);
5035 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
5036 const NBAIO_Format offers[1] = {format};
5037 size_t numCounterOffers = 0;
5038 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
5039 ALOG_ASSERT(index == 0);
5040 mPipeSink = pipe;
5041 PipeReader *pipeReader = new PipeReader(*pipe);
5042 numCounterOffers = 0;
5043 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
5044 ALOG_ASSERT(index == 0);
5045 mPipeSource = pipeReader;
5046 mPipeFramesP2 = pipeFramesP2;
5047 mPipeMemory = pipeMemory;
5048
5049 // create fast capture
5050 mFastCapture = new FastCapture();
5051 FastCaptureStateQueue *sq = mFastCapture->sq();
5052#ifdef STATE_QUEUE_DUMP
5053 // FIXME
5054#endif
5055 FastCaptureState *state = sq->begin();
5056 state->mCblk = NULL;
5057 state->mInputSource = mInputSource.get();
5058 state->mInputSourceGen++;
5059 state->mPipeSink = pipe;
5060 state->mPipeSinkGen++;
5061 state->mFrameCount = mFrameCount;
5062 state->mCommand = FastCaptureState::COLD_IDLE;
5063 // already done in constructor initialization list
5064 //mFastCaptureFutex = 0;
5065 state->mColdFutexAddr = &mFastCaptureFutex;
5066 state->mColdGen++;
5067 state->mDumpState = &mFastCaptureDumpState;
5068#ifdef TEE_SINK
5069 // FIXME
5070#endif
5071 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
5072 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
5073 sq->end();
5074 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5075
5076 // start the fast capture
5077 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
5078 pid_t tid = mFastCapture->getTid();
5079 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
5080 if (err != 0) {
5081 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
5082 kPriorityFastCapture, getpid_cached, tid, err);
5083 }
5084
5085#ifdef AUDIO_WATCHDOG
5086 // FIXME
5087#endif
5088
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005089 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005090 }
5091failed: ;
5092
5093 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08005094}
5095
5096
5097AudioFlinger::RecordThread::~RecordThread()
5098{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005099 if (mFastCapture != 0) {
5100 FastCaptureStateQueue *sq = mFastCapture->sq();
5101 FastCaptureState *state = sq->begin();
5102 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5103 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5104 if (old == -1) {
5105 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5106 }
5107 }
5108 state->mCommand = FastCaptureState::EXIT;
5109 sq->end();
5110 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5111 mFastCapture->join();
5112 mFastCapture.clear();
5113 }
5114 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07005115 mAudioFlinger->unregisterWriter(mNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08005116 delete[] mRsmpInBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005117}
5118
5119void AudioFlinger::RecordThread::onFirstRef()
5120{
5121 run(mName, PRIORITY_URGENT_AUDIO);
5122}
5123
Eric Laurent81784c32012-11-19 14:55:58 -08005124bool AudioFlinger::RecordThread::threadLoop()
5125{
Eric Laurent81784c32012-11-19 14:55:58 -08005126 nsecs_t lastWarning = 0;
5127
5128 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08005129
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005130reacquire_wakelock:
5131 sp<RecordTrack> activeTrack;
Glenn Kasten2b806402013-11-20 16:37:38 -08005132 int activeTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005133 {
5134 Mutex::Autolock _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005135 size_t size = mActiveTracks.size();
5136 activeTracksGen = mActiveTracksGen;
5137 if (size > 0) {
5138 // FIXME an arbitrary choice
5139 activeTrack = mActiveTracks[0];
5140 acquireWakeLock_l(activeTrack->uid());
5141 if (size > 1) {
5142 SortedVector<int> tmp;
5143 for (size_t i = 0; i < size; i++) {
5144 tmp.add(mActiveTracks[i]->uid());
5145 }
5146 updateWakeLockUids_l(tmp);
5147 }
5148 } else {
5149 acquireWakeLock_l(-1);
5150 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005151 }
5152
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005153 // used to request a deferred sleep, to be executed later while mutex is unlocked
5154 uint32_t sleepUs = 0;
5155
5156 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005157 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005158 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07005159
Glenn Kasten5edadd42013-08-14 16:30:49 -07005160 // sleep with mutex unlocked
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005161 if (sleepUs > 0) {
5162 usleep(sleepUs);
5163 sleepUs = 0;
Glenn Kasten5edadd42013-08-14 16:30:49 -07005164 }
5165
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005166 // activeTracks accumulates a copy of a subset of mActiveTracks
5167 Vector< sp<RecordTrack> > activeTracks;
5168
Glenn Kasten735f45f2014-08-18 15:51:59 -07005169 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005170 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07005171
Glenn Kasten735f45f2014-08-18 15:51:59 -07005172 // reference to a fast track which is about to be removed
5173 sp<RecordTrack> fastTrackToRemove;
5174
Eric Laurent81784c32012-11-19 14:55:58 -08005175 { // scope for mLock
5176 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08005177
Eric Laurent021cf962014-05-13 10:18:14 -07005178 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005179
Eric Laurent000a4192014-01-29 15:17:32 -08005180 // check exitPending here because checkForNewParameters_l() and
5181 // checkForNewParameters_l() can temporarily release mLock
5182 if (exitPending()) {
5183 break;
5184 }
5185
Glenn Kasten2b806402013-11-20 16:37:38 -08005186 // if no active track(s), then standby and release wakelock
5187 size_t size = mActiveTracks.size();
5188 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07005189 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005190 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08005191 releaseWakeLock_l();
5192 ALOGV("RecordThread: loop stopping");
5193 // go to sleep
5194 mWaitWorkCV.wait(mLock);
5195 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005196 goto reacquire_wakelock;
5197 }
5198
Glenn Kasten2b806402013-11-20 16:37:38 -08005199 if (mActiveTracksGen != activeTracksGen) {
5200 activeTracksGen = mActiveTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005201 SortedVector<int> tmp;
Glenn Kasten2b806402013-11-20 16:37:38 -08005202 for (size_t i = 0; i < size; i++) {
5203 tmp.add(mActiveTracks[i]->uid());
5204 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005205 updateWakeLockUids_l(tmp);
Eric Laurent81784c32012-11-19 14:55:58 -08005206 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005207
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005208 bool doBroadcast = false;
5209 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07005210
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005211 activeTrack = mActiveTracks[i];
5212 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07005213 if (activeTrack->isFastTrack()) {
5214 ALOG_ASSERT(fastTrackToRemove == 0);
5215 fastTrackToRemove = activeTrack;
5216 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005217 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08005218 mActiveTracks.remove(activeTrack);
5219 mActiveTracksGen++;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005220 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07005221 continue;
5222 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005223
5224 TrackBase::track_state activeTrackState = activeTrack->mState;
5225 switch (activeTrackState) {
5226
5227 case TrackBase::PAUSING:
5228 mActiveTracks.remove(activeTrack);
5229 mActiveTracksGen++;
5230 doBroadcast = true;
5231 size--;
5232 continue;
5233
5234 case TrackBase::STARTING_1:
5235 sleepUs = 10000;
5236 i++;
5237 continue;
5238
5239 case TrackBase::STARTING_2:
5240 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005241 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07005242 activeTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005243 break;
5244
5245 case TrackBase::ACTIVE:
5246 break;
5247
5248 case TrackBase::IDLE:
5249 i++;
5250 continue;
5251
5252 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08005253 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07005254 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005255
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005256 activeTracks.add(activeTrack);
5257 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07005258
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005259 if (activeTrack->isFastTrack()) {
5260 ALOG_ASSERT(!mFastTrackAvail);
5261 ALOG_ASSERT(fastTrack == 0);
5262 fastTrack = activeTrack;
5263 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005264 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005265 if (doBroadcast) {
5266 mStartStopCond.broadcast();
5267 }
5268
5269 // sleep if there are no active tracks to process
5270 if (activeTracks.size() == 0) {
5271 if (sleepUs == 0) {
5272 sleepUs = kRecordThreadSleepUs;
5273 }
5274 continue;
5275 }
5276 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07005277
Eric Laurent81784c32012-11-19 14:55:58 -08005278 lockEffectChains_l(effectChains);
5279 }
5280
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005281 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07005282
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005283 size_t size = effectChains.size();
5284 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005285 // thread mutex is not locked, but effect chain is locked
5286 effectChains[i]->process_l();
5287 }
5288
Glenn Kasten735f45f2014-08-18 15:51:59 -07005289 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005290 if (mFastCapture != 0) {
5291 FastCaptureStateQueue *sq = mFastCapture->sq();
5292 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07005293 bool didModify = false;
5294 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005295 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
5296 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
5297 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5298 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5299 if (old == -1) {
5300 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5301 }
5302 }
5303 state->mCommand = FastCaptureState::READ_WRITE;
5304#if 0 // FIXME
5305 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
5306 FastCaptureDumpState::kSamplingNforLowRamDevice : FastMixerDumpState::kSamplingN);
5307#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07005308 didModify = true;
5309 }
5310 audio_track_cblk_t *cblkOld = state->mCblk;
5311 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
5312 if (cblkNew != cblkOld) {
5313 state->mCblk = cblkNew;
5314 // block until acked if removing a fast track
5315 if (cblkOld != NULL) {
5316 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
5317 }
5318 didModify = true;
5319 }
5320 sq->end(didModify);
5321 if (didModify) {
5322 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005323#if 0
5324 if (kUseFastCapture == FastCapture_Dynamic) {
5325 mNormalSource = mPipeSource;
5326 }
5327#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005328 }
5329 }
5330
Glenn Kasten735f45f2014-08-18 15:51:59 -07005331 // now run the fast track destructor with thread mutex unlocked
5332 fastTrackToRemove.clear();
5333
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005334 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
5335 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
5336 // slow, then this RecordThread will overrun by not calling HAL read often enough.
5337 // If destination is non-contiguous, first read past the nominal end of buffer, then
5338 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005339
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005340 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005341 ssize_t framesRead;
5342
5343 // If an NBAIO source is present, use it to read the normal capture's data
5344 if (mPipeSource != 0) {
5345 size_t framesToRead = mBufferSize / mFrameSize;
5346 framesRead = mPipeSource->read(&mRsmpInBuffer[rear * mChannelCount],
5347 framesToRead, AudioBufferProvider::kInvalidPTS);
5348 if (framesRead == 0) {
5349 // since pipe is non-blocking, simulate blocking input
5350 sleepUs = (framesToRead * 1000000LL) / mSampleRate;
5351 }
5352 // otherwise use the HAL / AudioStreamIn directly
5353 } else {
5354 ssize_t bytesRead = mInput->stream->read(mInput->stream,
5355 &mRsmpInBuffer[rear * mChannelCount], mBufferSize);
5356 if (bytesRead < 0) {
5357 framesRead = bytesRead;
5358 } else {
5359 framesRead = bytesRead / mFrameSize;
5360 }
5361 }
5362
5363 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
5364 ALOGE("read failed: framesRead=%d", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005365 // Force input into standby so that it tries to recover at next read attempt
5366 inputStandBy();
5367 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005368 }
5369 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005370 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005371 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005372 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005373
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005374 if (mTeeSink != 0) {
5375 (void) mTeeSink->write(&mRsmpInBuffer[rear * mChannelCount], framesRead);
5376 }
5377 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005378 {
5379 size_t part1 = mRsmpInFramesP2 - rear;
5380 if ((size_t) framesRead > part1) {
5381 memcpy(mRsmpInBuffer, &mRsmpInBuffer[mRsmpInFramesP2 * mChannelCount],
5382 (framesRead - part1) * mFrameSize);
5383 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005384 }
5385 rear = mRsmpInRear += framesRead;
5386
5387 size = activeTracks.size();
5388 // loop over each active track
5389 for (size_t i = 0; i < size; i++) {
5390 activeTrack = activeTracks[i];
5391
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005392 // skip fast tracks, as those are handled directly by FastCapture
5393 if (activeTrack->isFastTrack()) {
5394 continue;
5395 }
5396
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005397 enum {
5398 OVERRUN_UNKNOWN,
5399 OVERRUN_TRUE,
5400 OVERRUN_FALSE
5401 } overrun = OVERRUN_UNKNOWN;
5402
5403 // loop over getNextBuffer to handle circular sink
5404 for (;;) {
5405
5406 activeTrack->mSink.frameCount = ~0;
5407 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
5408 size_t framesOut = activeTrack->mSink.frameCount;
5409 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
5410
5411 int32_t front = activeTrack->mRsmpInFront;
5412 ssize_t filled = rear - front;
5413 size_t framesIn;
5414
5415 if (filled < 0) {
5416 // should not happen, but treat like a massive overrun and re-sync
5417 framesIn = 0;
5418 activeTrack->mRsmpInFront = rear;
5419 overrun = OVERRUN_TRUE;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005420 } else if ((size_t) filled <= mRsmpInFrames) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005421 framesIn = (size_t) filled;
5422 } else {
5423 // client is not keeping up with server, but give it latest data
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005424 framesIn = mRsmpInFrames;
5425 activeTrack->mRsmpInFront = front = rear - framesIn;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005426 overrun = OVERRUN_TRUE;
5427 }
5428
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005429 if (framesOut == 0 || framesIn == 0) {
5430 break;
5431 }
5432
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005433 if (activeTrack->mResampler == NULL) {
5434 // no resampling
5435 if (framesIn > framesOut) {
5436 framesIn = framesOut;
5437 } else {
5438 framesOut = framesIn;
5439 }
5440 int8_t *dst = activeTrack->mSink.i8;
5441 while (framesIn > 0) {
5442 front &= mRsmpInFramesP2 - 1;
5443 size_t part1 = mRsmpInFramesP2 - front;
5444 if (part1 > framesIn) {
5445 part1 = framesIn;
5446 }
5447 int8_t *src = (int8_t *)mRsmpInBuffer + (front * mFrameSize);
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005448 if (mChannelCount == activeTrack->mChannelCount) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005449 memcpy(dst, src, part1 * mFrameSize);
5450 } else if (mChannelCount == 1) {
Glenn Kastencd704212014-07-14 17:26:36 -07005451 upmix_to_stereo_i16_from_mono_i16((int16_t *)dst, (const int16_t *)src,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005452 part1);
5453 } else {
Glenn Kastencd704212014-07-14 17:26:36 -07005454 downmix_to_mono_i16_from_stereo_i16((int16_t *)dst, (const int16_t *)src,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005455 part1);
5456 }
5457 dst += part1 * activeTrack->mFrameSize;
5458 front += part1;
5459 framesIn -= part1;
5460 }
5461 activeTrack->mRsmpInFront += framesOut;
5462
5463 } else {
5464 // resampling
5465 // FIXME framesInNeeded should really be part of resampler API, and should
5466 // depend on the SRC ratio
5467 // to keep mRsmpInBuffer full so resampler always has sufficient input
5468 size_t framesInNeeded;
5469 // FIXME only re-calculate when it changes, and optimize for common ratios
Andy Hung8661aaf2014-07-28 14:38:41 -07005470 // Do not precompute in/out because floating point is not associative
5471 // e.g. a*b/c != a*(b/c).
5472 const double in(mSampleRate);
5473 const double out(activeTrack->mSampleRate);
5474 framesInNeeded = ceil(framesOut * in / out) + 1;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005475 ALOGV("need %u frames in to produce %u out given in/out ratio of %.4g",
Andy Hung8661aaf2014-07-28 14:38:41 -07005476 framesInNeeded, framesOut, in / out);
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005477 // Although we theoretically have framesIn in circular buffer, some of those are
5478 // unreleased frames, and thus must be discounted for purpose of budgeting.
5479 size_t unreleased = activeTrack->mRsmpInUnrel;
5480 framesIn = framesIn > unreleased ? framesIn - unreleased : 0;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005481 if (framesIn < framesInNeeded) {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005482 ALOGV("not enough to resample: have %u frames in but need %u in to "
5483 "produce %u out given in/out ratio of %.4g",
Andy Hung8661aaf2014-07-28 14:38:41 -07005484 framesIn, framesInNeeded, framesOut, in / out);
5485 size_t newFramesOut = framesIn > 0 ? floor((framesIn - 1) * out / in) : 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005486 LOG_ALWAYS_FATAL_IF(newFramesOut >= framesOut);
5487 if (newFramesOut == 0) {
5488 break;
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005489 }
Andy Hung8661aaf2014-07-28 14:38:41 -07005490 framesInNeeded = ceil(newFramesOut * in / out) + 1;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005491 ALOGV("now need %u frames in to produce %u out given out/in ratio of %.4g",
Andy Hung8661aaf2014-07-28 14:38:41 -07005492 framesInNeeded, newFramesOut, out / in);
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005493 LOG_ALWAYS_FATAL_IF(framesIn < framesInNeeded);
5494 ALOGV("success 2: have %u frames in and need %u in to produce %u out "
5495 "given in/out ratio of %.4g",
Andy Hung8661aaf2014-07-28 14:38:41 -07005496 framesIn, framesInNeeded, newFramesOut, in / out);
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005497 framesOut = newFramesOut;
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005498 } else {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005499 ALOGV("success 1: have %u in and need %u in to produce %u out "
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005500 "given in/out ratio of %.4g",
Andy Hung8661aaf2014-07-28 14:38:41 -07005501 framesIn, framesInNeeded, framesOut, in / out);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005502 }
5503
5504 // reallocate mRsmpOutBuffer as needed; we will grow but never shrink
5505 if (activeTrack->mRsmpOutFrameCount < framesOut) {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005506 // FIXME why does each track need it's own mRsmpOutBuffer? can't they share?
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005507 delete[] activeTrack->mRsmpOutBuffer;
5508 // resampler always outputs stereo
5509 activeTrack->mRsmpOutBuffer = new int32_t[framesOut * FCC_2];
5510 activeTrack->mRsmpOutFrameCount = framesOut;
5511 }
5512
5513 // resampler accumulates, but we only have one source track
5514 memset(activeTrack->mRsmpOutBuffer, 0, framesOut * FCC_2 * sizeof(int32_t));
5515 activeTrack->mResampler->resample(activeTrack->mRsmpOutBuffer, framesOut,
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005516 // FIXME how about having activeTrack implement this interface itself?
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005517 activeTrack->mResamplerBufferProvider
5518 /*this*/ /* AudioBufferProvider* */);
5519 // ditherAndClamp() works as long as all buffers returned by
5520 // activeTrack->getNextBuffer() are 32 bit aligned which should be always true.
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005521 if (activeTrack->mChannelCount == 1) {
Andy Hung84a0c6e2014-04-02 11:24:53 -07005522 // temporarily type pun mRsmpOutBuffer from Q4.27 to int16_t
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005523 ditherAndClamp(activeTrack->mRsmpOutBuffer, activeTrack->mRsmpOutBuffer,
5524 framesOut);
5525 // the resampler always outputs stereo samples:
5526 // do post stereo to mono conversion
5527 downmix_to_mono_i16_from_stereo_i16(activeTrack->mSink.i16,
Glenn Kastencd704212014-07-14 17:26:36 -07005528 (const int16_t *)activeTrack->mRsmpOutBuffer, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005529 } else {
5530 ditherAndClamp((int32_t *)activeTrack->mSink.raw,
5531 activeTrack->mRsmpOutBuffer, framesOut);
5532 }
5533 // now done with mRsmpOutBuffer
5534
5535 }
5536
5537 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
5538 overrun = OVERRUN_FALSE;
5539 }
5540
5541 if (activeTrack->mFramesToDrop == 0) {
5542 if (framesOut > 0) {
5543 activeTrack->mSink.frameCount = framesOut;
5544 activeTrack->releaseBuffer(&activeTrack->mSink);
5545 }
5546 } else {
5547 // FIXME could do a partial drop of framesOut
5548 if (activeTrack->mFramesToDrop > 0) {
5549 activeTrack->mFramesToDrop -= framesOut;
5550 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005551 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005552 }
5553 } else {
5554 activeTrack->mFramesToDrop += framesOut;
5555 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
5556 activeTrack->mSyncStartEvent->isCancelled()) {
5557 ALOGW("Synced record %s, session %d, trigger session %d",
5558 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
5559 activeTrack->sessionId(),
5560 (activeTrack->mSyncStartEvent != 0) ?
5561 activeTrack->mSyncStartEvent->triggerSession() : 0);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005562 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005563 }
5564 }
5565 }
5566
5567 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005568 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005569 }
5570 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005571
5572 switch (overrun) {
5573 case OVERRUN_TRUE:
5574 // client isn't retrieving buffers fast enough
5575 if (!activeTrack->setOverflow()) {
5576 nsecs_t now = systemTime();
5577 // FIXME should lastWarning per track?
5578 if ((now - lastWarning) > kWarningThrottleNs) {
5579 ALOGW("RecordThread: buffer overflow");
5580 lastWarning = now;
5581 }
5582 }
5583 break;
5584 case OVERRUN_FALSE:
5585 activeTrack->clearOverflow();
5586 break;
5587 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005588 break;
5589 }
5590
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005591 }
5592
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005593unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08005594 // enable changes in effect chain
5595 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005596 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08005597 }
5598
Glenn Kasten93e471f2013-08-19 08:40:07 -07005599 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08005600
5601 {
5602 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07005603 for (size_t i = 0; i < mTracks.size(); i++) {
5604 sp<RecordTrack> track = mTracks[i];
5605 track->invalidate();
5606 }
Glenn Kasten2b806402013-11-20 16:37:38 -08005607 mActiveTracks.clear();
5608 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08005609 mStartStopCond.broadcast();
5610 }
5611
5612 releaseWakeLock();
5613
5614 ALOGV("RecordThread %p exiting", this);
5615 return false;
5616}
5617
Glenn Kasten93e471f2013-08-19 08:40:07 -07005618void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08005619{
5620 if (!mStandby) {
5621 inputStandBy();
5622 mStandby = true;
5623 }
5624}
5625
5626void AudioFlinger::RecordThread::inputStandBy()
5627{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005628 // Idle the fast capture if it's currently running
5629 if (mFastCapture != 0) {
5630 FastCaptureStateQueue *sq = mFastCapture->sq();
5631 FastCaptureState *state = sq->begin();
5632 if (!(state->mCommand & FastCaptureState::IDLE)) {
5633 state->mCommand = FastCaptureState::COLD_IDLE;
5634 state->mColdFutexAddr = &mFastCaptureFutex;
5635 state->mColdGen++;
5636 mFastCaptureFutex = 0;
5637 sq->end();
5638 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
5639 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
5640#if 0
5641 if (kUseFastCapture == FastCapture_Dynamic) {
5642 // FIXME
5643 }
5644#endif
5645#ifdef AUDIO_WATCHDOG
5646 // FIXME
5647#endif
5648 } else {
5649 sq->end(false /*didModify*/);
5650 }
5651 }
Eric Laurent81784c32012-11-19 14:55:58 -08005652 mInput->stream->common.standby(&mInput->stream->common);
5653}
5654
Glenn Kasten05997e22014-03-13 15:08:33 -07005655// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07005656sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08005657 const sp<AudioFlinger::Client>& client,
5658 uint32_t sampleRate,
5659 audio_format_t format,
5660 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08005661 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08005662 int sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07005663 size_t *notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005664 int uid,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07005665 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08005666 pid_t tid,
5667 status_t *status)
5668{
Glenn Kasten74935e42013-12-19 08:56:45 -08005669 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005670 sp<RecordTrack> track;
5671 status_t lStatus;
5672
Glenn Kasten90e58b12013-07-31 16:16:02 -07005673 // client expresses a preference for FAST, but we get the final say
5674 if (*flags & IAudioFlinger::TRACK_FAST) {
5675 if (
Glenn Kasten74105912014-07-03 12:28:53 -07005676 // use case: callback handler
5677 (tid != -1) &&
5678 // frame count is not specified, or is exactly the pipe depth
5679 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005680 // PCM data
5681 audio_is_linear_pcm(format) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005682 // native format
5683 (format == mFormat) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005684 // native channel mask
5685 (channelMask == mChannelMask) &&
5686 // native hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07005687 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005688 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005689 hasFastCapture() &&
5690 // there are sufficient fast track slots available
5691 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07005692 ) {
Glenn Kasten74105912014-07-03 12:28:53 -07005693 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%u mFrameCount=%u",
Glenn Kasten90e58b12013-07-31 16:16:02 -07005694 frameCount, mFrameCount);
5695 } else {
Glenn Kasten74105912014-07-03 12:28:53 -07005696 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%u mFrameCount=%u mPipeFramesP2=%u "
5697 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005698 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Glenn Kasten74105912014-07-03 12:28:53 -07005699 frameCount, mFrameCount, mPipeFramesP2,
5700 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
5701 hasFastCapture(), tid, mFastTrackAvail);
Glenn Kasten90e58b12013-07-31 16:16:02 -07005702 *flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kasten74105912014-07-03 12:28:53 -07005703 }
5704 }
5705
5706 // compute track buffer size in frames, and suggest the notification frame count
5707 if (*flags & IAudioFlinger::TRACK_FAST) {
5708 // fast track: frame count is exactly the pipe depth
5709 frameCount = mPipeFramesP2;
5710 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
5711 *notificationFrames = mFrameCount;
5712 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07005713 // not fast track: max notification period is resampled equivalent of one HAL buffer time
5714 // or 20 ms if there is a fast capture
5715 // TODO This could be a roundupRatio inline, and const
5716 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
5717 * sampleRate + mSampleRate - 1) / mSampleRate;
5718 // minimum number of notification periods is at least kMinNotifications,
5719 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
5720 static const size_t kMinNotifications = 3;
5721 static const uint32_t kMinMs = 30;
5722 // TODO This could be a roundupRatio inline
5723 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
5724 // TODO This could be a roundupRatio inline
5725 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
5726 maxNotificationFrames;
5727 const size_t minFrameCount = maxNotificationFrames *
5728 max(kMinNotifications, minNotificationsByMs);
5729 frameCount = max(frameCount, minFrameCount);
5730 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
5731 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07005732 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07005733 }
Glenn Kasten74935e42013-12-19 08:56:45 -08005734 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07005735
Glenn Kasten15e57982013-09-24 11:52:37 -07005736 lStatus = initCheck();
5737 if (lStatus != NO_ERROR) {
5738 ALOGE("createRecordTrack_l() audio driver not initialized");
5739 goto Exit;
5740 }
Eric Laurent81784c32012-11-19 14:55:58 -08005741
5742 { // scope for mLock
5743 Mutex::Autolock _l(mLock);
5744
5745 track = new RecordTrack(this, client, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07005746 format, channelMask, frameCount, NULL, sessionId, uid,
5747 *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08005748
Glenn Kasten03003332013-08-06 15:40:54 -07005749 lStatus = track->initCheck();
5750 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07005751 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08005752 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08005753 goto Exit;
5754 }
5755 mTracks.add(track);
5756
5757 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5758 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
5759 mAudioFlinger->btNrecIsOff();
5760 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
5761 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07005762
5763 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
5764 pid_t callingPid = IPCThreadState::self()->getCallingPid();
5765 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
5766 // so ask activity manager to do this on our behalf
5767 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
5768 }
Eric Laurent81784c32012-11-19 14:55:58 -08005769 }
Glenn Kasten05997e22014-03-13 15:08:33 -07005770
Eric Laurent81784c32012-11-19 14:55:58 -08005771 lStatus = NO_ERROR;
5772
5773Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07005774 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08005775 return track;
5776}
5777
5778status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
5779 AudioSystem::sync_event_t event,
5780 int triggerSession)
5781{
5782 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
5783 sp<ThreadBase> strongMe = this;
5784 status_t status = NO_ERROR;
5785
5786 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005787 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08005788 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005789 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08005790 triggerSession,
5791 recordTrack->sessionId(),
5792 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005793 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08005794 // Sync event can be cancelled by the trigger session if the track is not in a
5795 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005796 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005797 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08005798 } else {
5799 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005800 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005801 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08005802 }
5803 }
5804
5805 {
Glenn Kasten47c20702013-08-13 15:37:35 -07005806 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08005807 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005808 if (mActiveTracks.indexOf(recordTrack) >= 0) {
5809 if (recordTrack->mState == TrackBase::PAUSING) {
5810 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005811 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005812 } else {
5813 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08005814 }
5815 return status;
5816 }
5817
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005818 // TODO consider other ways of handling this, such as changing the state to :STARTING and
5819 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
5820 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005821 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08005822 mActiveTracks.add(recordTrack);
5823 mActiveTracksGen++;
Eric Laurent83b88082014-06-20 18:31:16 -07005824 status_t status = NO_ERROR;
5825 if (recordTrack->isExternalTrack()) {
5826 mLock.unlock();
Eric Laurent4dc68062014-07-28 17:26:49 -07005827 status = AudioSystem::startInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07005828 mLock.lock();
5829 // FIXME should verify that recordTrack is still in mActiveTracks
5830 if (status != NO_ERROR) {
5831 mActiveTracks.remove(recordTrack);
5832 mActiveTracksGen++;
5833 recordTrack->clearSyncStartEvent();
5834 ALOGV("RecordThread::start error %d", status);
5835 return status;
5836 }
Eric Laurent81784c32012-11-19 14:55:58 -08005837 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005838 // Catch up with current buffer indices if thread is already running.
5839 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
5840 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
5841 // see previously buffered data before it called start(), but with greater risk of overrun.
5842
5843 recordTrack->mRsmpInFront = mRsmpInRear;
5844 recordTrack->mRsmpInUnrel = 0;
5845 // FIXME why reset?
5846 if (recordTrack->mResampler != NULL) {
5847 recordTrack->mResampler->reset();
Eric Laurent81784c32012-11-19 14:55:58 -08005848 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005849 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08005850 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08005851 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08005852 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005853 ALOGV("Record failed to start");
5854 status = BAD_VALUE;
5855 goto startError;
5856 }
Eric Laurent81784c32012-11-19 14:55:58 -08005857 return status;
5858 }
Glenn Kasten7c027242012-12-26 14:43:16 -08005859
Eric Laurent81784c32012-11-19 14:55:58 -08005860startError:
Eric Laurent83b88082014-06-20 18:31:16 -07005861 if (recordTrack->isExternalTrack()) {
Eric Laurent4dc68062014-07-28 17:26:49 -07005862 AudioSystem::stopInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07005863 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005864 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005865 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08005866 return status;
5867}
5868
Eric Laurent81784c32012-11-19 14:55:58 -08005869void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
5870{
5871 sp<SyncEvent> strongEvent = event.promote();
5872
5873 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08005874 sp<RefBase> ptr = strongEvent->cookie().promote();
5875 if (ptr != 0) {
5876 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
5877 recordTrack->handleSyncStartEvent(strongEvent);
5878 }
Eric Laurent81784c32012-11-19 14:55:58 -08005879 }
5880}
5881
Glenn Kastena8356f62013-07-25 14:37:52 -07005882bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08005883 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07005884 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005885 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08005886 return false;
5887 }
Glenn Kasten47c20702013-08-13 15:37:35 -07005888 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08005889 recordTrack->mState = TrackBase::PAUSING;
5890 // do not wait for mStartStopCond if exiting
5891 if (exitPending()) {
5892 return true;
5893 }
Glenn Kasten47c20702013-08-13 15:37:35 -07005894 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08005895 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005896 // if we have been restarted, recordTrack is in mActiveTracks here
5897 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005898 ALOGV("Record stopped OK");
5899 return true;
5900 }
5901 return false;
5902}
5903
Glenn Kasten0f11b512014-01-31 16:18:54 -08005904bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08005905{
5906 return false;
5907}
5908
Glenn Kasten0f11b512014-01-31 16:18:54 -08005909status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005910{
5911#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
5912 if (!isValidSyncEvent(event)) {
5913 return BAD_VALUE;
5914 }
5915
5916 int eventSession = event->triggerSession();
5917 status_t ret = NAME_NOT_FOUND;
5918
5919 Mutex::Autolock _l(mLock);
5920
5921 for (size_t i = 0; i < mTracks.size(); i++) {
5922 sp<RecordTrack> track = mTracks[i];
5923 if (eventSession == track->sessionId()) {
5924 (void) track->setSyncEvent(event);
5925 ret = NO_ERROR;
5926 }
5927 }
5928 return ret;
5929#else
5930 return BAD_VALUE;
5931#endif
5932}
5933
5934// destroyTrack_l() must be called with ThreadBase::mLock held
5935void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
5936{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005937 track->terminate();
5938 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08005939 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08005940 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005941 removeTrack_l(track);
5942 }
5943}
5944
5945void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
5946{
5947 mTracks.remove(track);
5948 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005949 if (track->isFastTrack()) {
5950 ALOG_ASSERT(!mFastTrackAvail);
5951 mFastTrackAvail = true;
5952 }
Eric Laurent81784c32012-11-19 14:55:58 -08005953}
5954
5955void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
5956{
5957 dumpInternals(fd, args);
5958 dumpTracks(fd, args);
5959 dumpEffectChains(fd, args);
5960}
5961
5962void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
5963{
Elliott Hughes87cebad2014-05-22 10:14:43 -07005964 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08005965
Glenn Kasten2b806402013-11-20 16:37:38 -08005966 if (mActiveTracks.size() > 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07005967 dprintf(fd, " Buffer size: %zu bytes\n", mBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005968 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07005969 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08005970 }
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005971 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005972 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Eric Laurent81784c32012-11-19 14:55:58 -08005973
Eric Laurent81784c32012-11-19 14:55:58 -08005974 dumpBase(fd, args);
5975}
5976
Glenn Kasten0f11b512014-01-31 16:18:54 -08005977void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005978{
5979 const size_t SIZE = 256;
5980 char buffer[SIZE];
5981 String8 result;
5982
Marco Nelissenb2208842014-02-07 14:00:50 -08005983 size_t numtracks = mTracks.size();
5984 size_t numactive = mActiveTracks.size();
5985 size_t numactiveseen = 0;
Elliott Hughes87cebad2014-05-22 10:14:43 -07005986 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08005987 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07005988 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08005989 RecordTrack::appendDumpHeader(result);
5990 for (size_t i = 0; i < numtracks ; ++i) {
5991 sp<RecordTrack> track = mTracks[i];
5992 if (track != 0) {
5993 bool active = mActiveTracks.indexOf(track) >= 0;
5994 if (active) {
5995 numactiveseen++;
5996 }
5997 track->dump(buffer, SIZE, active);
5998 result.append(buffer);
5999 }
Eric Laurent81784c32012-11-19 14:55:58 -08006000 }
Marco Nelissenb2208842014-02-07 14:00:50 -08006001 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006002 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006003 }
6004
Marco Nelissenb2208842014-02-07 14:00:50 -08006005 if (numactiveseen != numactive) {
6006 snprintf(buffer, SIZE, " The following tracks are in the active list but"
6007 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006008 result.append(buffer);
6009 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08006010 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08006011 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08006012 if (mTracks.indexOf(track) < 0) {
6013 track->dump(buffer, SIZE, true);
6014 result.append(buffer);
6015 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006016 }
Eric Laurent81784c32012-11-19 14:55:58 -08006017
6018 }
6019 write(fd, result.string(), result.size());
6020}
6021
6022// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006023status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
6024 AudioBufferProvider::Buffer* buffer, int64_t pts __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006025{
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006026 RecordTrack *activeTrack = mRecordTrack;
6027 sp<ThreadBase> threadBase = activeTrack->mThread.promote();
6028 if (threadBase == 0) {
6029 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006030 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006031 return NOT_ENOUGH_DATA;
6032 }
6033 RecordThread *recordThread = (RecordThread *) threadBase.get();
6034 int32_t rear = recordThread->mRsmpInRear;
6035 int32_t front = activeTrack->mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07006036 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006037 // FIXME should not be P2 (don't want to increase latency)
6038 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006039 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07006040 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006041 front &= recordThread->mRsmpInFramesP2 - 1;
6042 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07006043 if (part1 > (size_t) filled) {
6044 part1 = filled;
6045 }
6046 size_t ask = buffer->frameCount;
6047 ALOG_ASSERT(ask > 0);
6048 if (part1 > ask) {
6049 part1 = ask;
6050 }
6051 if (part1 == 0) {
6052 // Higher-level should keep mRsmpInBuffer full, and not call resampler if empty
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006053 LOG_ALWAYS_FATAL("RecordThread::getNextBuffer() starved");
Glenn Kasten85948432013-08-19 12:09:05 -07006054 buffer->raw = NULL;
6055 buffer->frameCount = 0;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006056 activeTrack->mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07006057 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08006058 }
6059
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006060 buffer->raw = recordThread->mRsmpInBuffer + front * recordThread->mChannelCount;
Glenn Kasten85948432013-08-19 12:09:05 -07006061 buffer->frameCount = part1;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006062 activeTrack->mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08006063 return NO_ERROR;
6064}
6065
6066// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006067void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
6068 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006069{
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006070 RecordTrack *activeTrack = mRecordTrack;
Glenn Kasten85948432013-08-19 12:09:05 -07006071 size_t stepCount = buffer->frameCount;
6072 if (stepCount == 0) {
6073 return;
6074 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006075 ALOG_ASSERT(stepCount <= activeTrack->mRsmpInUnrel);
6076 activeTrack->mRsmpInUnrel -= stepCount;
6077 activeTrack->mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07006078 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006079 buffer->frameCount = 0;
6080}
6081
Eric Laurent10351942014-05-08 18:49:52 -07006082bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
6083 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006084{
6085 bool reconfig = false;
6086
Eric Laurent10351942014-05-08 18:49:52 -07006087 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006088
Eric Laurent10351942014-05-08 18:49:52 -07006089 audio_format_t reqFormat = mFormat;
6090 uint32_t samplingRate = mSampleRate;
6091 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
6092
6093 AudioParameter param = AudioParameter(keyValuePair);
6094 int value;
6095 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
6096 // channel count change can be requested. Do we mandate the first client defines the
6097 // HAL sampling rate and channel count or do we allow changes on the fly?
6098 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6099 samplingRate = value;
6100 reconfig = true;
6101 }
6102 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
6103 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
6104 status = BAD_VALUE;
6105 } else {
6106 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08006107 reconfig = true;
6108 }
Eric Laurent10351942014-05-08 18:49:52 -07006109 }
6110 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
6111 audio_channel_mask_t mask = (audio_channel_mask_t) value;
6112 if (mask != AUDIO_CHANNEL_IN_MONO && mask != AUDIO_CHANNEL_IN_STEREO) {
6113 status = BAD_VALUE;
6114 } else {
6115 channelMask = mask;
6116 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006117 }
Eric Laurent10351942014-05-08 18:49:52 -07006118 }
6119 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6120 // do not accept frame count changes if tracks are open as the track buffer
6121 // size depends on frame count and correct behavior would not be guaranteed
6122 // if frame count is changed after track creation
6123 if (mActiveTracks.size() > 0) {
6124 status = INVALID_OPERATION;
6125 } else {
6126 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006127 }
Eric Laurent10351942014-05-08 18:49:52 -07006128 }
6129 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6130 // forward device change to effects that have requested to be
6131 // aware of attached audio device.
6132 for (size_t i = 0; i < mEffectChains.size(); i++) {
6133 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08006134 }
Eric Laurent81784c32012-11-19 14:55:58 -08006135
Eric Laurent10351942014-05-08 18:49:52 -07006136 // store input device and output device but do not forward output device to audio HAL.
6137 // Note that status is ignored by the caller for output device
6138 // (see AudioFlinger::setParameters()
6139 if (audio_is_output_devices(value)) {
6140 mOutDevice = value;
6141 status = BAD_VALUE;
6142 } else {
6143 mInDevice = value;
6144 // disable AEC and NS if the device is a BT SCO headset supporting those
6145 // pre processings
6146 if (mTracks.size() > 0) {
6147 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6148 mAudioFlinger->btNrecIsOff();
6149 for (size_t i = 0; i < mTracks.size(); i++) {
6150 sp<RecordTrack> track = mTracks[i];
6151 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
6152 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08006153 }
6154 }
6155 }
Eric Laurent10351942014-05-08 18:49:52 -07006156 }
6157 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
6158 mAudioSource != (audio_source_t)value) {
6159 // forward device change to effects that have requested to be
6160 // aware of attached audio device.
6161 for (size_t i = 0; i < mEffectChains.size(); i++) {
6162 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08006163 }
Eric Laurent10351942014-05-08 18:49:52 -07006164 mAudioSource = (audio_source_t)value;
6165 }
Glenn Kastene198c362013-08-13 09:13:36 -07006166
Eric Laurent10351942014-05-08 18:49:52 -07006167 if (status == NO_ERROR) {
6168 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6169 keyValuePair.string());
6170 if (status == INVALID_OPERATION) {
6171 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006172 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6173 keyValuePair.string());
Eric Laurent10351942014-05-08 18:49:52 -07006174 }
6175 if (reconfig) {
6176 if (status == BAD_VALUE &&
6177 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
6178 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
6179 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
6180 <= (2 * samplingRate)) &&
Andy Hunge5412692014-05-16 11:25:07 -07006181 audio_channel_count_from_in_mask(
6182 mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
Eric Laurent10351942014-05-08 18:49:52 -07006183 (channelMask == AUDIO_CHANNEL_IN_MONO ||
6184 channelMask == AUDIO_CHANNEL_IN_STEREO)) {
6185 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006186 }
Eric Laurent10351942014-05-08 18:49:52 -07006187 if (status == NO_ERROR) {
6188 readInputParameters_l();
6189 sendIoConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08006190 }
6191 }
Eric Laurent81784c32012-11-19 14:55:58 -08006192 }
Eric Laurent10351942014-05-08 18:49:52 -07006193
Eric Laurent81784c32012-11-19 14:55:58 -08006194 return reconfig;
6195}
6196
6197String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6198{
Eric Laurent81784c32012-11-19 14:55:58 -08006199 Mutex::Autolock _l(mLock);
6200 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07006201 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08006202 }
6203
Glenn Kastend8ea6992013-07-16 14:17:15 -07006204 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
6205 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08006206 free(s);
6207 return out_s8;
6208}
6209
Eric Laurent021cf962014-05-13 10:18:14 -07006210void AudioFlinger::RecordThread::audioConfigChanged(int event, int param __unused) {
Eric Laurent81784c32012-11-19 14:55:58 -08006211 AudioSystem::OutputDescriptor desc;
Glenn Kastenb2737d02013-08-19 12:03:11 -07006212 const void *param2 = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006213
6214 switch (event) {
6215 case AudioSystem::INPUT_OPENED:
6216 case AudioSystem::INPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07006217 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08006218 desc.samplingRate = mSampleRate;
6219 desc.format = mFormat;
6220 desc.frameCount = mFrameCount;
6221 desc.latency = 0;
6222 param2 = &desc;
6223 break;
6224
6225 case AudioSystem::INPUT_CLOSED:
6226 default:
6227 break;
6228 }
Eric Laurent021cf962014-05-13 10:18:14 -07006229 mAudioFlinger->audioConfigChanged(event, mId, param2);
Eric Laurent81784c32012-11-19 14:55:58 -08006230}
6231
Glenn Kastendeca2ae2014-02-07 10:25:56 -08006232void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006233{
Eric Laurent81784c32012-11-19 14:55:58 -08006234 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
6235 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Andy Hunge5412692014-05-16 11:25:07 -07006236 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Andy Hung463be252014-07-10 16:56:07 -07006237 mHALFormat = mInput->stream->common.get_format(&mInput->stream->common);
6238 mFormat = mHALFormat;
Glenn Kasten291bb6d2013-07-16 17:23:39 -07006239 if (mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08006240 ALOGE("HAL format %#x not supported; must be AUDIO_FORMAT_PCM_16_BIT", mFormat);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07006241 }
Eric Laurent665470b2014-07-03 16:37:08 -07006242 mFrameSize = audio_stream_in_frame_size(mInput->stream);
Glenn Kasten548efc92012-11-29 08:48:51 -08006243 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
6244 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006245 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08006246 // With 7 HAL buffers, we can guarantee ability to down-sample the input by ratio of 6:1 to
Glenn Kasten85948432013-08-19 12:09:05 -07006247 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08006248 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006249 // A larger value should allow more old data to be read after a track calls start(),
6250 // without increasing latency.
Glenn Kastene8426142014-02-28 16:45:03 -08006251 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07006252 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006253 delete[] mRsmpInBuffer;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006254
6255 // TODO optimize audio capture buffer sizes ...
6256 // Here we calculate the size of the sliding buffer used as a source
6257 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
6258 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
6259 // be better to have it derived from the pipe depth in the long term.
6260 // The current value is higher than necessary. However it should not add to latency.
6261
Glenn Kasten85948432013-08-19 12:09:05 -07006262 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Andy Hung8c987fa2015-09-24 16:36:56 -07006263 size_t bufferSizeInShorts = (mRsmpInFramesP2 + mFrameCount - 1) * mChannelCount;
6264 mRsmpInBuffer = new int16_t[bufferSizeInShorts];
6265 memset(mRsmpInBuffer, 0, bufferSizeInShorts * sizeof(mRsmpInBuffer[0]));
Eric Laurent81784c32012-11-19 14:55:58 -08006266
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006267 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
6268 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08006269}
6270
Glenn Kasten5f972c02014-01-13 09:59:31 -08006271uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08006272{
6273 Mutex::Autolock _l(mLock);
6274 if (initCheck() != NO_ERROR) {
6275 return 0;
6276 }
6277
6278 return mInput->stream->get_input_frames_lost(mInput->stream);
6279}
6280
6281uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
6282{
6283 Mutex::Autolock _l(mLock);
6284 uint32_t result = 0;
6285 if (getEffectChain_l(sessionId) != 0) {
6286 result = EFFECT_SESSION;
6287 }
6288
6289 for (size_t i = 0; i < mTracks.size(); ++i) {
6290 if (sessionId == mTracks[i]->sessionId()) {
6291 result |= TRACK_SESSION;
6292 break;
6293 }
6294 }
6295
6296 return result;
6297}
6298
6299KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
6300{
6301 KeyedVector<int, bool> ids;
6302 Mutex::Autolock _l(mLock);
6303 for (size_t j = 0; j < mTracks.size(); ++j) {
6304 sp<RecordThread::RecordTrack> track = mTracks[j];
6305 int sessionId = track->sessionId();
6306 if (ids.indexOfKey(sessionId) < 0) {
6307 ids.add(sessionId, true);
6308 }
6309 }
6310 return ids;
6311}
6312
6313AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
6314{
6315 Mutex::Autolock _l(mLock);
6316 AudioStreamIn *input = mInput;
6317 mInput = NULL;
6318 return input;
6319}
6320
6321// this method must always be called either with ThreadBase mLock held or inside the thread loop
6322audio_stream_t* AudioFlinger::RecordThread::stream() const
6323{
6324 if (mInput == NULL) {
6325 return NULL;
6326 }
6327 return &mInput->stream->common;
6328}
6329
6330status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6331{
6332 // only one chain per input thread
6333 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07006334 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08006335 return INVALID_OPERATION;
6336 }
6337 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07006338 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08006339 chain->setInBuffer(NULL);
6340 chain->setOutBuffer(NULL);
6341
6342 checkSuspendOnAddEffectChain_l(chain);
6343
Eric Laurent1b928682014-10-02 19:41:47 -07006344 // make sure enabled pre processing effects state is communicated to the HAL as we
6345 // just moved them to a new input stream.
6346 chain->syncHalEffectsState();
6347
Eric Laurent81784c32012-11-19 14:55:58 -08006348 mEffectChains.add(chain);
6349
6350 return NO_ERROR;
6351}
6352
6353size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6354{
6355 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
6356 ALOGW_IF(mEffectChains.size() != 1,
6357 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6358 chain.get(), mEffectChains.size(), this);
6359 if (mEffectChains.size() == 1) {
6360 mEffectChains.removeAt(0);
6361 }
6362 return 0;
6363}
6364
Eric Laurent1c333e22014-05-20 10:48:17 -07006365status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
6366 audio_patch_handle_t *handle)
6367{
6368 status_t status = NO_ERROR;
6369 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
6370 // store new device and send to effects
6371 mInDevice = patch->sources[0].ext.device.type;
6372 for (size_t i = 0; i < mEffectChains.size(); i++) {
6373 mEffectChains[i]->setDevice_l(mInDevice);
6374 }
6375
6376 // disable AEC and NS if the device is a BT SCO headset supporting those
6377 // pre processings
6378 if (mTracks.size() > 0) {
6379 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6380 mAudioFlinger->btNrecIsOff();
6381 for (size_t i = 0; i < mTracks.size(); i++) {
6382 sp<RecordTrack> track = mTracks[i];
6383 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
6384 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
6385 }
6386 }
6387
6388 // store new source and send to effects
6389 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
6390 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
6391 for (size_t i = 0; i < mEffectChains.size(); i++) {
6392 mEffectChains[i]->setAudioSource_l(mAudioSource);
6393 }
6394 }
6395
6396 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
6397 status = hwDevice->create_audio_patch(hwDevice,
6398 patch->num_sources,
6399 patch->sources,
6400 patch->num_sinks,
6401 patch->sinks,
6402 handle);
6403 } else {
6404 ALOG_ASSERT(false, "createAudioPatch_l() called on a pre 3.0 HAL");
6405 }
6406 return status;
6407}
6408
6409status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
6410{
6411 status_t status = NO_ERROR;
6412 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
6413 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
6414 status = hwDevice->release_audio_patch(hwDevice, handle);
6415 } else {
6416 ALOG_ASSERT(false, "releaseAudioPatch_l() called on a pre 3.0 HAL");
6417 }
6418 return status;
6419}
6420
Eric Laurent83b88082014-06-20 18:31:16 -07006421void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
6422{
6423 Mutex::Autolock _l(mLock);
6424 mTracks.add(record);
6425}
6426
6427void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
6428{
6429 Mutex::Autolock _l(mLock);
6430 destroyTrack_l(record);
6431}
6432
6433void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
6434{
6435 ThreadBase::getAudioPortConfig(config);
6436 config->role = AUDIO_PORT_ROLE_SINK;
6437 config->ext.mix.hw_module = mInput->audioHwDev->handle();
6438 config->ext.mix.usecase.source = mAudioSource;
6439}
Eric Laurent1c333e22014-05-20 10:48:17 -07006440
Eric Laurent81784c32012-11-19 14:55:58 -08006441}; // namespace android