blob: f4ba3e3c8585a215630bada198964bdc8fb8e1d2 [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 Laurent84c39212016-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 Laurent84c39212016-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 Laurent84c39212016-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 Laurent84c39212016-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 Laurent84c39212016-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 Laurent84c39212016-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),
1221 // mLatchD, mLatchQ,
1222 mLatchDValid(false), mLatchQValid(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001223{
1224 snprintf(mName, kNameLength, "AudioOut_%X", id);
Glenn Kasten9e58b552013-01-18 15:09:48 -08001225 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mName);
Eric Laurent81784c32012-11-19 14:55:58 -08001226
1227 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1228 // it would be safer to explicitly pass initial masterVolume/masterMute as
1229 // parameter.
1230 //
1231 // If the HAL we are using has support for master volume or master mute,
1232 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1233 // and the mute set to false).
1234 mMasterVolume = audioFlinger->masterVolume_l();
1235 mMasterMute = audioFlinger->masterMute_l();
1236 if (mOutput && mOutput->audioHwDev) {
1237 if (mOutput->audioHwDev->canSetMasterVolume()) {
1238 mMasterVolume = 1.0;
1239 }
1240
1241 if (mOutput->audioHwDev->canSetMasterMute()) {
1242 mMasterMute = false;
1243 }
1244 }
1245
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001246 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001247
1248 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
1249 // There is no AUDIO_STREAM_MIN, and ++ 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 }
1255 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1256 // because mAudioFlinger doesn't have one to copy from
1257}
1258
1259AudioFlinger::PlaybackThread::~PlaybackThread()
1260{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001261 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001262 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001263 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001264 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001265}
1266
1267void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1268{
1269 dumpInternals(fd, args);
1270 dumpTracks(fd, args);
1271 dumpEffectChains(fd, args);
1272}
1273
Glenn Kasten0f11b512014-01-31 16:18:54 -08001274void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001275{
1276 const size_t SIZE = 256;
1277 char buffer[SIZE];
1278 String8 result;
1279
Marco Nelissenb2208842014-02-07 14:00:50 -08001280 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001281 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1282 const stream_type_t *st = &mStreamTypes[i];
1283 if (i > 0) {
1284 result.appendFormat(", ");
1285 }
1286 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1287 if (st->mute) {
1288 result.append("M");
1289 }
1290 }
1291 result.append("\n");
1292 write(fd, result.string(), result.length());
1293 result.clear();
1294
Eric Laurent81784c32012-11-19 14:55:58 -08001295 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1296 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001297 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001298 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001299
1300 size_t numtracks = mTracks.size();
1301 size_t numactive = mActiveTracks.size();
Elliott Hughes87cebad2014-05-22 10:14:43 -07001302 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001303 size_t numactiveseen = 0;
1304 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07001305 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08001306 Track::appendDumpHeader(result);
1307 for (size_t i = 0; i < numtracks; ++i) {
1308 sp<Track> track = mTracks[i];
1309 if (track != 0) {
1310 bool active = mActiveTracks.indexOf(track) >= 0;
1311 if (active) {
1312 numactiveseen++;
1313 }
1314 track->dump(buffer, SIZE, active);
1315 result.append(buffer);
1316 }
1317 }
1318 } else {
1319 result.append("\n");
1320 }
1321 if (numactiveseen != numactive) {
1322 // some tracks in the active list were not in the tracks list
1323 snprintf(buffer, SIZE, " The following tracks are in the active list but"
1324 " not in the track list\n");
1325 result.append(buffer);
1326 Track::appendDumpHeader(result);
1327 for (size_t i = 0; i < numactive; ++i) {
1328 sp<Track> track = mActiveTracks[i].promote();
1329 if (track != 0 && mTracks.indexOf(track) < 0) {
1330 track->dump(buffer, SIZE, true);
1331 result.append(buffer);
1332 }
1333 }
1334 }
1335
1336 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001337}
1338
1339void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1340{
Elliott Hughes87cebad2014-05-22 10:14:43 -07001341 dprintf(fd, "\nOutput thread %p:\n", this);
1342 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
1343 dprintf(fd, " Last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1344 dprintf(fd, " Total writes: %d\n", mNumWrites);
1345 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1346 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1347 dprintf(fd, " Suspend count: %d\n", mSuspended);
1348 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1349 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1350 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1351 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent81784c32012-11-19 14:55:58 -08001352
1353 dumpBase(fd, args);
1354}
1355
1356// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001357
1358void AudioFlinger::PlaybackThread::onFirstRef()
1359{
1360 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
1361}
1362
1363// ThreadBase virtuals
1364void AudioFlinger::PlaybackThread::preExit()
1365{
1366 ALOGV(" preExit()");
1367 // FIXME this is using hard-coded strings but in the future, this functionality will be
1368 // converted to use audio HAL extensions required to support tunneling
1369 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1370}
1371
1372// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1373sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1374 const sp<AudioFlinger::Client>& client,
1375 audio_stream_type_t streamType,
1376 uint32_t sampleRate,
1377 audio_format_t format,
1378 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001379 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001380 const sp<IMemory>& sharedBuffer,
1381 int sessionId,
1382 IAudioFlinger::track_flags_t *flags,
1383 pid_t tid,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001384 int uid,
Eric Laurent81784c32012-11-19 14:55:58 -08001385 status_t *status)
1386{
Glenn Kasten74935e42013-12-19 08:56:45 -08001387 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001388 sp<Track> track;
1389 status_t lStatus;
1390
1391 bool isTimed = (*flags & IAudioFlinger::TRACK_TIMED) != 0;
1392
1393 // client expresses a preference for FAST, but we get the final say
1394 if (*flags & IAudioFlinger::TRACK_FAST) {
1395 if (
1396 // not timed
1397 (!isTimed) &&
1398 // either of these use cases:
1399 (
1400 // use case 1: shared buffer with any frame count
1401 (
1402 (sharedBuffer != 0)
1403 ) ||
1404 // use case 2: callback handler and frame count is default or at least as large as HAL
1405 (
1406 (tid != -1) &&
1407 ((frameCount == 0) ||
Glenn Kastenb5fed682013-12-03 09:06:43 -08001408 (frameCount >= mFrameCount))
Eric Laurent81784c32012-11-19 14:55:58 -08001409 )
1410 ) &&
1411 // PCM data
1412 audio_is_linear_pcm(format) &&
Andy Hung9a592762014-07-21 21:56:01 -07001413 // identical channel mask to sink, or mono in and stereo sink
1414 (channelMask == mChannelMask ||
1415 (channelMask == AUDIO_CHANNEL_OUT_MONO &&
1416 mChannelMask == AUDIO_CHANNEL_OUT_STEREO)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001417 // hardware sample rate
1418 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001419 // normal mixer has an associated fast mixer
1420 hasFastMixer() &&
1421 // there are sufficient fast track slots available
1422 (mFastTrackAvailMask != 0)
1423 // FIXME test that MixerThread for this fast track has a capable output HAL
1424 // FIXME add a permission test also?
1425 ) {
1426 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1427 if (frameCount == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001428 // read the fast track multiplier property the first time it is needed
1429 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1430 if (ok != 0) {
1431 ALOGE("%s pthread_once failed: %d", __func__, ok);
1432 }
1433 frameCount = mFrameCount * sFastTrackMultiplier;
Eric Laurent81784c32012-11-19 14:55:58 -08001434 }
1435 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
1436 frameCount, mFrameCount);
1437 } else {
1438 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
Andy Hung6146c082014-03-18 11:56:15 -07001439 "mFrameCount=%d format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
1440 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001441 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Andy Hung6146c082014-03-18 11:56:15 -07001442 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001443 audio_is_linear_pcm(format),
1444 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
1445 *flags &= ~IAudioFlinger::TRACK_FAST;
1446 // For compatibility with AudioTrack calculation, buffer depth is forced
1447 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1448 // This is probably too conservative, but legacy application code may depend on it.
1449 // If you change this calculation, also review the start threshold which is related.
1450 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1451 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1452 if (minBufCount < 2) {
1453 minBufCount = 2;
1454 }
1455 size_t minFrameCount = mNormalFrameCount * minBufCount;
1456 if (frameCount < minFrameCount) {
1457 frameCount = minFrameCount;
1458 }
1459 }
1460 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001461 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001462
Glenn Kastenc3df8382014-03-13 15:05:25 -07001463 switch (mType) {
1464
1465 case DIRECT:
Glenn Kasten993fa062014-05-02 11:14:34 -07001466 if (audio_is_linear_pcm(format)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001467 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001468 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1469 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001470 sampleRate, format, channelMask, mOutput, mFormat);
1471 lStatus = BAD_VALUE;
1472 goto Exit;
1473 }
1474 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001475 break;
1476
1477 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001478 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001479 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1480 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001481 sampleRate, format, channelMask, mOutput, mFormat);
1482 lStatus = BAD_VALUE;
1483 goto Exit;
1484 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001485 break;
1486
1487 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07001488 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001489 ALOGE("createTrack_l() Bad parameter: format %#x \""
1490 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001491 format, mOutput, mFormat);
1492 lStatus = BAD_VALUE;
1493 goto Exit;
1494 }
Andy Hungcd044842014-08-07 11:04:34 -07001495 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08001496 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1497 lStatus = BAD_VALUE;
1498 goto Exit;
1499 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001500 break;
1501
Eric Laurent81784c32012-11-19 14:55:58 -08001502 }
1503
1504 lStatus = initCheck();
1505 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07001506 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08001507 goto Exit;
1508 }
1509
1510 { // scope for mLock
1511 Mutex::Autolock _l(mLock);
1512
1513 // all tracks in same audio session must share the same routing strategy otherwise
1514 // conflicts will happen when tracks are moved from one output to another by audio policy
1515 // manager
1516 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1517 for (size_t i = 0; i < mTracks.size(); ++i) {
1518 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07001519 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001520 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1521 if (sessionId == t->sessionId() && strategy != actual) {
1522 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1523 strategy, actual);
1524 lStatus = BAD_VALUE;
1525 goto Exit;
1526 }
1527 }
1528 }
1529
1530 if (!isTimed) {
1531 track = new Track(this, client, streamType, sampleRate, format,
Eric Laurent83b88082014-06-20 18:31:16 -07001532 channelMask, frameCount, NULL, sharedBuffer,
1533 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08001534 } else {
1535 track = TimedTrack::create(this, client, streamType, sampleRate, format,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001536 channelMask, frameCount, sharedBuffer, sessionId, uid);
Eric Laurent81784c32012-11-19 14:55:58 -08001537 }
Glenn Kasten03003332013-08-06 15:40:54 -07001538
1539 // new Track always returns non-NULL,
1540 // but TimedTrack::create() is a factory that could fail by returning NULL
1541 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
1542 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08001543 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001544 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08001545 goto Exit;
1546 }
1547 mTracks.add(track);
1548
1549 sp<EffectChain> chain = getEffectChain_l(sessionId);
1550 if (chain != 0) {
1551 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1552 track->setMainBuffer(chain->inBuffer());
1553 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1554 chain->incTrackCnt();
1555 }
1556
1557 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1558 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1559 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1560 // so ask activity manager to do this on our behalf
1561 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1562 }
1563 }
1564
1565 lStatus = NO_ERROR;
1566
1567Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001568 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001569 return track;
1570}
1571
1572uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1573{
1574 return latency;
1575}
1576
1577uint32_t AudioFlinger::PlaybackThread::latency() const
1578{
1579 Mutex::Autolock _l(mLock);
1580 return latency_l();
1581}
1582uint32_t AudioFlinger::PlaybackThread::latency_l() const
1583{
1584 if (initCheck() == NO_ERROR) {
1585 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
1586 } else {
1587 return 0;
1588 }
1589}
1590
1591void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1592{
1593 Mutex::Autolock _l(mLock);
1594 // Don't apply master volume in SW if our HAL can do it for us.
1595 if (mOutput && mOutput->audioHwDev &&
1596 mOutput->audioHwDev->canSetMasterVolume()) {
1597 mMasterVolume = 1.0;
1598 } else {
1599 mMasterVolume = value;
1600 }
1601}
1602
1603void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1604{
1605 Mutex::Autolock _l(mLock);
1606 // Don't apply master mute in SW if our HAL can do it for us.
1607 if (mOutput && mOutput->audioHwDev &&
1608 mOutput->audioHwDev->canSetMasterMute()) {
1609 mMasterMute = false;
1610 } else {
1611 mMasterMute = muted;
1612 }
1613}
1614
1615void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
1616{
1617 Mutex::Autolock _l(mLock);
1618 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001619 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001620}
1621
1622void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
1623{
1624 Mutex::Autolock _l(mLock);
1625 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001626 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001627}
1628
1629float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
1630{
1631 Mutex::Autolock _l(mLock);
1632 return mStreamTypes[stream].volume;
1633}
1634
1635// addTrack_l() must be called with ThreadBase::mLock held
1636status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1637{
1638 status_t status = ALREADY_EXISTS;
1639
1640 // set retry count for buffer fill
1641 track->mRetryCount = kMaxTrackStartupRetries;
1642 if (mActiveTracks.indexOf(track) < 0) {
1643 // the track is newly added, make sure it fills up all its
1644 // buffers before playing. This is to ensure the client will
1645 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07001646 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001647 TrackBase::track_state state = track->mState;
1648 mLock.unlock();
1649 status = AudioSystem::startOutput(mId, track->streamType(), track->sessionId());
1650 mLock.lock();
1651 // abort track was stopped/paused while we released the lock
1652 if (state != track->mState) {
1653 if (status == NO_ERROR) {
1654 mLock.unlock();
1655 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
1656 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
Andy Hung09a50072014-02-27 14:30:47 -08001872 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08001873 double multiplier = 1.0;
1874 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
1875 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08001876 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
1877 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Eric Laurent81784c32012-11-19 14:55:58 -08001878 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
1879 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
1880 maxNormalFrameCount = maxNormalFrameCount & ~15;
1881 if (maxNormalFrameCount < minNormalFrameCount) {
1882 maxNormalFrameCount = minNormalFrameCount;
1883 }
1884 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
1885 if (multiplier <= 1.0) {
1886 multiplier = 1.0;
1887 } else if (multiplier <= 2.0) {
1888 if (2 * mFrameCount <= maxNormalFrameCount) {
1889 multiplier = 2.0;
1890 } else {
1891 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
1892 }
1893 } else {
1894 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
Andy Hung09a50072014-02-27 14:30:47 -08001895 // 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 -08001896 // track, but we sometimes have to do this to satisfy the maximum frame count
1897 // constraint)
1898 // FIXME this rounding up should not be done if no HAL SRC
1899 uint32_t truncMult = (uint32_t) multiplier;
1900 if ((truncMult & 1)) {
1901 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
1902 ++truncMult;
1903 }
1904 }
1905 multiplier = (double) truncMult;
1906 }
1907 }
1908 mNormalFrameCount = multiplier * mFrameCount;
1909 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07001910 if (mType == MIXER || mType == DUPLICATING) {
1911 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
1912 }
Andy Hung09a50072014-02-27 14:30:47 -08001913 ALOGI("HAL output buffer size %u frames, normal sink buffer size %u frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001914 mNormalFrameCount);
1915
Andy Hung010a1a12014-03-13 13:57:33 -07001916 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
1917 // Originally this was int16_t[] array, need to remove legacy implications.
1918 free(mSinkBuffer);
1919 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07001920 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
1921 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
1922 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07001923 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08001924
Andy Hung69aed5f2014-02-25 17:24:40 -08001925 // We resize the mMixerBuffer according to the requirements of the sink buffer which
1926 // drives the output.
1927 free(mMixerBuffer);
1928 mMixerBuffer = NULL;
1929 if (mMixerBufferEnabled) {
1930 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
1931 mMixerBufferSize = mNormalFrameCount * mChannelCount
1932 * audio_bytes_per_sample(mMixerBufferFormat);
1933 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
1934 }
Andy Hung98ef9782014-03-04 14:46:50 -08001935 free(mEffectBuffer);
1936 mEffectBuffer = NULL;
1937 if (mEffectBufferEnabled) {
1938 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
1939 mEffectBufferSize = mNormalFrameCount * mChannelCount
1940 * audio_bytes_per_sample(mEffectBufferFormat);
1941 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
1942 }
Andy Hung69aed5f2014-02-25 17:24:40 -08001943
Eric Laurent81784c32012-11-19 14:55:58 -08001944 // force reconfiguration of effect chains and engines to take new buffer size and audio
1945 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001946 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08001947 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1948 // matter.
1949 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1950 Vector< sp<EffectChain> > effectChains = mEffectChains;
1951 for (size_t i = 0; i < effectChains.size(); i ++) {
1952 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
1953 }
1954}
1955
1956
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001957status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08001958{
1959 if (halFrames == NULL || dspFrames == NULL) {
1960 return BAD_VALUE;
1961 }
1962 Mutex::Autolock _l(mLock);
1963 if (initCheck() != NO_ERROR) {
1964 return INVALID_OPERATION;
1965 }
1966 size_t framesWritten = mBytesWritten / mFrameSize;
1967 *halFrames = framesWritten;
1968
1969 if (isSuspended()) {
1970 // return an estimation of rendered frames when the output is suspended
1971 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
1972 *dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0;
1973 return NO_ERROR;
1974 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001975 status_t status;
1976 uint32_t frames;
1977 status = mOutput->stream->get_render_position(mOutput->stream, &frames);
1978 *dspFrames = (size_t)frames;
1979 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08001980 }
1981}
1982
1983uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
1984{
1985 Mutex::Autolock _l(mLock);
1986 uint32_t result = 0;
1987 if (getEffectChain_l(sessionId) != 0) {
1988 result = EFFECT_SESSION;
1989 }
1990
1991 for (size_t i = 0; i < mTracks.size(); ++i) {
1992 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08001993 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001994 result |= TRACK_SESSION;
1995 break;
1996 }
1997 }
1998
1999 return result;
2000}
2001
2002uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
2003{
2004 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2005 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2006 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2007 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2008 }
2009 for (size_t i = 0; i < mTracks.size(); i++) {
2010 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002011 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002012 return AudioSystem::getStrategyForStream(track->streamType());
2013 }
2014 }
2015 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2016}
2017
2018
2019AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
2020{
2021 Mutex::Autolock _l(mLock);
2022 return mOutput;
2023}
2024
2025AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
2026{
2027 Mutex::Autolock _l(mLock);
2028 AudioStreamOut *output = mOutput;
2029 mOutput = NULL;
2030 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2031 // must push a NULL and wait for ack
2032 mOutputSink.clear();
2033 mPipeSink.clear();
2034 mNormalSink.clear();
2035 return output;
2036}
2037
2038// this method must always be called either with ThreadBase mLock held or inside the thread loop
2039audio_stream_t* AudioFlinger::PlaybackThread::stream() const
2040{
2041 if (mOutput == NULL) {
2042 return NULL;
2043 }
2044 return &mOutput->stream->common;
2045}
2046
2047uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2048{
2049 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2050}
2051
2052status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2053{
2054 if (!isValidSyncEvent(event)) {
2055 return BAD_VALUE;
2056 }
2057
2058 Mutex::Autolock _l(mLock);
2059
2060 for (size_t i = 0; i < mTracks.size(); ++i) {
2061 sp<Track> track = mTracks[i];
2062 if (event->triggerSession() == track->sessionId()) {
2063 (void) track->setSyncEvent(event);
2064 return NO_ERROR;
2065 }
2066 }
2067
2068 return NAME_NOT_FOUND;
2069}
2070
2071bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2072{
2073 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2074}
2075
2076void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2077 const Vector< sp<Track> >& tracksToRemove)
2078{
2079 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002080 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002081 for (size_t i = 0 ; i < count ; i++) {
2082 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002083 if (track->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002084 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002085#ifdef ADD_BATTERY_DATA
2086 // to track the speaker usage
2087 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2088#endif
2089 if (track->isTerminated()) {
2090 AudioSystem::releaseOutput(mId);
2091 }
Eric Laurent81784c32012-11-19 14:55:58 -08002092 }
2093 }
2094 }
Eric Laurent81784c32012-11-19 14:55:58 -08002095}
2096
2097void AudioFlinger::PlaybackThread::checkSilentMode_l()
2098{
2099 if (!mMasterMute) {
2100 char value[PROPERTY_VALUE_MAX];
2101 if (property_get("ro.audio.silent", value, "0") > 0) {
2102 char *endptr;
2103 unsigned long ul = strtoul(value, &endptr, 0);
2104 if (*endptr == '\0' && ul != 0) {
2105 ALOGD("Silence is golden");
2106 // The setprop command will not allow a property to be changed after
2107 // the first time it is set, so we don't have to worry about un-muting.
2108 setMasterMute_l(true);
2109 }
2110 }
2111 }
2112}
2113
2114// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002115ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002116{
2117 // FIXME rewrite to reduce number of system calls
2118 mLastWriteTime = systemTime();
2119 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002120 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002121 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002122
2123 // If an NBAIO sink is present, use it to write the normal mixer's submix
2124 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002125
Andy Hung010a1a12014-03-13 13:57:33 -07002126 const size_t count = mBytesRemaining / mFrameSize;
2127
Simon Wilson2d590962012-11-29 15:18:50 -08002128 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002129 // update the setpoint when AudioFlinger::mScreenState changes
2130 uint32_t screenState = AudioFlinger::mScreenState;
2131 if (screenState != mScreenState) {
2132 mScreenState = screenState;
2133 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2134 if (pipe != NULL) {
2135 pipe->setAvgFrames((mScreenState & 1) ?
2136 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2137 }
2138 }
Andy Hung010a1a12014-03-13 13:57:33 -07002139 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002140 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002141 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002142 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002143 } else {
2144 bytesWritten = framesWritten;
2145 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002146 status_t status = mNormalSink->getTimestamp(mLatchD.mTimestamp);
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002147 if (status == NO_ERROR) {
2148 size_t totalFramesWritten = mNormalSink->framesWritten();
2149 if (totalFramesWritten >= mLatchD.mTimestamp.mPosition) {
2150 mLatchD.mUnpresentedFrames = totalFramesWritten - mLatchD.mTimestamp.mPosition;
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002151 // mLatchD.mFramesReleased is set immediately before D is clocked into Q
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002152 mLatchDValid = true;
2153 }
2154 }
Eric Laurent81784c32012-11-19 14:55:58 -08002155 // otherwise use the HAL / AudioStreamOut directly
2156 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002157 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002158
Eric Laurentbfb1b832013-01-07 09:53:42 -08002159 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002160 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2161 mWriteAckSequence += 2;
2162 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002163 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002164 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002165 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002166 // FIXME We should have an implementation of timestamps for direct output threads.
2167 // They are used e.g for multichannel PCM playback over HDMI.
Eric Laurentbfb1b832013-01-07 09:53:42 -08002168 bytesWritten = mOutput->stream->write(mOutput->stream,
Andy Hung2098f272014-02-27 14:00:06 -08002169 (char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002170 if (mUseAsyncWrite &&
2171 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2172 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002173 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002174 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002175 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002176 }
Eric Laurent81784c32012-11-19 14:55:58 -08002177 }
2178
Eric Laurent81784c32012-11-19 14:55:58 -08002179 mNumWrites++;
2180 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002181 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002182 return bytesWritten;
2183}
2184
2185void AudioFlinger::PlaybackThread::threadLoop_drain()
2186{
2187 if (mOutput->stream->drain) {
2188 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2189 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002190 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2191 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002192 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002193 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002194 }
2195 mOutput->stream->drain(mOutput->stream,
2196 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
2197 : AUDIO_DRAIN_ALL);
2198 }
2199}
2200
2201void AudioFlinger::PlaybackThread::threadLoop_exit()
2202{
2203 // Default implementation has nothing to do
Eric Laurent81784c32012-11-19 14:55:58 -08002204}
2205
2206/*
2207The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002208 - mSinkBufferSize from frame count * frame size
Eric Laurent81784c32012-11-19 14:55:58 -08002209 - activeSleepTime from activeSleepTimeUs()
2210 - idleSleepTime from idleSleepTimeUs()
2211 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
2212 - maxPeriod from frame count and sample rate (MIXER only)
2213
2214The parameters that affect these derived values are:
2215 - frame count
2216 - frame size
2217 - sample rate
2218 - device type: A2DP or not
2219 - device latency
2220 - format: PCM or not
2221 - active sleep time
2222 - idle sleep time
2223*/
2224
2225void AudioFlinger::PlaybackThread::cacheParameters_l()
2226{
Andy Hung25c2dac2014-02-27 14:56:00 -08002227 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002228 activeSleepTime = activeSleepTimeUs();
2229 idleSleepTime = idleSleepTimeUs();
2230}
2231
2232void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2233{
Glenn Kasten7c027242012-12-26 14:43:16 -08002234 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurent81784c32012-11-19 14:55:58 -08002235 this, streamType, mTracks.size());
2236 Mutex::Autolock _l(mLock);
2237
2238 size_t size = mTracks.size();
2239 for (size_t i = 0; i < size; i++) {
2240 sp<Track> t = mTracks[i];
2241 if (t->streamType() == streamType) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002242 t->invalidate();
Eric Laurent81784c32012-11-19 14:55:58 -08002243 }
2244 }
2245}
2246
2247status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2248{
2249 int session = chain->sessionId();
Andy Hung010a1a12014-03-13 13:57:33 -07002250 int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled
2251 ? mEffectBuffer : mSinkBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002252 bool ownsBuffer = false;
2253
2254 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
2255 if (session > 0) {
2256 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002257 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002258 if (mType != DIRECT) {
2259 size_t numSamples = mNormalFrameCount * mChannelCount;
2260 buffer = new int16_t[numSamples];
2261 memset(buffer, 0, numSamples * sizeof(int16_t));
2262 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2263 ownsBuffer = true;
2264 }
2265
2266 // Attach all tracks with same session ID to this chain.
2267 for (size_t i = 0; i < mTracks.size(); ++i) {
2268 sp<Track> track = mTracks[i];
2269 if (session == track->sessionId()) {
2270 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2271 buffer);
2272 track->setMainBuffer(buffer);
2273 chain->incTrackCnt();
2274 }
2275 }
2276
2277 // indicate all active tracks in the chain
2278 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2279 sp<Track> track = mActiveTracks[i].promote();
2280 if (track == 0) {
2281 continue;
2282 }
2283 if (session == track->sessionId()) {
2284 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2285 chain->incActiveTrackCnt();
2286 }
2287 }
2288 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002289 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08002290 chain->setInBuffer(buffer, ownsBuffer);
Andy Hung010a1a12014-03-13 13:57:33 -07002291 chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled
2292 ? mEffectBuffer : mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002293 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
2294 // chains list in order to be processed last as it contains output stage effects
2295 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2296 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
2297 // after track specific effects and before output stage
2298 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
2299 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
2300 // Effect chain for other sessions are inserted at beginning of effect
2301 // chains list to be processed before output mix effects. Relative order between other
2302 // sessions is not important
2303 size_t size = mEffectChains.size();
2304 size_t i = 0;
2305 for (i = 0; i < size; i++) {
2306 if (mEffectChains[i]->sessionId() < session) {
2307 break;
2308 }
2309 }
2310 mEffectChains.insertAt(chain, i);
2311 checkSuspendOnAddEffectChain_l(chain);
2312
2313 return NO_ERROR;
2314}
2315
2316size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2317{
2318 int session = chain->sessionId();
2319
2320 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2321
2322 for (size_t i = 0; i < mEffectChains.size(); i++) {
2323 if (chain == mEffectChains[i]) {
2324 mEffectChains.removeAt(i);
2325 // detach all active tracks from the chain
2326 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2327 sp<Track> track = mActiveTracks[i].promote();
2328 if (track == 0) {
2329 continue;
2330 }
2331 if (session == track->sessionId()) {
2332 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2333 chain.get(), session);
2334 chain->decActiveTrackCnt();
2335 }
2336 }
2337
2338 // detach all tracks with same session ID from this chain
2339 for (size_t i = 0; i < mTracks.size(); ++i) {
2340 sp<Track> track = mTracks[i];
2341 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002342 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002343 chain->decTrackCnt();
2344 }
2345 }
2346 break;
2347 }
2348 }
2349 return mEffectChains.size();
2350}
2351
2352status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2353 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2354{
2355 Mutex::Autolock _l(mLock);
2356 return attachAuxEffect_l(track, EffectId);
2357}
2358
2359status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2360 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2361{
2362 status_t status = NO_ERROR;
2363
2364 if (EffectId == 0) {
2365 track->setAuxBuffer(0, NULL);
2366 } else {
2367 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2368 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2369 if (effect != 0) {
2370 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2371 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2372 } else {
2373 status = INVALID_OPERATION;
2374 }
2375 } else {
2376 status = BAD_VALUE;
2377 }
2378 }
2379 return status;
2380}
2381
2382void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2383{
2384 for (size_t i = 0; i < mTracks.size(); ++i) {
2385 sp<Track> track = mTracks[i];
2386 if (track->auxEffectId() == effectId) {
2387 attachAuxEffect_l(track, 0);
2388 }
2389 }
2390}
2391
2392bool AudioFlinger::PlaybackThread::threadLoop()
2393{
2394 Vector< sp<Track> > tracksToRemove;
2395
2396 standbyTime = systemTime();
2397
2398 // MIXER
2399 nsecs_t lastWarning = 0;
2400
2401 // DUPLICATING
2402 // FIXME could this be made local to while loop?
2403 writeFrames = 0;
2404
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002405 int lastGeneration = 0;
2406
Eric Laurent81784c32012-11-19 14:55:58 -08002407 cacheParameters_l();
2408 sleepTime = idleSleepTime;
2409
2410 if (mType == MIXER) {
2411 sleepTimeShift = 0;
2412 }
2413
2414 CpuStats cpuStats;
2415 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2416
2417 acquireWakeLock();
2418
Glenn Kasten9e58b552013-01-18 15:09:48 -08002419 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2420 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2421 // and then that string will be logged at the next convenient opportunity.
2422 const char *logString = NULL;
2423
Eric Laurent664539d2013-09-23 18:24:31 -07002424 checkSilentMode_l();
2425
Eric Laurent81784c32012-11-19 14:55:58 -08002426 while (!exitPending())
2427 {
2428 cpuStats.sample(myName);
2429
2430 Vector< sp<EffectChain> > effectChains;
2431
Eric Laurent81784c32012-11-19 14:55:58 -08002432 { // scope for mLock
2433
2434 Mutex::Autolock _l(mLock);
2435
Eric Laurent021cf962014-05-13 10:18:14 -07002436 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07002437
Glenn Kasten9e58b552013-01-18 15:09:48 -08002438 if (logString != NULL) {
2439 mNBLogWriter->logTimestamp();
2440 mNBLogWriter->log(logString);
2441 logString = NULL;
2442 }
2443
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002444 // Gather the framesReleased counters for all active tracks,
2445 // and latch them atomically with the timestamp.
2446 // FIXME We're using raw pointers as indices. A unique track ID would be a better index.
2447 mLatchD.mFramesReleased.clear();
2448 size_t size = mActiveTracks.size();
2449 for (size_t i = 0; i < size; i++) {
2450 sp<Track> t = mActiveTracks[i].promote();
2451 if (t != 0) {
2452 mLatchD.mFramesReleased.add(t.get(),
2453 t->mAudioTrackServerProxy->framesReleased());
2454 }
2455 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002456 if (mLatchDValid) {
2457 mLatchQ = mLatchD;
2458 mLatchDValid = false;
2459 mLatchQValid = true;
2460 }
2461
Eric Laurent81784c32012-11-19 14:55:58 -08002462 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002463 if (mSignalPending) {
2464 // A signal was raised while we were unlocked
2465 mSignalPending = false;
2466 } else if (waitingAsyncCallback_l()) {
2467 if (exitPending()) {
2468 break;
2469 }
2470 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002471 mWakeLockUids.clear();
2472 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002473 ALOGV("wait async completion");
2474 mWaitWorkCV.wait(mLock);
2475 ALOGV("async completion/wake");
2476 acquireWakeLock_l();
Eric Laurent972a1732013-09-04 09:42:59 -07002477 standbyTime = systemTime() + standbyDelay;
2478 sleepTime = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002479
2480 continue;
2481 }
2482 if ((!mActiveTracks.size() && systemTime() > standbyTime) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08002483 isSuspended()) {
2484 // put audio hardware into standby after short delay
2485 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002486
2487 threadLoop_standby();
2488
2489 mStandby = true;
2490 }
2491
2492 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2493 // we're about to wait, flush the binder command buffer
2494 IPCThreadState::self()->flushCommands();
2495
2496 clearOutputTracks();
2497
2498 if (exitPending()) {
2499 break;
2500 }
2501
2502 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002503 mWakeLockUids.clear();
2504 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002505 // wait until we have something to do...
2506 ALOGV("%s going to sleep", myName.string());
2507 mWaitWorkCV.wait(mLock);
2508 ALOGV("%s waking up", myName.string());
2509 acquireWakeLock_l();
2510
2511 mMixerStatus = MIXER_IDLE;
2512 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2513 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002514 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002515 checkSilentMode_l();
2516
2517 standbyTime = systemTime() + standbyDelay;
2518 sleepTime = idleSleepTime;
2519 if (mType == MIXER) {
2520 sleepTimeShift = 0;
2521 }
2522
2523 continue;
2524 }
2525 }
Eric Laurent81784c32012-11-19 14:55:58 -08002526 // mMixerStatusIgnoringFastTracks is also updated internally
2527 mMixerStatus = prepareTracks_l(&tracksToRemove);
2528
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002529 // compare with previously applied list
2530 if (lastGeneration != mActiveTracksGeneration) {
2531 // update wakelock
2532 updateWakeLockUids_l(mWakeLockUids);
2533 lastGeneration = mActiveTracksGeneration;
2534 }
2535
Eric Laurent81784c32012-11-19 14:55:58 -08002536 // prevent any changes in effect chain list and in each effect chain
2537 // during mixing and effect process as the audio buffers could be deleted
2538 // or modified if an effect is created or deleted
2539 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002540 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08002541
Eric Laurentbfb1b832013-01-07 09:53:42 -08002542 if (mBytesRemaining == 0) {
2543 mCurrentWriteLength = 0;
2544 if (mMixerStatus == MIXER_TRACKS_READY) {
2545 // threadLoop_mix() sets mCurrentWriteLength
2546 threadLoop_mix();
2547 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
2548 && (mMixerStatus != MIXER_DRAIN_ALL)) {
2549 // threadLoop_sleepTime sets sleepTime to 0 if data
2550 // must be written to HAL
2551 threadLoop_sleepTime();
2552 if (sleepTime == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08002553 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002554 }
2555 }
Andy Hung98ef9782014-03-04 14:46:50 -08002556 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
2557 // mMixerBuffer with data if mMixerBufferValid is true and sleepTime == 0.
2558 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
2559 // or mSinkBuffer (if there are no effects).
2560 //
2561 // This is done pre-effects computation; if effects change to
2562 // support higher precision, this needs to move.
2563 //
2564 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
2565 // TODO use sleepTime == 0 as an additional condition.
2566 if (mMixerBufferValid) {
2567 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
2568 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
2569
2570 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
2571 mNormalFrameCount * mChannelCount);
2572 }
2573
Eric Laurentbfb1b832013-01-07 09:53:42 -08002574 mBytesRemaining = mCurrentWriteLength;
2575 if (isSuspended()) {
2576 sleepTime = suspendSleepTimeUs();
2577 // simulate write to HAL when suspended
Andy Hung25c2dac2014-02-27 14:56:00 -08002578 mBytesWritten += mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002579 mBytesRemaining = 0;
2580 }
Eric Laurent81784c32012-11-19 14:55:58 -08002581
Eric Laurentbfb1b832013-01-07 09:53:42 -08002582 // only process effects if we're going to write
Eric Laurent59fe0102013-09-27 18:48:26 -07002583 if (sleepTime == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002584 for (size_t i = 0; i < effectChains.size(); i ++) {
2585 effectChains[i]->process_l();
2586 }
Eric Laurent81784c32012-11-19 14:55:58 -08002587 }
2588 }
Eric Laurent59fe0102013-09-27 18:48:26 -07002589 // Process effect chains for offloaded thread even if no audio
2590 // was read from audio track: process only updates effect state
2591 // and thus does have to be synchronized with audio writes but may have
2592 // to be called while waiting for async write callback
2593 if (mType == OFFLOAD) {
2594 for (size_t i = 0; i < effectChains.size(); i ++) {
2595 effectChains[i]->process_l();
2596 }
2597 }
Eric Laurent81784c32012-11-19 14:55:58 -08002598
Andy Hung98ef9782014-03-04 14:46:50 -08002599 // Only if the Effects buffer is enabled and there is data in the
2600 // Effects buffer (buffer valid), we need to
2601 // copy into the sink buffer.
2602 // TODO use sleepTime == 0 as an additional condition.
2603 if (mEffectBufferValid) {
2604 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
2605 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
2606 mNormalFrameCount * mChannelCount);
2607 }
2608
Eric Laurent81784c32012-11-19 14:55:58 -08002609 // enable changes in effect chain
2610 unlockEffectChains(effectChains);
2611
Eric Laurentbfb1b832013-01-07 09:53:42 -08002612 if (!waitingAsyncCallback()) {
2613 // sleepTime == 0 means we must write to audio hardware
2614 if (sleepTime == 0) {
2615 if (mBytesRemaining) {
2616 ssize_t ret = threadLoop_write();
2617 if (ret < 0) {
2618 mBytesRemaining = 0;
2619 } else {
2620 mBytesWritten += ret;
2621 mBytesRemaining -= ret;
2622 }
2623 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
2624 (mMixerStatus == MIXER_DRAIN_ALL)) {
2625 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08002626 }
Glenn Kasten4944acb2013-08-19 08:39:20 -07002627 if (mType == MIXER) {
2628 // write blocked detection
2629 nsecs_t now = systemTime();
2630 nsecs_t delta = now - mLastWriteTime;
2631 if (!mStandby && delta > maxPeriod) {
2632 mNumDelayedWrites++;
2633 if ((now - lastWarning) > kWarningThrottleNs) {
2634 ATRACE_NAME("underrun");
2635 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2636 ns2ms(delta), mNumDelayedWrites, this);
2637 lastWarning = now;
2638 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002639 }
2640 }
Eric Laurent81784c32012-11-19 14:55:58 -08002641
Eric Laurentbfb1b832013-01-07 09:53:42 -08002642 } else {
2643 usleep(sleepTime);
2644 }
Eric Laurent81784c32012-11-19 14:55:58 -08002645 }
2646
2647 // Finally let go of removed track(s), without the lock held
2648 // since we can't guarantee the destructors won't acquire that
2649 // same lock. This will also mutate and push a new fast mixer state.
2650 threadLoop_removeTracks(tracksToRemove);
2651 tracksToRemove.clear();
2652
2653 // FIXME I don't understand the need for this here;
2654 // it was in the original code but maybe the
2655 // assignment in saveOutputTracks() makes this unnecessary?
2656 clearOutputTracks();
2657
2658 // Effect chains will be actually deleted here if they were removed from
2659 // mEffectChains list during mixing or effects processing
2660 effectChains.clear();
2661
2662 // FIXME Note that the above .clear() is no longer necessary since effectChains
2663 // is now local to this block, but will keep it for now (at least until merge done).
2664 }
2665
Eric Laurentbfb1b832013-01-07 09:53:42 -08002666 threadLoop_exit();
2667
Eric Laurentcf817a22014-08-04 20:36:31 -07002668 if (!mStandby) {
2669 threadLoop_standby();
2670 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08002671 }
2672
2673 releaseWakeLock();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002674 mWakeLockUids.clear();
2675 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002676
2677 ALOGV("Thread %p type %d exiting", this, mType);
2678 return false;
2679}
2680
Eric Laurentbfb1b832013-01-07 09:53:42 -08002681// removeTracks_l() must be called with ThreadBase::mLock held
2682void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
2683{
2684 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002685 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002686 for (size_t i=0 ; i<count ; i++) {
2687 const sp<Track>& track = tracksToRemove.itemAt(i);
2688 mActiveTracks.remove(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002689 mWakeLockUids.remove(track->uid());
2690 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002691 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
2692 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2693 if (chain != 0) {
2694 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
2695 track->sessionId());
2696 chain->decActiveTrackCnt();
2697 }
2698 if (track->isTerminated()) {
2699 removeTrack_l(track);
2700 }
2701 }
2702 }
2703
2704}
Eric Laurent81784c32012-11-19 14:55:58 -08002705
Eric Laurentaccc1472013-09-20 09:36:34 -07002706status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
2707{
2708 if (mNormalSink != 0) {
2709 return mNormalSink->getTimestamp(timestamp);
2710 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07002711 if ((mType == OFFLOAD || mType == DIRECT) && mOutput->stream->get_presentation_position) {
Eric Laurentaccc1472013-09-20 09:36:34 -07002712 uint64_t position64;
2713 int ret = mOutput->stream->get_presentation_position(
2714 mOutput->stream, &position64, &timestamp.mTime);
2715 if (ret == 0) {
2716 timestamp.mPosition = (uint32_t)position64;
2717 return NO_ERROR;
2718 }
2719 }
2720 return INVALID_OPERATION;
2721}
Eric Laurent1c333e22014-05-20 10:48:17 -07002722
2723status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
2724 audio_patch_handle_t *handle)
2725{
2726 status_t status = NO_ERROR;
2727 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
2728 // store new device and send to effects
2729 audio_devices_t type = AUDIO_DEVICE_NONE;
2730 for (unsigned int i = 0; i < patch->num_sinks; i++) {
2731 type |= patch->sinks[i].ext.device.type;
2732 }
2733 mOutDevice = type;
2734 for (size_t i = 0; i < mEffectChains.size(); i++) {
2735 mEffectChains[i]->setDevice_l(mOutDevice);
2736 }
2737
2738 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
2739 status = hwDevice->create_audio_patch(hwDevice,
2740 patch->num_sources,
2741 patch->sources,
2742 patch->num_sinks,
2743 patch->sinks,
2744 handle);
2745 } else {
2746 ALOG_ASSERT(false, "createAudioPatch_l() called on a pre 3.0 HAL");
2747 }
2748 return status;
2749}
2750
2751status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
2752{
2753 status_t status = NO_ERROR;
2754 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
2755 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
2756 status = hwDevice->release_audio_patch(hwDevice, handle);
2757 } else {
2758 ALOG_ASSERT(false, "releaseAudioPatch_l() called on a pre 3.0 HAL");
2759 }
2760 return status;
2761}
2762
Eric Laurent83b88082014-06-20 18:31:16 -07002763void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
2764{
2765 Mutex::Autolock _l(mLock);
2766 mTracks.add(track);
2767}
2768
2769void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
2770{
2771 Mutex::Autolock _l(mLock);
2772 destroyTrack_l(track);
2773}
2774
2775void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
2776{
2777 ThreadBase::getAudioPortConfig(config);
2778 config->role = AUDIO_PORT_ROLE_SOURCE;
2779 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
2780 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
2781}
2782
Eric Laurent81784c32012-11-19 14:55:58 -08002783// ----------------------------------------------------------------------------
2784
2785AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
2786 audio_io_handle_t id, audio_devices_t device, type_t type)
2787 : PlaybackThread(audioFlinger, output, id, device, type),
2788 // mAudioMixer below
2789 // mFastMixer below
2790 mFastMixerFutex(0)
2791 // mOutputSink below
2792 // mPipeSink below
2793 // mNormalSink below
2794{
2795 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07002796 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, "
Eric Laurent81784c32012-11-19 14:55:58 -08002797 "mFrameCount=%d, mNormalFrameCount=%d",
2798 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2799 mNormalFrameCount);
2800 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2801
Eric Laurent81784c32012-11-19 14:55:58 -08002802 // create an NBAIO sink for the HAL output stream, and negotiate
2803 mOutputSink = new AudioStreamOutSink(output->stream);
2804 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08002805 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Eric Laurent81784c32012-11-19 14:55:58 -08002806 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2807 ALOG_ASSERT(index == 0);
2808
2809 // initialize fast mixer depending on configuration
2810 bool initFastMixer;
2811 switch (kUseFastMixer) {
2812 case FastMixer_Never:
2813 initFastMixer = false;
2814 break;
2815 case FastMixer_Always:
2816 initFastMixer = true;
2817 break;
2818 case FastMixer_Static:
2819 case FastMixer_Dynamic:
2820 initFastMixer = mFrameCount < mNormalFrameCount;
2821 break;
2822 }
2823 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07002824 audio_format_t fastMixerFormat;
2825 if (mMixerBufferEnabled && mEffectBufferEnabled) {
2826 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
2827 } else {
2828 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
2829 }
2830 if (mFormat != fastMixerFormat) {
2831 // change our Sink format to accept our intermediate precision
2832 mFormat = fastMixerFormat;
2833 free(mSinkBuffer);
2834 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2835 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
2836 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
2837 }
Eric Laurent81784c32012-11-19 14:55:58 -08002838
2839 // create a MonoPipe to connect our submix to FastMixer
2840 NBAIO_Format format = mOutputSink->format();
Glenn Kastenba0b34c2014-09-28 13:06:06 -07002841 NBAIO_Format origformat = format;
Andy Hung1258c1a2014-05-23 21:22:17 -07002842 // adjust format to match that of the Fast Mixer
2843 format.mFormat = fastMixerFormat;
2844 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
2845
Eric Laurent81784c32012-11-19 14:55:58 -08002846 // This pipe depth compensates for scheduling latency of the normal mixer thread.
2847 // When it wakes up after a maximum latency, it runs a few cycles quickly before
2848 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
2849 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
2850 const NBAIO_Format offers[1] = {format};
2851 size_t numCounterOffers = 0;
2852 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2853 ALOG_ASSERT(index == 0);
2854 monoPipe->setAvgFrames((mScreenState & 1) ?
2855 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2856 mPipeSink = monoPipe;
2857
Glenn Kasten46909e72013-02-26 09:20:22 -08002858#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08002859 if (mTeeSinkOutputEnabled) {
2860 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07002861 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
2862 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08002863 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07002864 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08002865 ALOG_ASSERT(index == 0);
2866 mTeeSink = teeSink;
2867 PipeReader *teeSource = new PipeReader(*teeSink);
2868 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07002869 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08002870 ALOG_ASSERT(index == 0);
2871 mTeeSource = teeSource;
2872 }
Glenn Kasten46909e72013-02-26 09:20:22 -08002873#endif
Eric Laurent81784c32012-11-19 14:55:58 -08002874
2875 // create fast mixer and configure it initially with just one fast track for our submix
2876 mFastMixer = new FastMixer();
2877 FastMixerStateQueue *sq = mFastMixer->sq();
2878#ifdef STATE_QUEUE_DUMP
2879 sq->setObserverDump(&mStateQueueObserverDump);
2880 sq->setMutatorDump(&mStateQueueMutatorDump);
2881#endif
2882 FastMixerState *state = sq->begin();
2883 FastTrack *fastTrack = &state->mFastTracks[0];
2884 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2885 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2886 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07002887 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
2888 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08002889 fastTrack->mGeneration++;
2890 state->mFastTracksGen++;
2891 state->mTrackMask = 1;
2892 // fast mixer will use the HAL output sink
2893 state->mOutputSink = mOutputSink.get();
2894 state->mOutputSinkGen++;
2895 state->mFrameCount = mFrameCount;
2896 state->mCommand = FastMixerState::COLD_IDLE;
2897 // already done in constructor initialization list
2898 //mFastMixerFutex = 0;
2899 state->mColdFutexAddr = &mFastMixerFutex;
2900 state->mColdGen++;
2901 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08002902#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08002903 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08002904#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08002905 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
2906 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08002907 sq->end();
2908 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2909
2910 // start the fast mixer
2911 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
2912 pid_t tid = mFastMixer->getTid();
2913 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2914 if (err != 0) {
2915 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2916 kPriorityFastMixer, getpid_cached, tid, err);
2917 }
2918
2919#ifdef AUDIO_WATCHDOG
2920 // create and start the watchdog
2921 mAudioWatchdog = new AudioWatchdog();
2922 mAudioWatchdog->setDump(&mAudioWatchdogDump);
2923 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
2924 tid = mAudioWatchdog->getTid();
2925 err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2926 if (err != 0) {
2927 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2928 kPriorityFastMixer, getpid_cached, tid, err);
2929 }
2930#endif
2931
Eric Laurent81784c32012-11-19 14:55:58 -08002932 }
2933
2934 switch (kUseFastMixer) {
2935 case FastMixer_Never:
2936 case FastMixer_Dynamic:
2937 mNormalSink = mOutputSink;
2938 break;
2939 case FastMixer_Always:
2940 mNormalSink = mPipeSink;
2941 break;
2942 case FastMixer_Static:
2943 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2944 break;
2945 }
2946}
2947
2948AudioFlinger::MixerThread::~MixerThread()
2949{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07002950 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002951 FastMixerStateQueue *sq = mFastMixer->sq();
2952 FastMixerState *state = sq->begin();
2953 if (state->mCommand == FastMixerState::COLD_IDLE) {
2954 int32_t old = android_atomic_inc(&mFastMixerFutex);
2955 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07002956 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08002957 }
2958 }
2959 state->mCommand = FastMixerState::EXIT;
2960 sq->end();
2961 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2962 mFastMixer->join();
2963 // Though the fast mixer thread has exited, it's state queue is still valid.
2964 // We'll use that extract the final state which contains one remaining fast track
2965 // corresponding to our sub-mix.
2966 state = sq->begin();
2967 ALOG_ASSERT(state->mTrackMask == 1);
2968 FastTrack *fastTrack = &state->mFastTracks[0];
2969 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2970 delete fastTrack->mBufferProvider;
2971 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07002972 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08002973#ifdef AUDIO_WATCHDOG
2974 if (mAudioWatchdog != 0) {
2975 mAudioWatchdog->requestExit();
2976 mAudioWatchdog->requestExitAndWait();
2977 mAudioWatchdog.clear();
2978 }
2979#endif
2980 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08002981 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08002982 delete mAudioMixer;
2983}
2984
2985
2986uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
2987{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07002988 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002989 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2990 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
2991 }
2992 return latency;
2993}
2994
2995
2996void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2997{
2998 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
2999}
3000
Eric Laurentbfb1b832013-01-07 09:53:42 -08003001ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003002{
3003 // FIXME we should only do one push per cycle; confirm this is true
3004 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003005 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003006 FastMixerStateQueue *sq = mFastMixer->sq();
3007 FastMixerState *state = sq->begin();
3008 if (state->mCommand != FastMixerState::MIX_WRITE &&
3009 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3010 if (state->mCommand == FastMixerState::COLD_IDLE) {
3011 int32_t old = android_atomic_inc(&mFastMixerFutex);
3012 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003013 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003014 }
3015#ifdef AUDIO_WATCHDOG
3016 if (mAudioWatchdog != 0) {
3017 mAudioWatchdog->resume();
3018 }
3019#endif
3020 }
3021 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003022 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
3023 FastMixerDumpState::kSamplingNforLowRamDevice : FastMixerDumpState::kSamplingN);
Eric Laurent81784c32012-11-19 14:55:58 -08003024 sq->end();
3025 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3026 if (kUseFastMixer == FastMixer_Dynamic) {
3027 mNormalSink = mPipeSink;
3028 }
3029 } else {
3030 sq->end(false /*didModify*/);
3031 }
3032 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003033 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003034}
3035
3036void AudioFlinger::MixerThread::threadLoop_standby()
3037{
3038 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003039 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003040 FastMixerStateQueue *sq = mFastMixer->sq();
3041 FastMixerState *state = sq->begin();
3042 if (!(state->mCommand & FastMixerState::IDLE)) {
3043 state->mCommand = FastMixerState::COLD_IDLE;
3044 state->mColdFutexAddr = &mFastMixerFutex;
3045 state->mColdGen++;
3046 mFastMixerFutex = 0;
3047 sq->end();
3048 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3049 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3050 if (kUseFastMixer == FastMixer_Dynamic) {
3051 mNormalSink = mOutputSink;
3052 }
3053#ifdef AUDIO_WATCHDOG
3054 if (mAudioWatchdog != 0) {
3055 mAudioWatchdog->pause();
3056 }
3057#endif
3058 } else {
3059 sq->end(false /*didModify*/);
3060 }
3061 }
3062 PlaybackThread::threadLoop_standby();
3063}
3064
Eric Laurentbfb1b832013-01-07 09:53:42 -08003065bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3066{
3067 return false;
3068}
3069
3070bool AudioFlinger::PlaybackThread::shouldStandby_l()
3071{
3072 return !mStandby;
3073}
3074
3075bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3076{
3077 Mutex::Autolock _l(mLock);
3078 return waitingAsyncCallback_l();
3079}
3080
Eric Laurent81784c32012-11-19 14:55:58 -08003081// shared by MIXER and DIRECT, overridden by DUPLICATING
3082void AudioFlinger::PlaybackThread::threadLoop_standby()
3083{
3084 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
3085 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003086 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003087 // discard any pending drain or write ack by incrementing sequence
3088 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3089 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003090 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003091 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3092 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003093 }
Eric Laurent81784c32012-11-19 14:55:58 -08003094}
3095
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003096void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3097{
3098 ALOGV("signal playback thread");
3099 broadcast_l();
3100}
3101
Eric Laurent81784c32012-11-19 14:55:58 -08003102void AudioFlinger::MixerThread::threadLoop_mix()
3103{
3104 // obtain the presentation timestamp of the next output buffer
3105 int64_t pts;
3106 status_t status = INVALID_OPERATION;
3107
3108 if (mNormalSink != 0) {
3109 status = mNormalSink->getNextWriteTimestamp(&pts);
3110 } else {
3111 status = mOutputSink->getNextWriteTimestamp(&pts);
3112 }
3113
3114 if (status != NO_ERROR) {
3115 pts = AudioBufferProvider::kInvalidPTS;
3116 }
3117
3118 // mix buffers...
3119 mAudioMixer->process(pts);
Andy Hung25c2dac2014-02-27 14:56:00 -08003120 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003121 // increase sleep time progressively when application underrun condition clears.
3122 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3123 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3124 // such that we would underrun the audio HAL.
3125 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
3126 sleepTimeShift--;
3127 }
3128 sleepTime = 0;
3129 standbyTime = systemTime() + standbyDelay;
3130 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003131
Eric Laurent81784c32012-11-19 14:55:58 -08003132}
3133
3134void AudioFlinger::MixerThread::threadLoop_sleepTime()
3135{
3136 // If no tracks are ready, sleep once for the duration of an output
3137 // buffer size, then write 0s to the output
3138 if (sleepTime == 0) {
3139 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3140 sleepTime = activeSleepTime >> sleepTimeShift;
3141 if (sleepTime < kMinThreadSleepTimeUs) {
3142 sleepTime = kMinThreadSleepTimeUs;
3143 }
3144 // reduce sleep time in case of consecutive application underruns to avoid
3145 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3146 // duration we would end up writing less data than needed by the audio HAL if
3147 // the condition persists.
3148 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3149 sleepTimeShift++;
3150 }
3151 } else {
3152 sleepTime = idleSleepTime;
3153 }
3154 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003155 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3156 // before effects processing or output.
3157 if (mMixerBufferValid) {
3158 memset(mMixerBuffer, 0, mMixerBufferSize);
3159 } else {
3160 memset(mSinkBuffer, 0, mSinkBufferSize);
3161 }
Eric Laurent81784c32012-11-19 14:55:58 -08003162 sleepTime = 0;
3163 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3164 "anticipated start");
3165 }
3166 // TODO add standby time extension fct of effect tail
3167}
3168
3169// prepareTracks_l() must be called with ThreadBase::mLock held
3170AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3171 Vector< sp<Track> > *tracksToRemove)
3172{
3173
3174 mixer_state mixerStatus = MIXER_IDLE;
3175 // find out which tracks need to be processed
3176 size_t count = mActiveTracks.size();
3177 size_t mixedTracks = 0;
3178 size_t tracksWithEffect = 0;
3179 // counts only _active_ fast tracks
3180 size_t fastTracks = 0;
3181 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
3182
3183 float masterVolume = mMasterVolume;
3184 bool masterMute = mMasterMute;
3185
3186 if (masterMute) {
3187 masterVolume = 0;
3188 }
3189 // Delegate master volume control to effect in output mix effect chain if needed
3190 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3191 if (chain != 0) {
3192 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
3193 chain->setVolume_l(&v, &v);
3194 masterVolume = (float)((v + (1 << 23)) >> 24);
3195 chain.clear();
3196 }
3197
3198 // prepare a new state to push
3199 FastMixerStateQueue *sq = NULL;
3200 FastMixerState *state = NULL;
3201 bool didModify = false;
3202 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003203 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003204 sq = mFastMixer->sq();
3205 state = sq->begin();
3206 }
3207
Andy Hung69aed5f2014-02-25 17:24:40 -08003208 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08003209 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08003210
Eric Laurent81784c32012-11-19 14:55:58 -08003211 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003212 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003213 if (t == 0) {
3214 continue;
3215 }
3216
3217 // this const just means the local variable doesn't change
3218 Track* const track = t.get();
3219
3220 // process fast tracks
3221 if (track->isFastTrack()) {
3222
3223 // It's theoretically possible (though unlikely) for a fast track to be created
3224 // and then removed within the same normal mix cycle. This is not a problem, as
3225 // the track never becomes active so it's fast mixer slot is never touched.
3226 // The converse, of removing an (active) track and then creating a new track
3227 // at the identical fast mixer slot within the same normal mix cycle,
3228 // is impossible because the slot isn't marked available until the end of each cycle.
3229 int j = track->mFastIndex;
3230 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
3231 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
3232 FastTrack *fastTrack = &state->mFastTracks[j];
3233
3234 // Determine whether the track is currently in underrun condition,
3235 // and whether it had a recent underrun.
3236 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
3237 FastTrackUnderruns underruns = ftDump->mUnderruns;
3238 uint32_t recentFull = (underruns.mBitFields.mFull -
3239 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
3240 uint32_t recentPartial = (underruns.mBitFields.mPartial -
3241 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
3242 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
3243 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
3244 uint32_t recentUnderruns = recentPartial + recentEmpty;
3245 track->mObservedUnderruns = underruns;
3246 // don't count underruns that occur while stopping or pausing
3247 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07003248 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
3249 recentUnderruns > 0) {
3250 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
3251 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003252 }
3253
3254 // This is similar to the state machine for normal tracks,
3255 // with a few modifications for fast tracks.
3256 bool isActive = true;
3257 switch (track->mState) {
3258 case TrackBase::STOPPING_1:
3259 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08003260 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003261 track->mState = TrackBase::STOPPING_2;
3262 }
3263 break;
3264 case TrackBase::PAUSING:
3265 // ramp down is not yet implemented
3266 track->setPaused();
3267 break;
3268 case TrackBase::RESUMING:
3269 // ramp up is not yet implemented
3270 track->mState = TrackBase::ACTIVE;
3271 break;
3272 case TrackBase::ACTIVE:
3273 if (recentFull > 0 || recentPartial > 0) {
3274 // track has provided at least some frames recently: reset retry count
3275 track->mRetryCount = kMaxTrackRetries;
3276 }
3277 if (recentUnderruns == 0) {
3278 // no recent underruns: stay active
3279 break;
3280 }
3281 // there has recently been an underrun of some kind
3282 if (track->sharedBuffer() == 0) {
3283 // were any of the recent underruns "empty" (no frames available)?
3284 if (recentEmpty == 0) {
3285 // no, then ignore the partial underruns as they are allowed indefinitely
3286 break;
3287 }
3288 // there has recently been an "empty" underrun: decrement the retry counter
3289 if (--(track->mRetryCount) > 0) {
3290 break;
3291 }
3292 // indicate to client process that the track was disabled because of underrun;
3293 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003294 android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003295 // remove from active list, but state remains ACTIVE [confusing but true]
3296 isActive = false;
3297 break;
3298 }
3299 // fall through
3300 case TrackBase::STOPPING_2:
3301 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003302 case TrackBase::STOPPED:
3303 case TrackBase::FLUSHED: // flush() while active
3304 // Check for presentation complete if track is inactive
3305 // We have consumed all the buffers of this track.
3306 // This would be incomplete if we auto-paused on underrun
3307 {
3308 size_t audioHALFrames =
3309 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3310 size_t framesWritten = mBytesWritten / mFrameSize;
3311 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
3312 // track stays in active list until presentation is complete
3313 break;
3314 }
3315 }
3316 if (track->isStopping_2()) {
3317 track->mState = TrackBase::STOPPED;
3318 }
3319 if (track->isStopped()) {
3320 // Can't reset directly, as fast mixer is still polling this track
3321 // track->reset();
3322 // So instead mark this track as needing to be reset after push with ack
3323 resetMask |= 1 << i;
3324 }
3325 isActive = false;
3326 break;
3327 case TrackBase::IDLE:
3328 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08003329 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08003330 }
3331
3332 if (isActive) {
3333 // was it previously inactive?
3334 if (!(state->mTrackMask & (1 << j))) {
3335 ExtendedAudioBufferProvider *eabp = track;
3336 VolumeProvider *vp = track;
3337 fastTrack->mBufferProvider = eabp;
3338 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08003339 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003340 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08003341 fastTrack->mGeneration++;
3342 state->mTrackMask |= 1 << j;
3343 didModify = true;
3344 // no acknowledgement required for newly active tracks
3345 }
3346 // cache the combined master volume and stream type volume for fast mixer; this
3347 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08003348 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08003349 ++fastTracks;
3350 } else {
3351 // was it previously active?
3352 if (state->mTrackMask & (1 << j)) {
3353 fastTrack->mBufferProvider = NULL;
3354 fastTrack->mGeneration++;
3355 state->mTrackMask &= ~(1 << j);
3356 didModify = true;
3357 // If any fast tracks were removed, we must wait for acknowledgement
3358 // because we're about to decrement the last sp<> on those tracks.
3359 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3360 } else {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003361 LOG_ALWAYS_FATAL("fast track %d should have been active", j);
Eric Laurent81784c32012-11-19 14:55:58 -08003362 }
3363 tracksToRemove->add(track);
3364 // Avoids a misleading display in dumpsys
3365 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
3366 }
3367 continue;
3368 }
3369
3370 { // local variable scope to avoid goto warning
3371
3372 audio_track_cblk_t* cblk = track->cblk();
3373
3374 // The first time a track is added we wait
3375 // for all its buffers to be filled before processing it
3376 int name = track->name();
3377 // make sure that we have enough frames to mix one full buffer.
3378 // enforce this condition only once to enable draining the buffer in case the client
3379 // app does not call stop() and relies on underrun to stop:
3380 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
3381 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003382 size_t desiredFrames;
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003383 uint32_t sr = track->sampleRate();
3384 if (sr == mSampleRate) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003385 desiredFrames = mNormalFrameCount;
3386 } else {
3387 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003388 desiredFrames = (mNormalFrameCount * sr) / mSampleRate + 1 + 1;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003389 // add frames already consumed but not yet released by the resampler
Glenn Kasten2fc14732013-08-05 14:58:14 -07003390 // because mAudioTrackServerProxy->framesReady() will include these frames
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003391 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
Glenn Kasten74935e42013-12-19 08:56:45 -08003392#if 0
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003393 // the minimum track buffer size is normally twice the number of frames necessary
3394 // to fill one buffer and the resampler should not leave more than one buffer worth
3395 // of unreleased frames after each pass, but just in case...
3396 ALOG_ASSERT(desiredFrames <= cblk->frameCount_);
Glenn Kasten74935e42013-12-19 08:56:45 -08003397#endif
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003398 }
Eric Laurent81784c32012-11-19 14:55:58 -08003399 uint32_t minFrames = 1;
3400 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
3401 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003402 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08003403 }
Eric Laurent13e4c962013-12-20 17:36:01 -08003404
3405 size_t framesReady = track->framesReady();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003406 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08003407 !track->isPaused() && !track->isTerminated())
3408 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003409 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003410
3411 mixedTracks++;
3412
Andy Hung69aed5f2014-02-25 17:24:40 -08003413 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
3414 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08003415 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08003416 if (track->mainBuffer() != mSinkBuffer &&
3417 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08003418 if (mEffectBufferEnabled) {
3419 mEffectBufferValid = true; // Later can set directly.
3420 }
Eric Laurent81784c32012-11-19 14:55:58 -08003421 chain = getEffectChain_l(track->sessionId());
3422 // Delegate volume control to effect in track effect chain if needed
3423 if (chain != 0) {
3424 tracksWithEffect++;
3425 } else {
3426 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
3427 "session %d",
3428 name, track->sessionId());
3429 }
3430 }
3431
3432
3433 int param = AudioMixer::VOLUME;
3434 if (track->mFillingUpStatus == Track::FS_FILLED) {
3435 // no ramp for the first volume setting
3436 track->mFillingUpStatus = Track::FS_ACTIVE;
3437 if (track->mState == TrackBase::RESUMING) {
3438 track->mState = TrackBase::ACTIVE;
3439 param = AudioMixer::RAMP_VOLUME;
3440 }
3441 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003442 // FIXME should not make a decision based on mServer
3443 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003444 // If the track is stopped before the first frame was mixed,
3445 // do not apply ramp
3446 param = AudioMixer::RAMP_VOLUME;
3447 }
3448
3449 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07003450 uint32_t vl, vr; // in U8.24 integer format
3451 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08003452 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07003453 vl = vr = 0;
3454 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08003455 if (track->isPausing()) {
3456 track->setPaused();
3457 }
3458 } else {
3459
3460 // read original volumes with volume control
3461 float typeVolume = mStreamTypes[track->streamType()].volume;
3462 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003463 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07003464 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07003465 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
3466 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08003467 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07003468 if (vlf > GAIN_FLOAT_UNITY) {
3469 ALOGV("Track left volume out of range: %.3g", vlf);
3470 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003471 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07003472 if (vrf > GAIN_FLOAT_UNITY) {
3473 ALOGV("Track right volume out of range: %.3g", vrf);
3474 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003475 }
3476 // now apply the master volume and stream type volume
Andy Hung6be49402014-05-30 10:42:03 -07003477 vlf *= v;
3478 vrf *= v;
Eric Laurent81784c32012-11-19 14:55:58 -08003479 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07003480 // then derive vl and vr as U8.24 versions for the effect chain
3481 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
3482 vl = (uint32_t) (scaleto8_24 * vlf);
3483 vr = (uint32_t) (scaleto8_24 * vrf);
3484 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08003485 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08003486 // send level comes from shared memory and so may be corrupt
3487 if (sendLevel > MAX_GAIN_INT) {
3488 ALOGV("Track send level out of range: %04X", sendLevel);
3489 sendLevel = MAX_GAIN_INT;
3490 }
Andy Hung6be49402014-05-30 10:42:03 -07003491 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
3492 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08003493 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003494
Eric Laurent81784c32012-11-19 14:55:58 -08003495 // Delegate volume control to effect in track effect chain if needed
3496 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3497 // Do not ramp volume if volume is controlled by effect
3498 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08003499 // Update remaining floating point volume levels
3500 vlf = (float)vl / (1 << 24);
3501 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08003502 track->mHasVolumeController = true;
3503 } else {
3504 // force no volume ramp when volume controller was just disabled or removed
3505 // from effect chain to avoid volume spike
3506 if (track->mHasVolumeController) {
3507 param = AudioMixer::VOLUME;
3508 }
3509 track->mHasVolumeController = false;
3510 }
3511
Eric Laurent81784c32012-11-19 14:55:58 -08003512 // XXX: these things DON'T need to be done each time
3513 mAudioMixer->setBufferProvider(name, track);
3514 mAudioMixer->enable(name);
3515
Andy Hung6be49402014-05-30 10:42:03 -07003516 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
3517 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
3518 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08003519 mAudioMixer->setParameter(
3520 name,
3521 AudioMixer::TRACK,
3522 AudioMixer::FORMAT, (void *)track->format());
3523 mAudioMixer->setParameter(
3524 name,
3525 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003526 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07003527 mAudioMixer->setParameter(
3528 name,
3529 AudioMixer::TRACK,
3530 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08003531 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07003532 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003533 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08003534 if (reqSampleRate == 0) {
3535 reqSampleRate = mSampleRate;
3536 } else if (reqSampleRate > maxSampleRate) {
3537 reqSampleRate = maxSampleRate;
3538 }
Eric Laurent81784c32012-11-19 14:55:58 -08003539 mAudioMixer->setParameter(
3540 name,
3541 AudioMixer::RESAMPLE,
3542 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003543 (void *)(uintptr_t)reqSampleRate);
Andy Hung69aed5f2014-02-25 17:24:40 -08003544 /*
3545 * Select the appropriate output buffer for the track.
3546 *
Andy Hung98ef9782014-03-04 14:46:50 -08003547 * Tracks with effects go into their own effects chain buffer
3548 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08003549 *
3550 * Other tracks can use mMixerBuffer for higher precision
3551 * channel accumulation. If this buffer is enabled
3552 * (mMixerBufferEnabled true), then selected tracks will accumulate
3553 * into it.
3554 *
3555 */
3556 if (mMixerBufferEnabled
3557 && (track->mainBuffer() == mSinkBuffer
3558 || track->mainBuffer() == mMixerBuffer)) {
3559 mAudioMixer->setParameter(
3560 name,
3561 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08003562 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08003563 mAudioMixer->setParameter(
3564 name,
3565 AudioMixer::TRACK,
3566 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
3567 // TODO: override track->mainBuffer()?
3568 mMixerBufferValid = true;
3569 } else {
3570 mAudioMixer->setParameter(
3571 name,
3572 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08003573 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08003574 mAudioMixer->setParameter(
3575 name,
3576 AudioMixer::TRACK,
3577 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3578 }
Eric Laurent81784c32012-11-19 14:55:58 -08003579 mAudioMixer->setParameter(
3580 name,
3581 AudioMixer::TRACK,
3582 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3583
3584 // reset retry count
3585 track->mRetryCount = kMaxTrackRetries;
3586
3587 // If one track is ready, set the mixer ready if:
3588 // - the mixer was not ready during previous round OR
3589 // - no other track is not ready
3590 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
3591 mixerStatus != MIXER_TRACKS_ENABLED) {
3592 mixerStatus = MIXER_TRACKS_READY;
3593 }
3594 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003595 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Glenn Kasten82aaf942013-07-17 16:05:07 -07003596 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003597 }
Eric Laurent81784c32012-11-19 14:55:58 -08003598 // clear effect chain input buffer if an active track underruns to avoid sending
3599 // previous audio buffer again to effects
3600 chain = getEffectChain_l(track->sessionId());
3601 if (chain != 0) {
3602 chain->clearInputBuffer();
3603 }
3604
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003605 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003606 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3607 track->isStopped() || track->isPaused()) {
3608 // We have consumed all the buffers of this track.
3609 // Remove it from the list of active tracks.
3610 // TODO: use actual buffer filling status instead of latency when available from
3611 // audio HAL
3612 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3613 size_t framesWritten = mBytesWritten / mFrameSize;
3614 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
3615 if (track->isStopped()) {
3616 track->reset();
3617 }
3618 tracksToRemove->add(track);
3619 }
3620 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08003621 // No buffers for this track. Give it a few chances to
3622 // fill a buffer, then remove it from active list.
3623 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08003624 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003625 tracksToRemove->add(track);
3626 // indicate to client process that the track was disabled because of underrun;
3627 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003628 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003629 // If one track is not ready, mark the mixer also not ready if:
3630 // - the mixer was ready during previous round OR
3631 // - no other track is ready
3632 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
3633 mixerStatus != MIXER_TRACKS_READY) {
3634 mixerStatus = MIXER_TRACKS_ENABLED;
3635 }
3636 }
3637 mAudioMixer->disable(name);
3638 }
3639
3640 } // local variable scope to avoid goto warning
3641track_is_ready: ;
3642
3643 }
3644
3645 // Push the new FastMixer state if necessary
3646 bool pauseAudioWatchdog = false;
3647 if (didModify) {
3648 state->mFastTracksGen++;
3649 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3650 if (kUseFastMixer == FastMixer_Dynamic &&
3651 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3652 state->mCommand = FastMixerState::COLD_IDLE;
3653 state->mColdFutexAddr = &mFastMixerFutex;
3654 state->mColdGen++;
3655 mFastMixerFutex = 0;
3656 if (kUseFastMixer == FastMixer_Dynamic) {
3657 mNormalSink = mOutputSink;
3658 }
3659 // If we go into cold idle, need to wait for acknowledgement
3660 // so that fast mixer stops doing I/O.
3661 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3662 pauseAudioWatchdog = true;
3663 }
Eric Laurent81784c32012-11-19 14:55:58 -08003664 }
3665 if (sq != NULL) {
3666 sq->end(didModify);
3667 sq->push(block);
3668 }
3669#ifdef AUDIO_WATCHDOG
3670 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3671 mAudioWatchdog->pause();
3672 }
3673#endif
3674
3675 // Now perform the deferred reset on fast tracks that have stopped
3676 while (resetMask != 0) {
3677 size_t i = __builtin_ctz(resetMask);
3678 ALOG_ASSERT(i < count);
3679 resetMask &= ~(1 << i);
3680 sp<Track> t = mActiveTracks[i].promote();
3681 if (t == 0) {
3682 continue;
3683 }
3684 Track* track = t.get();
3685 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3686 track->reset();
3687 }
3688
3689 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08003690 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08003691
Eric Laurent97d547d2014-09-02 14:45:53 -07003692 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
3693 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07003694 }
3695
3696 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07003697 // as long as there are effects we should clear the effects buffer, to avoid
3698 // passing a non-clean buffer to the effect chain
3699 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07003700 }
Andy Hung69aed5f2014-02-25 17:24:40 -08003701 // sink or mix buffer must be cleared if all tracks are connected to an
3702 // effect chain as in this case the mixer will not write to the sink or mix buffer
3703 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08003704 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3705 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08003706 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08003707 if (mMixerBufferValid) {
3708 memset(mMixerBuffer, 0, mMixerBufferSize);
3709 // TODO: In testing, mSinkBuffer below need not be cleared because
3710 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
3711 // after mixing.
3712 //
3713 // To enforce this guarantee:
3714 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3715 // (mixedTracks == 0 && fastTracks > 0))
3716 // must imply MIXER_TRACKS_READY.
3717 // Later, we may clear buffers regardless, and skip much of this logic.
3718 }
Andy Hung98ef9782014-03-04 14:46:50 -08003719 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07003720 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003721 }
3722
3723 // if any fast tracks, then status is ready
3724 mMixerStatusIgnoringFastTracks = mixerStatus;
3725 if (fastTracks > 0) {
3726 mixerStatus = MIXER_TRACKS_READY;
3727 }
3728 return mixerStatus;
3729}
3730
3731// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07003732int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
3733 audio_format_t format, int sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08003734{
Andy Hunge8a1ced2014-05-09 15:02:21 -07003735 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08003736}
3737
3738// deleteTrackName_l() must be called with ThreadBase::mLock held
3739void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3740{
3741 ALOGV("remove track (%d) and delete from mixer", name);
3742 mAudioMixer->deleteTrackName(name);
3743}
3744
Eric Laurent10351942014-05-08 18:49:52 -07003745// checkForNewParameter_l() must be called with ThreadBase::mLock held
3746bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
3747 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08003748{
Eric Laurent81784c32012-11-19 14:55:58 -08003749 bool reconfig = false;
3750
Eric Laurent10351942014-05-08 18:49:52 -07003751 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08003752
Eric Laurent10351942014-05-08 18:49:52 -07003753 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3754 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003755 if (mFastMixer != 0) {
Eric Laurent10351942014-05-08 18:49:52 -07003756 FastMixerStateQueue *sq = mFastMixer->sq();
3757 FastMixerState *state = sq->begin();
3758 if (!(state->mCommand & FastMixerState::IDLE)) {
3759 previousCommand = state->mCommand;
3760 state->mCommand = FastMixerState::HOT_IDLE;
3761 sq->end();
3762 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3763 } else {
3764 sq->end(false /*didModify*/);
Eric Laurent81784c32012-11-19 14:55:58 -08003765 }
Eric Laurent10351942014-05-08 18:49:52 -07003766 }
Eric Laurent81784c32012-11-19 14:55:58 -08003767
Eric Laurent10351942014-05-08 18:49:52 -07003768 AudioParameter param = AudioParameter(keyValuePair);
3769 int value;
3770 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3771 reconfig = true;
3772 }
3773 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07003774 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07003775 status = BAD_VALUE;
3776 } else {
3777 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08003778 reconfig = true;
3779 }
Eric Laurent10351942014-05-08 18:49:52 -07003780 }
3781 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07003782 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07003783 status = BAD_VALUE;
3784 } else {
3785 // no need to save value, since it's constant
3786 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003787 }
Eric Laurent10351942014-05-08 18:49:52 -07003788 }
3789 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3790 // do not accept frame count changes if tracks are open as the track buffer
3791 // size depends on frame count and correct behavior would not be guaranteed
3792 // if frame count is changed after track creation
3793 if (!mTracks.isEmpty()) {
3794 status = INVALID_OPERATION;
3795 } else {
3796 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003797 }
Eric Laurent10351942014-05-08 18:49:52 -07003798 }
3799 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08003800#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07003801 // when changing the audio output device, call addBatteryData to notify
3802 // the change
3803 if (mOutDevice != value) {
3804 uint32_t params = 0;
3805 // check whether speaker is on
3806 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
3807 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08003808 }
Eric Laurent10351942014-05-08 18:49:52 -07003809
3810 audio_devices_t deviceWithoutSpeaker
3811 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3812 // check if any other device (except speaker) is on
3813 if (value & deviceWithoutSpeaker ) {
3814 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3815 }
3816
3817 if (params != 0) {
3818 addBatteryData(params);
3819 }
3820 }
Eric Laurent81784c32012-11-19 14:55:58 -08003821#endif
3822
Eric Laurent10351942014-05-08 18:49:52 -07003823 // forward device change to effects that have requested to be
3824 // aware of attached audio device.
3825 if (value != AUDIO_DEVICE_NONE) {
3826 mOutDevice = value;
3827 for (size_t i = 0; i < mEffectChains.size(); i++) {
3828 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08003829 }
3830 }
Eric Laurent10351942014-05-08 18:49:52 -07003831 }
Eric Laurent81784c32012-11-19 14:55:58 -08003832
Eric Laurent10351942014-05-08 18:49:52 -07003833 if (status == NO_ERROR) {
3834 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3835 keyValuePair.string());
3836 if (!mStandby && status == INVALID_OPERATION) {
3837 mOutput->stream->common.standby(&mOutput->stream->common);
3838 mStandby = true;
3839 mBytesWritten = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003840 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Eric Laurent10351942014-05-08 18:49:52 -07003841 keyValuePair.string());
Eric Laurent81784c32012-11-19 14:55:58 -08003842 }
Eric Laurent10351942014-05-08 18:49:52 -07003843 if (status == NO_ERROR && reconfig) {
3844 readOutputParameters_l();
3845 delete mAudioMixer;
3846 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3847 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07003848 int name = getTrackName_l(mTracks[i]->mChannelMask,
3849 mTracks[i]->mFormat, mTracks[i]->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07003850 if (name < 0) {
3851 break;
3852 }
3853 mTracks[i]->mName = name;
3854 }
3855 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3856 }
Eric Laurent81784c32012-11-19 14:55:58 -08003857 }
3858
3859 if (!(previousCommand & FastMixerState::IDLE)) {
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003860 ALOG_ASSERT(mFastMixer != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08003861 FastMixerStateQueue *sq = mFastMixer->sq();
3862 FastMixerState *state = sq->begin();
3863 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3864 state->mCommand = previousCommand;
3865 sq->end();
3866 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3867 }
3868
3869 return reconfig;
3870}
3871
3872
3873void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
3874{
3875 const size_t SIZE = 256;
3876 char buffer[SIZE];
3877 String8 result;
3878
3879 PlaybackThread::dumpInternals(fd, args);
3880
Elliott Hughes87cebad2014-05-22 10:14:43 -07003881 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Eric Laurent81784c32012-11-19 14:55:58 -08003882
3883 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003884 const FastMixerDumpState copy(mFastMixerDumpState);
Eric Laurent81784c32012-11-19 14:55:58 -08003885 copy.dump(fd);
3886
3887#ifdef STATE_QUEUE_DUMP
3888 // Similar for state queue
3889 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
3890 observerCopy.dump(fd);
3891 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
3892 mutatorCopy.dump(fd);
3893#endif
3894
Glenn Kasten46909e72013-02-26 09:20:22 -08003895#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003896 // Write the tee output to a .wav file
3897 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08003898#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003899
3900#ifdef AUDIO_WATCHDOG
3901 if (mAudioWatchdog != 0) {
3902 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
3903 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
3904 wdCopy.dump(fd);
3905 }
3906#endif
3907}
3908
3909uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
3910{
3911 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
3912}
3913
3914uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
3915{
3916 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3917}
3918
3919void AudioFlinger::MixerThread::cacheParameters_l()
3920{
3921 PlaybackThread::cacheParameters_l();
3922
3923 // FIXME: Relaxed timing because of a certain device that can't meet latency
3924 // Should be reduced to 2x after the vendor fixes the driver issue
3925 // increase threshold again due to low power audio mode. The way this warning
3926 // threshold is calculated and its usefulness should be reconsidered anyway.
3927 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
3928}
3929
3930// ----------------------------------------------------------------------------
3931
3932AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3933 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
3934 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
3935 // mLeftVolFloat, mRightVolFloat
3936{
3937}
3938
Eric Laurentbfb1b832013-01-07 09:53:42 -08003939AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3940 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
3941 ThreadBase::type_t type)
3942 : PlaybackThread(audioFlinger, output, id, device, type)
3943 // mLeftVolFloat, mRightVolFloat
3944{
3945}
3946
Eric Laurent81784c32012-11-19 14:55:58 -08003947AudioFlinger::DirectOutputThread::~DirectOutputThread()
3948{
3949}
3950
Eric Laurentbfb1b832013-01-07 09:53:42 -08003951void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
3952{
3953 audio_track_cblk_t* cblk = track->cblk();
3954 float left, right;
3955
3956 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
3957 left = right = 0;
3958 } else {
3959 float typeVolume = mStreamTypes[track->streamType()].volume;
3960 float v = mMasterVolume * typeVolume;
3961 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07003962 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
3963 left = float_from_gain(gain_minifloat_unpack_left(vlr));
3964 if (left > GAIN_FLOAT_UNITY) {
3965 left = GAIN_FLOAT_UNITY;
3966 }
3967 left *= v;
3968 right = float_from_gain(gain_minifloat_unpack_right(vlr));
3969 if (right > GAIN_FLOAT_UNITY) {
3970 right = GAIN_FLOAT_UNITY;
3971 }
3972 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003973 }
3974
3975 if (lastTrack) {
3976 if (left != mLeftVolFloat || right != mRightVolFloat) {
3977 mLeftVolFloat = left;
3978 mRightVolFloat = right;
3979
3980 // Convert volumes from float to 8.24
3981 uint32_t vl = (uint32_t)(left * (1 << 24));
3982 uint32_t vr = (uint32_t)(right * (1 << 24));
3983
3984 // Delegate volume control to effect in track effect chain if needed
3985 // only one effect chain can be present on DirectOutputThread, so if
3986 // there is one, the track is connected to it
3987 if (!mEffectChains.isEmpty()) {
3988 mEffectChains[0]->setVolume_l(&vl, &vr);
3989 left = (float)vl / (1 << 24);
3990 right = (float)vr / (1 << 24);
3991 }
3992 if (mOutput->stream->set_volume) {
3993 mOutput->stream->set_volume(mOutput->stream, left, right);
3994 }
3995 }
3996 }
3997}
3998
3999
Eric Laurent81784c32012-11-19 14:55:58 -08004000AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4001 Vector< sp<Track> > *tracksToRemove
4002)
4003{
Eric Laurentd595b7c2013-04-03 17:27:56 -07004004 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08004005 mixer_state mixerStatus = MIXER_IDLE;
4006
4007 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07004008 for (size_t i = 0; i < count; i++) {
4009 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08004010 // The track died recently
4011 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004012 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08004013 }
4014
4015 Track* const track = t.get();
4016 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07004017 // Only consider last track started for volume and mixer state control.
4018 // In theory an older track could underrun and restart after the new one starts
4019 // but as we only care about the transition phase between two tracks on a
4020 // direct output, it is not a problem to ignore the underrun case.
4021 sp<Track> l = mLatestActiveTrack.promote();
4022 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08004023
4024 // The first time a track is added we wait
4025 // for all its buffers to be filled before processing it
4026 uint32_t minFrames;
Eric Laurentab5cdba2014-06-09 17:22:27 -07004027 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004028 minFrames = mNormalFrameCount;
4029 } else {
4030 minFrames = 1;
4031 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004032
Eric Laurentab5cdba2014-06-09 17:22:27 -07004033 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4034 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08004035 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004036 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08004037
4038 if (track->mFillingUpStatus == Track::FS_FILLED) {
4039 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004040 // make sure processVolume_l() will apply new volume even if 0
4041 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurent81784c32012-11-19 14:55:58 -08004042 if (track->mState == TrackBase::RESUMING) {
4043 track->mState = TrackBase::ACTIVE;
4044 }
4045 }
4046
4047 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004048 processVolume_l(track, last);
4049 if (last) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004050 // reset retry count
4051 track->mRetryCount = kMaxTrackRetriesDirect;
4052 mActiveTrack = t;
4053 mixerStatus = MIXER_TRACKS_READY;
4054 }
Eric Laurent81784c32012-11-19 14:55:58 -08004055 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004056 // clear effect chain input buffer if the last active track started underruns
4057 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07004058 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004059 mEffectChains[0]->clearInputBuffer();
4060 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004061 if (track->isStopping_1()) {
4062 track->mState = TrackBase::STOPPING_2;
4063 }
4064 if ((track->sharedBuffer() != 0) || track->isStopped() ||
4065 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004066 // We have consumed all the buffers of this track.
4067 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07004068 size_t audioHALFrames;
4069 if (audio_is_linear_pcm(mFormat)) {
4070 audioHALFrames = (latency_l() * mSampleRate) / 1000;
4071 } else {
4072 audioHALFrames = 0;
4073 }
4074
Eric Laurent81784c32012-11-19 14:55:58 -08004075 size_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07004076 if (mStandby || !last ||
4077 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004078 if (track->isStopping_2()) {
4079 track->mState = TrackBase::STOPPED;
4080 }
Eric Laurent81784c32012-11-19 14:55:58 -08004081 if (track->isStopped()) {
Eric Laurente659ef42014-09-29 13:06:46 -07004082 if (track->mState == TrackBase::FLUSHED) {
4083 flushHw_l();
4084 }
Eric Laurent81784c32012-11-19 14:55:58 -08004085 track->reset();
4086 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004087 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08004088 }
4089 } else {
4090 // No buffers for this track. Give it a few chances to
4091 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07004092 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08004093 if (--(track->mRetryCount) <= 0) {
4094 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07004095 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004096 // indicate to client process that the track was disabled because of underrun;
4097 // it will then automatically call start() when data is available
4098 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004099 } else if (last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004100 mixerStatus = MIXER_TRACKS_ENABLED;
4101 }
4102 }
4103 }
4104 }
4105
Eric Laurent81784c32012-11-19 14:55:58 -08004106 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004107 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004108
4109 return mixerStatus;
4110}
4111
4112void AudioFlinger::DirectOutputThread::threadLoop_mix()
4113{
Eric Laurent81784c32012-11-19 14:55:58 -08004114 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08004115 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004116 // output audio to hardware
4117 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07004118 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004119 buffer.frameCount = frameCount;
4120 mActiveTrack->getNextBuffer(&buffer);
Glenn Kastenfa319e62013-07-29 17:17:38 -07004121 if (buffer.raw == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08004122 memset(curBuf, 0, frameCount * mFrameSize);
4123 break;
4124 }
4125 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
4126 frameCount -= buffer.frameCount;
4127 curBuf += buffer.frameCount * mFrameSize;
4128 mActiveTrack->releaseBuffer(&buffer);
4129 }
Andy Hung2098f272014-02-27 14:00:06 -08004130 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004131 sleepTime = 0;
4132 standbyTime = systemTime() + standbyDelay;
4133 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004134}
4135
4136void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
4137{
4138 if (sleepTime == 0) {
4139 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4140 sleepTime = activeSleepTime;
4141 } else {
4142 sleepTime = idleSleepTime;
4143 }
4144 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08004145 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004146 sleepTime = 0;
4147 }
4148}
4149
4150// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004151int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Andy Hunge8a1ced2014-05-09 15:02:21 -07004152 audio_format_t format __unused, int sessionId __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004153{
4154 return 0;
4155}
4156
4157// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004158void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004159{
4160}
4161
Eric Laurent10351942014-05-08 18:49:52 -07004162// checkForNewParameter_l() must be called with ThreadBase::mLock held
4163bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
4164 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004165{
4166 bool reconfig = false;
4167
Eric Laurent10351942014-05-08 18:49:52 -07004168 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004169
Eric Laurent10351942014-05-08 18:49:52 -07004170 AudioParameter param = AudioParameter(keyValuePair);
4171 int value;
4172 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4173 // forward device change to effects that have requested to be
4174 // aware of attached audio device.
4175 if (value != AUDIO_DEVICE_NONE) {
4176 mOutDevice = value;
4177 for (size_t i = 0; i < mEffectChains.size(); i++) {
4178 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07004179 }
4180 }
Eric Laurent81784c32012-11-19 14:55:58 -08004181 }
Eric Laurent10351942014-05-08 18:49:52 -07004182 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4183 // do not accept frame count changes if tracks are open as the track buffer
4184 // size depends on frame count and correct behavior would not be garantied
4185 // if frame count is changed after track creation
4186 if (!mTracks.isEmpty()) {
4187 status = INVALID_OPERATION;
4188 } else {
4189 reconfig = true;
4190 }
4191 }
4192 if (status == NO_ERROR) {
4193 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4194 keyValuePair.string());
4195 if (!mStandby && status == INVALID_OPERATION) {
4196 mOutput->stream->common.standby(&mOutput->stream->common);
4197 mStandby = true;
4198 mBytesWritten = 0;
4199 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4200 keyValuePair.string());
4201 }
4202 if (status == NO_ERROR && reconfig) {
4203 readOutputParameters_l();
4204 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
4205 }
4206 }
4207
Eric Laurent81784c32012-11-19 14:55:58 -08004208 return reconfig;
4209}
4210
4211uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
4212{
4213 uint32_t time;
4214 if (audio_is_linear_pcm(mFormat)) {
4215 time = PlaybackThread::activeSleepTimeUs();
4216 } else {
4217 time = 10000;
4218 }
4219 return time;
4220}
4221
4222uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
4223{
4224 uint32_t time;
4225 if (audio_is_linear_pcm(mFormat)) {
4226 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
4227 } else {
4228 time = 10000;
4229 }
4230 return time;
4231}
4232
4233uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
4234{
4235 uint32_t time;
4236 if (audio_is_linear_pcm(mFormat)) {
4237 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
4238 } else {
4239 time = 10000;
4240 }
4241 return time;
4242}
4243
4244void AudioFlinger::DirectOutputThread::cacheParameters_l()
4245{
4246 PlaybackThread::cacheParameters_l();
4247
4248 // use shorter standby delay as on normal output to release
4249 // hardware resources as soon as possible
Eric Laurent972a1732013-09-04 09:42:59 -07004250 if (audio_is_linear_pcm(mFormat)) {
4251 standbyDelay = microseconds(activeSleepTime*2);
4252 } else {
4253 standbyDelay = kOffloadStandbyDelayNs;
4254 }
Eric Laurent81784c32012-11-19 14:55:58 -08004255}
4256
Eric Laurente659ef42014-09-29 13:06:46 -07004257void AudioFlinger::DirectOutputThread::flushHw_l()
4258{
4259 if (mOutput->stream->flush != NULL)
4260 mOutput->stream->flush(mOutput->stream);
4261}
4262
Eric Laurent81784c32012-11-19 14:55:58 -08004263// ----------------------------------------------------------------------------
4264
Eric Laurentbfb1b832013-01-07 09:53:42 -08004265AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07004266 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004267 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07004268 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07004269 mWriteAckSequence(0),
4270 mDrainSequence(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004271{
4272}
4273
4274AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
4275{
4276}
4277
4278void AudioFlinger::AsyncCallbackThread::onFirstRef()
4279{
4280 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
4281}
4282
4283bool AudioFlinger::AsyncCallbackThread::threadLoop()
4284{
4285 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004286 uint32_t writeAckSequence;
4287 uint32_t drainSequence;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004288
4289 {
4290 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08004291 while (!((mWriteAckSequence & 1) ||
4292 (mDrainSequence & 1) ||
4293 exitPending())) {
4294 mWaitWorkCV.wait(mLock);
4295 }
4296
Eric Laurentbfb1b832013-01-07 09:53:42 -08004297 if (exitPending()) {
4298 break;
4299 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004300 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
4301 mWriteAckSequence, mDrainSequence);
4302 writeAckSequence = mWriteAckSequence;
4303 mWriteAckSequence &= ~1;
4304 drainSequence = mDrainSequence;
4305 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004306 }
4307 {
Eric Laurent4de95592013-09-26 15:28:21 -07004308 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
4309 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004310 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004311 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004312 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004313 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004314 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004315 }
4316 }
4317 }
4318 }
4319 return false;
4320}
4321
4322void AudioFlinger::AsyncCallbackThread::exit()
4323{
4324 ALOGV("AsyncCallbackThread::exit");
4325 Mutex::Autolock _l(mLock);
4326 requestExit();
4327 mWaitWorkCV.broadcast();
4328}
4329
Eric Laurent3b4529e2013-09-05 18:09:19 -07004330void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004331{
4332 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004333 // bit 0 is cleared
4334 mWriteAckSequence = sequence << 1;
4335}
4336
4337void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
4338{
4339 Mutex::Autolock _l(mLock);
4340 // ignore unexpected callbacks
4341 if (mWriteAckSequence & 2) {
4342 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004343 mWaitWorkCV.signal();
4344 }
4345}
4346
Eric Laurent3b4529e2013-09-05 18:09:19 -07004347void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004348{
4349 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004350 // bit 0 is cleared
4351 mDrainSequence = sequence << 1;
4352}
4353
4354void AudioFlinger::AsyncCallbackThread::resetDraining()
4355{
4356 Mutex::Autolock _l(mLock);
4357 // ignore unexpected callbacks
4358 if (mDrainSequence & 2) {
4359 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004360 mWaitWorkCV.signal();
4361 }
4362}
4363
4364
4365// ----------------------------------------------------------------------------
4366AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
4367 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
4368 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD),
4369 mHwPaused(false),
Eric Laurentea0fade2013-10-04 16:23:48 -07004370 mFlushPending(false),
Eric Laurentd7e59222013-11-15 12:02:28 -08004371 mPausedBytesRemaining(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004372{
Eric Laurentfd477972013-10-25 18:10:40 -07004373 //FIXME: mStandby should be set to true by ThreadBase constructor
4374 mStandby = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004375}
4376
Eric Laurentbfb1b832013-01-07 09:53:42 -08004377void AudioFlinger::OffloadThread::threadLoop_exit()
4378{
4379 if (mFlushPending || mHwPaused) {
4380 // If a flush is pending or track was paused, just discard buffered data
4381 flushHw_l();
4382 } else {
4383 mMixerStatus = MIXER_DRAIN_ALL;
4384 threadLoop_drain();
4385 }
Uday Gupta56604aa2014-05-13 11:19:17 -07004386 if (mUseAsyncWrite) {
4387 ALOG_ASSERT(mCallbackThread != 0);
4388 mCallbackThread->exit();
4389 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004390 PlaybackThread::threadLoop_exit();
4391}
4392
4393AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
4394 Vector< sp<Track> > *tracksToRemove
4395)
4396{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004397 size_t count = mActiveTracks.size();
4398
4399 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07004400 bool doHwPause = false;
4401 bool doHwResume = false;
4402
Eric Laurentede6c3b2013-09-19 14:37:46 -07004403 ALOGV("OffloadThread::prepareTracks_l active tracks %d", count);
4404
Eric Laurentbfb1b832013-01-07 09:53:42 -08004405 // find out which tracks need to be processed
4406 for (size_t i = 0; i < count; i++) {
4407 sp<Track> t = mActiveTracks[i].promote();
4408 // The track died recently
4409 if (t == 0) {
4410 continue;
4411 }
4412 Track* const track = t.get();
4413 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07004414 // Only consider last track started for volume and mixer state control.
4415 // In theory an older track could underrun and restart after the new one starts
4416 // but as we only care about the transition phase between two tracks on a
4417 // direct output, it is not a problem to ignore the underrun case.
4418 sp<Track> l = mLatestActiveTrack.promote();
4419 bool last = l.get() == track;
4420
Haynes Mathew George7844f672014-01-15 12:32:55 -08004421 if (track->isInvalid()) {
4422 ALOGW("An invalidated track shouldn't be in active list");
4423 tracksToRemove->add(track);
4424 continue;
4425 }
4426
4427 if (track->mState == TrackBase::IDLE) {
4428 ALOGW("An idle track shouldn't be in active list");
4429 continue;
4430 }
4431
Eric Laurentbfb1b832013-01-07 09:53:42 -08004432 if (track->isPausing()) {
4433 track->setPaused();
4434 if (last) {
4435 if (!mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07004436 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004437 mHwPaused = true;
4438 }
4439 // If we were part way through writing the mixbuffer to
4440 // the HAL we must save this until we resume
4441 // BUG - this will be wrong if a different track is made active,
4442 // in that case we want to discard the pending data in the
4443 // mixbuffer and tell the client to present it again when the
4444 // track is resumed
4445 mPausedWriteLength = mCurrentWriteLength;
4446 mPausedBytesRemaining = mBytesRemaining;
4447 mBytesRemaining = 0; // stop writing
4448 }
4449 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08004450 } else if (track->isFlushPending()) {
4451 track->flushAck();
4452 if (last) {
4453 mFlushPending = true;
4454 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08004455 } else if (track->isResumePending()){
4456 track->resumeAck();
4457 if (last) {
4458 if (mPausedBytesRemaining) {
4459 // Need to continue write that was interrupted
4460 mCurrentWriteLength = mPausedWriteLength;
4461 mBytesRemaining = mPausedBytesRemaining;
4462 mPausedBytesRemaining = 0;
4463 }
4464 if (mHwPaused) {
4465 doHwResume = true;
4466 mHwPaused = false;
4467 // threadLoop_mix() will handle the case that we need to
4468 // resume an interrupted write
4469 }
4470 // enable write to audio HAL
4471 sleepTime = 0;
4472
4473 // Do not handle new data in this iteration even if track->framesReady()
4474 mixerStatus = MIXER_TRACKS_ENABLED;
4475 }
4476 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07004477 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004478 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004479 if (track->mFillingUpStatus == Track::FS_FILLED) {
4480 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004481 // make sure processVolume_l() will apply new volume even if 0
4482 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004483 }
4484
4485 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08004486 sp<Track> previousTrack = mPreviousTrack.promote();
4487 if (previousTrack != 0) {
4488 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08004489 // Flush any data still being written from last track
4490 mBytesRemaining = 0;
4491 if (mPausedBytesRemaining) {
4492 // Last track was paused so we also need to flush saved
4493 // mixbuffer state and invalidate track so that it will
4494 // re-submit that unwritten data when it is next resumed
4495 mPausedBytesRemaining = 0;
4496 // Invalidate is a bit drastic - would be more efficient
4497 // to have a flag to tell client that some of the
4498 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08004499 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004500 }
4501 // flush data already sent to the DSP if changing audio session as audio
4502 // comes from a different source. Also invalidate previous track to force a
4503 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08004504 if (previousTrack->sessionId() != track->sessionId()) {
4505 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004506 }
4507 }
4508 }
4509 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004510 // reset retry count
4511 track->mRetryCount = kMaxTrackRetriesOffload;
4512 mActiveTrack = t;
4513 mixerStatus = MIXER_TRACKS_READY;
4514 }
4515 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004516 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004517 if (track->isStopping_1()) {
4518 // Hardware buffer can hold a large amount of audio so we must
4519 // wait for all current track's data to drain before we say
4520 // that the track is stopped.
4521 if (mBytesRemaining == 0) {
4522 // Only start draining when all data in mixbuffer
4523 // has been written
4524 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
4525 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004526 // do not drain if no data was ever sent to HAL (mStandby == true)
4527 if (last && !mStandby) {
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004528 // do not modify drain sequence if we are already draining. This happens
4529 // when resuming from pause after drain.
4530 if ((mDrainSequence & 1) == 0) {
4531 sleepTime = 0;
4532 standbyTime = systemTime() + standbyDelay;
4533 mixerStatus = MIXER_DRAIN_TRACK;
4534 mDrainSequence += 2;
4535 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004536 if (mHwPaused) {
4537 // It is possible to move from PAUSED to STOPPING_1 without
4538 // a resume so we must ensure hardware is running
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004539 doHwResume = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004540 mHwPaused = false;
4541 }
4542 }
4543 }
4544 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004545 // Drain has completed or we are in standby, signal presentation complete
4546 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004547 track->mState = TrackBase::STOPPED;
4548 size_t audioHALFrames =
4549 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
4550 size_t framesWritten =
Eric Laurent665470b2014-07-03 16:37:08 -07004551 mBytesWritten / audio_stream_out_frame_size(mOutput->stream);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004552 track->presentationComplete(framesWritten, audioHALFrames);
4553 track->reset();
4554 tracksToRemove->add(track);
4555 }
4556 } else {
4557 // No buffers for this track. Give it a few chances to
4558 // fill a buffer, then remove it from active list.
4559 if (--(track->mRetryCount) <= 0) {
4560 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
4561 track->name());
4562 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004563 // indicate to client process that the track was disabled because of underrun;
4564 // it will then automatically call start() when data is available
4565 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004566 } else if (last){
4567 mixerStatus = MIXER_TRACKS_ENABLED;
4568 }
4569 }
4570 }
4571 // compute volume for this track
4572 processVolume_l(track, last);
4573 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004574
Eric Laurentea0fade2013-10-04 16:23:48 -07004575 // make sure the pause/flush/resume sequence is executed in the right order.
4576 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4577 // before flush and then resume HW. This can happen in case of pause/flush/resume
4578 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07004579 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurent972a1732013-09-04 09:42:59 -07004580 mOutput->stream->pause(mOutput->stream);
4581 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004582 if (mFlushPending) {
4583 flushHw_l();
4584 mFlushPending = false;
4585 }
Eric Laurentfd477972013-10-25 18:10:40 -07004586 if (!mStandby && doHwResume) {
Eric Laurent972a1732013-09-04 09:42:59 -07004587 mOutput->stream->resume(mOutput->stream);
4588 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004589
Eric Laurentbfb1b832013-01-07 09:53:42 -08004590 // remove all the tracks that need to be...
4591 removeTracks_l(*tracksToRemove);
4592
4593 return mixerStatus;
4594}
4595
Eric Laurentbfb1b832013-01-07 09:53:42 -08004596// must be called with thread mutex locked
4597bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
4598{
Eric Laurent3b4529e2013-09-05 18:09:19 -07004599 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
4600 mWriteAckSequence, mDrainSequence);
4601 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004602 return true;
4603 }
4604 return false;
4605}
4606
4607// must be called with thread mutex locked
4608bool AudioFlinger::OffloadThread::shouldStandby_l()
4609{
Glenn Kastene6f35b12013-08-19 09:58:50 -07004610 bool trackPaused = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004611
4612 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4613 // after a timeout and we will enter standby then.
4614 if (mTracks.size() > 0) {
Glenn Kastene6f35b12013-08-19 09:58:50 -07004615 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004616 }
4617
Glenn Kastene6f35b12013-08-19 09:58:50 -07004618 return !mStandby && !trackPaused;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004619}
4620
4621
4622bool AudioFlinger::OffloadThread::waitingAsyncCallback()
4623{
4624 Mutex::Autolock _l(mLock);
4625 return waitingAsyncCallback_l();
4626}
4627
4628void AudioFlinger::OffloadThread::flushHw_l()
4629{
Eric Laurente659ef42014-09-29 13:06:46 -07004630 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004631 // Flush anything still waiting in the mixbuffer
4632 mCurrentWriteLength = 0;
4633 mBytesRemaining = 0;
4634 mPausedWriteLength = 0;
4635 mPausedBytesRemaining = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08004636 mHwPaused = false;
4637
Eric Laurentbfb1b832013-01-07 09:53:42 -08004638 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004639 // discard any pending drain or write ack by incrementing sequence
4640 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4641 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004642 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004643 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4644 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004645 }
4646}
4647
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08004648void AudioFlinger::OffloadThread::onAddNewTrack_l()
4649{
4650 sp<Track> previousTrack = mPreviousTrack.promote();
4651 sp<Track> latestTrack = mLatestActiveTrack.promote();
4652
4653 if (previousTrack != 0 && latestTrack != 0 &&
4654 (previousTrack->sessionId() != latestTrack->sessionId())) {
4655 mFlushPending = true;
4656 }
4657 PlaybackThread::onAddNewTrack_l();
4658}
4659
Eric Laurentbfb1b832013-01-07 09:53:42 -08004660// ----------------------------------------------------------------------------
4661
Eric Laurent81784c32012-11-19 14:55:58 -08004662AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
4663 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
4664 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
4665 DUPLICATING),
4666 mWaitTimeMs(UINT_MAX)
4667{
4668 addOutputTrack(mainThread);
4669}
4670
4671AudioFlinger::DuplicatingThread::~DuplicatingThread()
4672{
4673 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4674 mOutputTracks[i]->destroy();
4675 }
4676}
4677
4678void AudioFlinger::DuplicatingThread::threadLoop_mix()
4679{
4680 // mix buffers...
4681 if (outputsReady(outputTracks)) {
4682 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
4683 } else {
Eric Laurent995599c2014-11-07 17:28:28 -08004684 if (mMixerBufferValid) {
4685 memset(mMixerBuffer, 0, mMixerBufferSize);
4686 } else {
4687 memset(mSinkBuffer, 0, mSinkBufferSize);
4688 }
Eric Laurent81784c32012-11-19 14:55:58 -08004689 }
4690 sleepTime = 0;
4691 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08004692 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004693 standbyTime = systemTime() + standbyDelay;
4694}
4695
4696void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
4697{
4698 if (sleepTime == 0) {
4699 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4700 sleepTime = activeSleepTime;
4701 } else {
4702 sleepTime = idleSleepTime;
4703 }
4704 } else if (mBytesWritten != 0) {
4705 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4706 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08004707 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004708 } else {
4709 // flush remaining overflow buffers in output tracks
4710 writeFrames = 0;
4711 }
4712 sleepTime = 0;
4713 }
4714}
4715
Eric Laurentbfb1b832013-01-07 09:53:42 -08004716ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004717{
4718 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung010a1a12014-03-13 13:57:33 -07004719 // We convert the duplicating thread format to AUDIO_FORMAT_PCM_16_BIT
4720 // for delivery downstream as needed. This in-place conversion is safe as
4721 // AUDIO_FORMAT_PCM_16_BIT is smaller than any other supported format
4722 // (AUDIO_FORMAT_PCM_8_BIT is not allowed here).
4723 if (mFormat != AUDIO_FORMAT_PCM_16_BIT) {
4724 memcpy_by_audio_format(mSinkBuffer, AUDIO_FORMAT_PCM_16_BIT,
4725 mSinkBuffer, mFormat, writeFrames * mChannelCount);
4726 }
4727 outputTracks[i]->write(reinterpret_cast<int16_t*>(mSinkBuffer), writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08004728 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07004729 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08004730 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004731}
4732
4733void AudioFlinger::DuplicatingThread::threadLoop_standby()
4734{
4735 // DuplicatingThread implements standby by stopping all tracks
4736 for (size_t i = 0; i < outputTracks.size(); i++) {
4737 outputTracks[i]->stop();
4738 }
4739}
4740
4741void AudioFlinger::DuplicatingThread::saveOutputTracks()
4742{
4743 outputTracks = mOutputTracks;
4744}
4745
4746void AudioFlinger::DuplicatingThread::clearOutputTracks()
4747{
4748 outputTracks.clear();
4749}
4750
4751void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
4752{
4753 Mutex::Autolock _l(mLock);
4754 // FIXME explain this formula
4755 size_t frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
Andy Hung010a1a12014-03-13 13:57:33 -07004756 // OutputTrack is forced to AUDIO_FORMAT_PCM_16_BIT regardless of mFormat
4757 // due to current usage case and restrictions on the AudioBufferProvider.
4758 // Actual buffer conversion is done in threadLoop_write().
4759 //
4760 // TODO: This may change in the future, depending on multichannel
4761 // (and non int16_t*) support on AF::PlaybackThread::OutputTrack
Eric Laurent81784c32012-11-19 14:55:58 -08004762 OutputTrack *outputTrack = new OutputTrack(thread,
4763 this,
4764 mSampleRate,
Andy Hung010a1a12014-03-13 13:57:33 -07004765 AUDIO_FORMAT_PCM_16_BIT,
Eric Laurent81784c32012-11-19 14:55:58 -08004766 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004767 frameCount,
4768 IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08004769 if (outputTrack->cblk() != NULL) {
4770 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
4771 mOutputTracks.add(outputTrack);
4772 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
4773 updateWaitTime_l();
4774 }
4775}
4776
4777void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
4778{
4779 Mutex::Autolock _l(mLock);
4780 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4781 if (mOutputTracks[i]->thread() == thread) {
4782 mOutputTracks[i]->destroy();
4783 mOutputTracks.removeAt(i);
4784 updateWaitTime_l();
Eric Laurentb97ee932015-05-08 10:50:03 -07004785 if (thread->getOutput() == mOutput) {
4786 mOutput = NULL;
4787 }
Eric Laurent81784c32012-11-19 14:55:58 -08004788 return;
4789 }
4790 }
Eric Laurentb97ee932015-05-08 10:50:03 -07004791 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08004792}
4793
4794// caller must hold mLock
4795void AudioFlinger::DuplicatingThread::updateWaitTime_l()
4796{
4797 mWaitTimeMs = UINT_MAX;
4798 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4799 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
4800 if (strong != 0) {
4801 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4802 if (waitTimeMs < mWaitTimeMs) {
4803 mWaitTimeMs = waitTimeMs;
4804 }
4805 }
4806 }
4807}
4808
4809
4810bool AudioFlinger::DuplicatingThread::outputsReady(
4811 const SortedVector< sp<OutputTrack> > &outputTracks)
4812{
4813 for (size_t i = 0; i < outputTracks.size(); i++) {
4814 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
4815 if (thread == 0) {
4816 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
4817 outputTracks[i].get());
4818 return false;
4819 }
4820 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4821 // see note at standby() declaration
4822 if (playbackThread->standby() && !playbackThread->isSuspended()) {
4823 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
4824 thread.get());
4825 return false;
4826 }
4827 }
4828 return true;
4829}
4830
4831uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
4832{
4833 return (mWaitTimeMs * 1000) / 2;
4834}
4835
4836void AudioFlinger::DuplicatingThread::cacheParameters_l()
4837{
4838 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
4839 updateWaitTime_l();
4840
4841 MixerThread::cacheParameters_l();
4842}
4843
4844// ----------------------------------------------------------------------------
4845// Record
4846// ----------------------------------------------------------------------------
4847
4848AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4849 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08004850 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08004851 audio_devices_t outDevice,
Glenn Kasten46909e72013-02-26 09:20:22 -08004852 audio_devices_t inDevice
4853#ifdef TEE_SINK
4854 , const sp<NBAIO_Sink>& teeSink
4855#endif
4856 ) :
Eric Laurentd3922f72013-02-01 17:57:04 -08004857 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD),
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004858 mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
Glenn Kastendeca2ae2014-02-07 10:25:56 -08004859 // mRsmpInFrames and mRsmpInFramesP2 are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08004860 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08004861#ifdef TEE_SINK
4862 , mTeeSink(teeSink)
4863#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07004864 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
4865 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07004866 // mFastCapture below
4867 , mFastCaptureFutex(0)
4868 // mInputSource
4869 // mPipeSink
4870 // mPipeSource
4871 , mPipeFramesP2(0)
4872 // mPipeMemory
4873 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07004874 , mFastTrackAvail(false)
Eric Laurent81784c32012-11-19 14:55:58 -08004875{
4876 snprintf(mName, kNameLength, "AudioIn_%X", id);
Glenn Kasten481fb672013-09-30 14:39:28 -07004877 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mName);
Eric Laurent81784c32012-11-19 14:55:58 -08004878
Glenn Kastendeca2ae2014-02-07 10:25:56 -08004879 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07004880
4881 // create an NBAIO source for the HAL input stream, and negotiate
4882 mInputSource = new AudioStreamInSource(input->stream);
4883 size_t numCounterOffers = 0;
4884 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
4885 ssize_t index = mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
4886 ALOG_ASSERT(index == 0);
4887
4888 // initialize fast capture depending on configuration
4889 bool initFastCapture;
4890 switch (kUseFastCapture) {
4891 case FastCapture_Never:
4892 initFastCapture = false;
4893 break;
4894 case FastCapture_Always:
4895 initFastCapture = true;
4896 break;
4897 case FastCapture_Static:
4898 uint32_t primaryOutputSampleRate;
4899 {
4900 AutoMutex _l(audioFlinger->mHardwareLock);
4901 primaryOutputSampleRate = audioFlinger->mPrimaryOutputSampleRate;
4902 }
4903 initFastCapture =
4904 // either capture sample rate is same as (a reasonable) primary output sample rate
4905 (((primaryOutputSampleRate == 44100 || primaryOutputSampleRate == 48000) &&
4906 (mSampleRate == primaryOutputSampleRate)) ||
4907 // or primary output sample rate is unknown, and capture sample rate is reasonable
4908 ((primaryOutputSampleRate == 0) &&
4909 ((mSampleRate == 44100 || mSampleRate == 48000)))) &&
Glenn Kasten9f81de32014-07-27 15:02:23 -07004910 // and the buffer size is < 12 ms
4911 (mFrameCount * 1000) / mSampleRate < 12;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07004912 break;
4913 // case FastCapture_Dynamic:
4914 }
4915
4916 if (initFastCapture) {
4917 // create a Pipe for FastMixer to write to, and for us and fast tracks to read from
4918 NBAIO_Format format = mInputSource->format();
Glenn Kasten49d00ad2014-07-21 11:22:03 -07004919 size_t pipeFramesP2 = roundup(mSampleRate / 25); // double-buffering of 20 ms each
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07004920 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
4921 void *pipeBuffer;
4922 const sp<MemoryDealer> roHeap(readOnlyHeap());
4923 sp<IMemory> pipeMemory;
4924 if ((roHeap == 0) ||
4925 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
4926 (pipeBuffer = pipeMemory->pointer()) == NULL) {
4927 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
4928 goto failed;
4929 }
4930 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
4931 memset(pipeBuffer, 0, pipeSize);
4932 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
4933 const NBAIO_Format offers[1] = {format};
4934 size_t numCounterOffers = 0;
4935 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
4936 ALOG_ASSERT(index == 0);
4937 mPipeSink = pipe;
4938 PipeReader *pipeReader = new PipeReader(*pipe);
4939 numCounterOffers = 0;
4940 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
4941 ALOG_ASSERT(index == 0);
4942 mPipeSource = pipeReader;
4943 mPipeFramesP2 = pipeFramesP2;
4944 mPipeMemory = pipeMemory;
4945
4946 // create fast capture
4947 mFastCapture = new FastCapture();
4948 FastCaptureStateQueue *sq = mFastCapture->sq();
4949#ifdef STATE_QUEUE_DUMP
4950 // FIXME
4951#endif
4952 FastCaptureState *state = sq->begin();
4953 state->mCblk = NULL;
4954 state->mInputSource = mInputSource.get();
4955 state->mInputSourceGen++;
4956 state->mPipeSink = pipe;
4957 state->mPipeSinkGen++;
4958 state->mFrameCount = mFrameCount;
4959 state->mCommand = FastCaptureState::COLD_IDLE;
4960 // already done in constructor initialization list
4961 //mFastCaptureFutex = 0;
4962 state->mColdFutexAddr = &mFastCaptureFutex;
4963 state->mColdGen++;
4964 state->mDumpState = &mFastCaptureDumpState;
4965#ifdef TEE_SINK
4966 // FIXME
4967#endif
4968 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
4969 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
4970 sq->end();
4971 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
4972
4973 // start the fast capture
4974 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
4975 pid_t tid = mFastCapture->getTid();
4976 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
4977 if (err != 0) {
4978 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
4979 kPriorityFastCapture, getpid_cached, tid, err);
4980 }
4981
4982#ifdef AUDIO_WATCHDOG
4983 // FIXME
4984#endif
4985
Glenn Kasten6e6704c2014-07-03 10:20:00 -07004986 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07004987 }
4988failed: ;
4989
4990 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08004991}
4992
4993
4994AudioFlinger::RecordThread::~RecordThread()
4995{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07004996 if (mFastCapture != 0) {
4997 FastCaptureStateQueue *sq = mFastCapture->sq();
4998 FastCaptureState *state = sq->begin();
4999 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5000 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5001 if (old == -1) {
5002 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5003 }
5004 }
5005 state->mCommand = FastCaptureState::EXIT;
5006 sq->end();
5007 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5008 mFastCapture->join();
5009 mFastCapture.clear();
5010 }
5011 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07005012 mAudioFlinger->unregisterWriter(mNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08005013 delete[] mRsmpInBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005014}
5015
5016void AudioFlinger::RecordThread::onFirstRef()
5017{
5018 run(mName, PRIORITY_URGENT_AUDIO);
5019}
5020
Eric Laurent81784c32012-11-19 14:55:58 -08005021bool AudioFlinger::RecordThread::threadLoop()
5022{
Eric Laurent81784c32012-11-19 14:55:58 -08005023 nsecs_t lastWarning = 0;
5024
5025 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08005026
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005027reacquire_wakelock:
5028 sp<RecordTrack> activeTrack;
Glenn Kasten2b806402013-11-20 16:37:38 -08005029 int activeTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005030 {
5031 Mutex::Autolock _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005032 size_t size = mActiveTracks.size();
5033 activeTracksGen = mActiveTracksGen;
5034 if (size > 0) {
5035 // FIXME an arbitrary choice
5036 activeTrack = mActiveTracks[0];
5037 acquireWakeLock_l(activeTrack->uid());
5038 if (size > 1) {
5039 SortedVector<int> tmp;
5040 for (size_t i = 0; i < size; i++) {
5041 tmp.add(mActiveTracks[i]->uid());
5042 }
5043 updateWakeLockUids_l(tmp);
5044 }
5045 } else {
5046 acquireWakeLock_l(-1);
5047 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005048 }
5049
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005050 // used to request a deferred sleep, to be executed later while mutex is unlocked
5051 uint32_t sleepUs = 0;
5052
5053 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005054 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005055 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07005056
Glenn Kasten5edadd42013-08-14 16:30:49 -07005057 // sleep with mutex unlocked
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005058 if (sleepUs > 0) {
5059 usleep(sleepUs);
5060 sleepUs = 0;
Glenn Kasten5edadd42013-08-14 16:30:49 -07005061 }
5062
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005063 // activeTracks accumulates a copy of a subset of mActiveTracks
5064 Vector< sp<RecordTrack> > activeTracks;
5065
Glenn Kasten735f45f2014-08-18 15:51:59 -07005066 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005067 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07005068
Glenn Kasten735f45f2014-08-18 15:51:59 -07005069 // reference to a fast track which is about to be removed
5070 sp<RecordTrack> fastTrackToRemove;
5071
Eric Laurent81784c32012-11-19 14:55:58 -08005072 { // scope for mLock
5073 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08005074
Eric Laurent021cf962014-05-13 10:18:14 -07005075 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005076
Eric Laurent000a4192014-01-29 15:17:32 -08005077 // check exitPending here because checkForNewParameters_l() and
5078 // checkForNewParameters_l() can temporarily release mLock
5079 if (exitPending()) {
5080 break;
5081 }
5082
Glenn Kasten2b806402013-11-20 16:37:38 -08005083 // if no active track(s), then standby and release wakelock
5084 size_t size = mActiveTracks.size();
5085 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07005086 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005087 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08005088 releaseWakeLock_l();
5089 ALOGV("RecordThread: loop stopping");
5090 // go to sleep
5091 mWaitWorkCV.wait(mLock);
5092 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005093 goto reacquire_wakelock;
5094 }
5095
Glenn Kasten2b806402013-11-20 16:37:38 -08005096 if (mActiveTracksGen != activeTracksGen) {
5097 activeTracksGen = mActiveTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005098 SortedVector<int> tmp;
Glenn Kasten2b806402013-11-20 16:37:38 -08005099 for (size_t i = 0; i < size; i++) {
5100 tmp.add(mActiveTracks[i]->uid());
5101 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005102 updateWakeLockUids_l(tmp);
Eric Laurent81784c32012-11-19 14:55:58 -08005103 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005104
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005105 bool doBroadcast = false;
5106 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07005107
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005108 activeTrack = mActiveTracks[i];
5109 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07005110 if (activeTrack->isFastTrack()) {
5111 ALOG_ASSERT(fastTrackToRemove == 0);
5112 fastTrackToRemove = activeTrack;
5113 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005114 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08005115 mActiveTracks.remove(activeTrack);
5116 mActiveTracksGen++;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005117 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07005118 continue;
5119 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005120
5121 TrackBase::track_state activeTrackState = activeTrack->mState;
5122 switch (activeTrackState) {
5123
5124 case TrackBase::PAUSING:
5125 mActiveTracks.remove(activeTrack);
5126 mActiveTracksGen++;
5127 doBroadcast = true;
5128 size--;
5129 continue;
5130
5131 case TrackBase::STARTING_1:
5132 sleepUs = 10000;
5133 i++;
5134 continue;
5135
5136 case TrackBase::STARTING_2:
5137 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005138 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07005139 activeTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005140 break;
5141
5142 case TrackBase::ACTIVE:
5143 break;
5144
5145 case TrackBase::IDLE:
5146 i++;
5147 continue;
5148
5149 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08005150 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07005151 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005152
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005153 activeTracks.add(activeTrack);
5154 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07005155
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005156 if (activeTrack->isFastTrack()) {
5157 ALOG_ASSERT(!mFastTrackAvail);
5158 ALOG_ASSERT(fastTrack == 0);
5159 fastTrack = activeTrack;
5160 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005161 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005162 if (doBroadcast) {
5163 mStartStopCond.broadcast();
5164 }
5165
5166 // sleep if there are no active tracks to process
5167 if (activeTracks.size() == 0) {
5168 if (sleepUs == 0) {
5169 sleepUs = kRecordThreadSleepUs;
5170 }
5171 continue;
5172 }
5173 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07005174
Eric Laurent81784c32012-11-19 14:55:58 -08005175 lockEffectChains_l(effectChains);
5176 }
5177
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005178 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07005179
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005180 size_t size = effectChains.size();
5181 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005182 // thread mutex is not locked, but effect chain is locked
5183 effectChains[i]->process_l();
5184 }
5185
Glenn Kasten735f45f2014-08-18 15:51:59 -07005186 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005187 if (mFastCapture != 0) {
5188 FastCaptureStateQueue *sq = mFastCapture->sq();
5189 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07005190 bool didModify = false;
5191 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005192 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
5193 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
5194 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5195 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5196 if (old == -1) {
5197 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5198 }
5199 }
5200 state->mCommand = FastCaptureState::READ_WRITE;
5201#if 0 // FIXME
5202 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
5203 FastCaptureDumpState::kSamplingNforLowRamDevice : FastMixerDumpState::kSamplingN);
5204#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07005205 didModify = true;
5206 }
5207 audio_track_cblk_t *cblkOld = state->mCblk;
5208 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
5209 if (cblkNew != cblkOld) {
5210 state->mCblk = cblkNew;
5211 // block until acked if removing a fast track
5212 if (cblkOld != NULL) {
5213 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
5214 }
5215 didModify = true;
5216 }
5217 sq->end(didModify);
5218 if (didModify) {
5219 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005220#if 0
5221 if (kUseFastCapture == FastCapture_Dynamic) {
5222 mNormalSource = mPipeSource;
5223 }
5224#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005225 }
5226 }
5227
Glenn Kasten735f45f2014-08-18 15:51:59 -07005228 // now run the fast track destructor with thread mutex unlocked
5229 fastTrackToRemove.clear();
5230
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005231 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
5232 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
5233 // slow, then this RecordThread will overrun by not calling HAL read often enough.
5234 // If destination is non-contiguous, first read past the nominal end of buffer, then
5235 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005236
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005237 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005238 ssize_t framesRead;
5239
5240 // If an NBAIO source is present, use it to read the normal capture's data
5241 if (mPipeSource != 0) {
5242 size_t framesToRead = mBufferSize / mFrameSize;
5243 framesRead = mPipeSource->read(&mRsmpInBuffer[rear * mChannelCount],
5244 framesToRead, AudioBufferProvider::kInvalidPTS);
5245 if (framesRead == 0) {
5246 // since pipe is non-blocking, simulate blocking input
5247 sleepUs = (framesToRead * 1000000LL) / mSampleRate;
5248 }
5249 // otherwise use the HAL / AudioStreamIn directly
5250 } else {
5251 ssize_t bytesRead = mInput->stream->read(mInput->stream,
5252 &mRsmpInBuffer[rear * mChannelCount], mBufferSize);
5253 if (bytesRead < 0) {
5254 framesRead = bytesRead;
5255 } else {
5256 framesRead = bytesRead / mFrameSize;
5257 }
5258 }
5259
5260 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
5261 ALOGE("read failed: framesRead=%d", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005262 // Force input into standby so that it tries to recover at next read attempt
5263 inputStandBy();
5264 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005265 }
5266 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005267 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005268 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005269 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005270
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005271 if (mTeeSink != 0) {
5272 (void) mTeeSink->write(&mRsmpInBuffer[rear * mChannelCount], framesRead);
5273 }
5274 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005275 {
5276 size_t part1 = mRsmpInFramesP2 - rear;
5277 if ((size_t) framesRead > part1) {
5278 memcpy(mRsmpInBuffer, &mRsmpInBuffer[mRsmpInFramesP2 * mChannelCount],
5279 (framesRead - part1) * mFrameSize);
5280 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005281 }
5282 rear = mRsmpInRear += framesRead;
5283
5284 size = activeTracks.size();
5285 // loop over each active track
5286 for (size_t i = 0; i < size; i++) {
5287 activeTrack = activeTracks[i];
5288
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005289 // skip fast tracks, as those are handled directly by FastCapture
5290 if (activeTrack->isFastTrack()) {
5291 continue;
5292 }
5293
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005294 enum {
5295 OVERRUN_UNKNOWN,
5296 OVERRUN_TRUE,
5297 OVERRUN_FALSE
5298 } overrun = OVERRUN_UNKNOWN;
5299
5300 // loop over getNextBuffer to handle circular sink
5301 for (;;) {
5302
5303 activeTrack->mSink.frameCount = ~0;
5304 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
5305 size_t framesOut = activeTrack->mSink.frameCount;
5306 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
5307
5308 int32_t front = activeTrack->mRsmpInFront;
5309 ssize_t filled = rear - front;
5310 size_t framesIn;
5311
5312 if (filled < 0) {
5313 // should not happen, but treat like a massive overrun and re-sync
5314 framesIn = 0;
5315 activeTrack->mRsmpInFront = rear;
5316 overrun = OVERRUN_TRUE;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005317 } else if ((size_t) filled <= mRsmpInFrames) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005318 framesIn = (size_t) filled;
5319 } else {
5320 // client is not keeping up with server, but give it latest data
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005321 framesIn = mRsmpInFrames;
5322 activeTrack->mRsmpInFront = front = rear - framesIn;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005323 overrun = OVERRUN_TRUE;
5324 }
5325
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005326 if (framesOut == 0 || framesIn == 0) {
5327 break;
5328 }
5329
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005330 if (activeTrack->mResampler == NULL) {
5331 // no resampling
5332 if (framesIn > framesOut) {
5333 framesIn = framesOut;
5334 } else {
5335 framesOut = framesIn;
5336 }
5337 int8_t *dst = activeTrack->mSink.i8;
5338 while (framesIn > 0) {
5339 front &= mRsmpInFramesP2 - 1;
5340 size_t part1 = mRsmpInFramesP2 - front;
5341 if (part1 > framesIn) {
5342 part1 = framesIn;
5343 }
5344 int8_t *src = (int8_t *)mRsmpInBuffer + (front * mFrameSize);
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005345 if (mChannelCount == activeTrack->mChannelCount) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005346 memcpy(dst, src, part1 * mFrameSize);
5347 } else if (mChannelCount == 1) {
Glenn Kastencd704212014-07-14 17:26:36 -07005348 upmix_to_stereo_i16_from_mono_i16((int16_t *)dst, (const int16_t *)src,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005349 part1);
5350 } else {
Glenn Kastencd704212014-07-14 17:26:36 -07005351 downmix_to_mono_i16_from_stereo_i16((int16_t *)dst, (const int16_t *)src,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005352 part1);
5353 }
5354 dst += part1 * activeTrack->mFrameSize;
5355 front += part1;
5356 framesIn -= part1;
5357 }
5358 activeTrack->mRsmpInFront += framesOut;
5359
5360 } else {
5361 // resampling
5362 // FIXME framesInNeeded should really be part of resampler API, and should
5363 // depend on the SRC ratio
5364 // to keep mRsmpInBuffer full so resampler always has sufficient input
5365 size_t framesInNeeded;
5366 // FIXME only re-calculate when it changes, and optimize for common ratios
Andy Hung8661aaf2014-07-28 14:38:41 -07005367 // Do not precompute in/out because floating point is not associative
5368 // e.g. a*b/c != a*(b/c).
5369 const double in(mSampleRate);
5370 const double out(activeTrack->mSampleRate);
5371 framesInNeeded = ceil(framesOut * in / out) + 1;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005372 ALOGV("need %u frames in to produce %u out given in/out ratio of %.4g",
Andy Hung8661aaf2014-07-28 14:38:41 -07005373 framesInNeeded, framesOut, in / out);
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005374 // Although we theoretically have framesIn in circular buffer, some of those are
5375 // unreleased frames, and thus must be discounted for purpose of budgeting.
5376 size_t unreleased = activeTrack->mRsmpInUnrel;
5377 framesIn = framesIn > unreleased ? framesIn - unreleased : 0;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005378 if (framesIn < framesInNeeded) {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005379 ALOGV("not enough to resample: have %u frames in but need %u in to "
5380 "produce %u out given in/out ratio of %.4g",
Andy Hung8661aaf2014-07-28 14:38:41 -07005381 framesIn, framesInNeeded, framesOut, in / out);
5382 size_t newFramesOut = framesIn > 0 ? floor((framesIn - 1) * out / in) : 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005383 LOG_ALWAYS_FATAL_IF(newFramesOut >= framesOut);
5384 if (newFramesOut == 0) {
5385 break;
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005386 }
Andy Hung8661aaf2014-07-28 14:38:41 -07005387 framesInNeeded = ceil(newFramesOut * in / out) + 1;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005388 ALOGV("now need %u frames in to produce %u out given out/in ratio of %.4g",
Andy Hung8661aaf2014-07-28 14:38:41 -07005389 framesInNeeded, newFramesOut, out / in);
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005390 LOG_ALWAYS_FATAL_IF(framesIn < framesInNeeded);
5391 ALOGV("success 2: have %u frames in and need %u in to produce %u out "
5392 "given in/out ratio of %.4g",
Andy Hung8661aaf2014-07-28 14:38:41 -07005393 framesIn, framesInNeeded, newFramesOut, in / out);
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005394 framesOut = newFramesOut;
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005395 } else {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005396 ALOGV("success 1: have %u in and need %u in to produce %u out "
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005397 "given in/out ratio of %.4g",
Andy Hung8661aaf2014-07-28 14:38:41 -07005398 framesIn, framesInNeeded, framesOut, in / out);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005399 }
5400
5401 // reallocate mRsmpOutBuffer as needed; we will grow but never shrink
5402 if (activeTrack->mRsmpOutFrameCount < framesOut) {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005403 // FIXME why does each track need it's own mRsmpOutBuffer? can't they share?
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005404 delete[] activeTrack->mRsmpOutBuffer;
5405 // resampler always outputs stereo
5406 activeTrack->mRsmpOutBuffer = new int32_t[framesOut * FCC_2];
5407 activeTrack->mRsmpOutFrameCount = framesOut;
5408 }
5409
5410 // resampler accumulates, but we only have one source track
5411 memset(activeTrack->mRsmpOutBuffer, 0, framesOut * FCC_2 * sizeof(int32_t));
5412 activeTrack->mResampler->resample(activeTrack->mRsmpOutBuffer, framesOut,
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005413 // FIXME how about having activeTrack implement this interface itself?
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005414 activeTrack->mResamplerBufferProvider
5415 /*this*/ /* AudioBufferProvider* */);
5416 // ditherAndClamp() works as long as all buffers returned by
5417 // activeTrack->getNextBuffer() are 32 bit aligned which should be always true.
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005418 if (activeTrack->mChannelCount == 1) {
Andy Hung84a0c6e2014-04-02 11:24:53 -07005419 // temporarily type pun mRsmpOutBuffer from Q4.27 to int16_t
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005420 ditherAndClamp(activeTrack->mRsmpOutBuffer, activeTrack->mRsmpOutBuffer,
5421 framesOut);
5422 // the resampler always outputs stereo samples:
5423 // do post stereo to mono conversion
5424 downmix_to_mono_i16_from_stereo_i16(activeTrack->mSink.i16,
Glenn Kastencd704212014-07-14 17:26:36 -07005425 (const int16_t *)activeTrack->mRsmpOutBuffer, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005426 } else {
5427 ditherAndClamp((int32_t *)activeTrack->mSink.raw,
5428 activeTrack->mRsmpOutBuffer, framesOut);
5429 }
5430 // now done with mRsmpOutBuffer
5431
5432 }
5433
5434 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
5435 overrun = OVERRUN_FALSE;
5436 }
5437
5438 if (activeTrack->mFramesToDrop == 0) {
5439 if (framesOut > 0) {
5440 activeTrack->mSink.frameCount = framesOut;
5441 activeTrack->releaseBuffer(&activeTrack->mSink);
5442 }
5443 } else {
5444 // FIXME could do a partial drop of framesOut
5445 if (activeTrack->mFramesToDrop > 0) {
5446 activeTrack->mFramesToDrop -= framesOut;
5447 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005448 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005449 }
5450 } else {
5451 activeTrack->mFramesToDrop += framesOut;
5452 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
5453 activeTrack->mSyncStartEvent->isCancelled()) {
5454 ALOGW("Synced record %s, session %d, trigger session %d",
5455 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
5456 activeTrack->sessionId(),
5457 (activeTrack->mSyncStartEvent != 0) ?
5458 activeTrack->mSyncStartEvent->triggerSession() : 0);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005459 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005460 }
5461 }
5462 }
5463
5464 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005465 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005466 }
5467 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005468
5469 switch (overrun) {
5470 case OVERRUN_TRUE:
5471 // client isn't retrieving buffers fast enough
5472 if (!activeTrack->setOverflow()) {
5473 nsecs_t now = systemTime();
5474 // FIXME should lastWarning per track?
5475 if ((now - lastWarning) > kWarningThrottleNs) {
5476 ALOGW("RecordThread: buffer overflow");
5477 lastWarning = now;
5478 }
5479 }
5480 break;
5481 case OVERRUN_FALSE:
5482 activeTrack->clearOverflow();
5483 break;
5484 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005485 break;
5486 }
5487
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005488 }
5489
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005490unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08005491 // enable changes in effect chain
5492 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005493 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08005494 }
5495
Glenn Kasten93e471f2013-08-19 08:40:07 -07005496 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08005497
5498 {
5499 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07005500 for (size_t i = 0; i < mTracks.size(); i++) {
5501 sp<RecordTrack> track = mTracks[i];
5502 track->invalidate();
5503 }
Glenn Kasten2b806402013-11-20 16:37:38 -08005504 mActiveTracks.clear();
5505 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08005506 mStartStopCond.broadcast();
5507 }
5508
5509 releaseWakeLock();
5510
5511 ALOGV("RecordThread %p exiting", this);
5512 return false;
5513}
5514
Glenn Kasten93e471f2013-08-19 08:40:07 -07005515void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08005516{
5517 if (!mStandby) {
5518 inputStandBy();
5519 mStandby = true;
5520 }
5521}
5522
5523void AudioFlinger::RecordThread::inputStandBy()
5524{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005525 // Idle the fast capture if it's currently running
5526 if (mFastCapture != 0) {
5527 FastCaptureStateQueue *sq = mFastCapture->sq();
5528 FastCaptureState *state = sq->begin();
5529 if (!(state->mCommand & FastCaptureState::IDLE)) {
5530 state->mCommand = FastCaptureState::COLD_IDLE;
5531 state->mColdFutexAddr = &mFastCaptureFutex;
5532 state->mColdGen++;
5533 mFastCaptureFutex = 0;
5534 sq->end();
5535 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
5536 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
5537#if 0
5538 if (kUseFastCapture == FastCapture_Dynamic) {
5539 // FIXME
5540 }
5541#endif
5542#ifdef AUDIO_WATCHDOG
5543 // FIXME
5544#endif
5545 } else {
5546 sq->end(false /*didModify*/);
5547 }
5548 }
Eric Laurent81784c32012-11-19 14:55:58 -08005549 mInput->stream->common.standby(&mInput->stream->common);
5550}
5551
Glenn Kasten05997e22014-03-13 15:08:33 -07005552// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07005553sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08005554 const sp<AudioFlinger::Client>& client,
5555 uint32_t sampleRate,
5556 audio_format_t format,
5557 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08005558 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08005559 int sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07005560 size_t *notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005561 int uid,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07005562 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08005563 pid_t tid,
5564 status_t *status)
5565{
Glenn Kasten74935e42013-12-19 08:56:45 -08005566 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005567 sp<RecordTrack> track;
5568 status_t lStatus;
5569
Glenn Kasten90e58b12013-07-31 16:16:02 -07005570 // client expresses a preference for FAST, but we get the final say
5571 if (*flags & IAudioFlinger::TRACK_FAST) {
5572 if (
Glenn Kasten74105912014-07-03 12:28:53 -07005573 // use case: callback handler
5574 (tid != -1) &&
5575 // frame count is not specified, or is exactly the pipe depth
5576 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005577 // PCM data
5578 audio_is_linear_pcm(format) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005579 // native format
5580 (format == mFormat) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005581 // native channel mask
5582 (channelMask == mChannelMask) &&
5583 // native hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07005584 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005585 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005586 hasFastCapture() &&
5587 // there are sufficient fast track slots available
5588 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07005589 ) {
Glenn Kasten74105912014-07-03 12:28:53 -07005590 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%u mFrameCount=%u",
Glenn Kasten90e58b12013-07-31 16:16:02 -07005591 frameCount, mFrameCount);
5592 } else {
Glenn Kasten74105912014-07-03 12:28:53 -07005593 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%u mFrameCount=%u mPipeFramesP2=%u "
5594 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005595 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Glenn Kasten74105912014-07-03 12:28:53 -07005596 frameCount, mFrameCount, mPipeFramesP2,
5597 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
5598 hasFastCapture(), tid, mFastTrackAvail);
Glenn Kasten90e58b12013-07-31 16:16:02 -07005599 *flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kasten74105912014-07-03 12:28:53 -07005600 }
5601 }
5602
5603 // compute track buffer size in frames, and suggest the notification frame count
5604 if (*flags & IAudioFlinger::TRACK_FAST) {
5605 // fast track: frame count is exactly the pipe depth
5606 frameCount = mPipeFramesP2;
5607 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
5608 *notificationFrames = mFrameCount;
5609 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07005610 // not fast track: max notification period is resampled equivalent of one HAL buffer time
5611 // or 20 ms if there is a fast capture
5612 // TODO This could be a roundupRatio inline, and const
5613 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
5614 * sampleRate + mSampleRate - 1) / mSampleRate;
5615 // minimum number of notification periods is at least kMinNotifications,
5616 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
5617 static const size_t kMinNotifications = 3;
5618 static const uint32_t kMinMs = 30;
5619 // TODO This could be a roundupRatio inline
5620 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
5621 // TODO This could be a roundupRatio inline
5622 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
5623 maxNotificationFrames;
5624 const size_t minFrameCount = maxNotificationFrames *
5625 max(kMinNotifications, minNotificationsByMs);
5626 frameCount = max(frameCount, minFrameCount);
5627 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
5628 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07005629 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07005630 }
Glenn Kasten74935e42013-12-19 08:56:45 -08005631 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07005632
Glenn Kasten15e57982013-09-24 11:52:37 -07005633 lStatus = initCheck();
5634 if (lStatus != NO_ERROR) {
5635 ALOGE("createRecordTrack_l() audio driver not initialized");
5636 goto Exit;
5637 }
Eric Laurent81784c32012-11-19 14:55:58 -08005638
5639 { // scope for mLock
5640 Mutex::Autolock _l(mLock);
5641
5642 track = new RecordTrack(this, client, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07005643 format, channelMask, frameCount, NULL, sessionId, uid,
5644 *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08005645
Glenn Kasten03003332013-08-06 15:40:54 -07005646 lStatus = track->initCheck();
5647 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07005648 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08005649 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08005650 goto Exit;
5651 }
5652 mTracks.add(track);
5653
5654 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5655 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
5656 mAudioFlinger->btNrecIsOff();
5657 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
5658 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07005659
5660 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
5661 pid_t callingPid = IPCThreadState::self()->getCallingPid();
5662 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
5663 // so ask activity manager to do this on our behalf
5664 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
5665 }
Eric Laurent81784c32012-11-19 14:55:58 -08005666 }
Glenn Kasten05997e22014-03-13 15:08:33 -07005667
Eric Laurent81784c32012-11-19 14:55:58 -08005668 lStatus = NO_ERROR;
5669
5670Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07005671 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08005672 return track;
5673}
5674
5675status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
5676 AudioSystem::sync_event_t event,
5677 int triggerSession)
5678{
5679 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
5680 sp<ThreadBase> strongMe = this;
5681 status_t status = NO_ERROR;
5682
5683 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005684 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08005685 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005686 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08005687 triggerSession,
5688 recordTrack->sessionId(),
5689 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005690 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08005691 // Sync event can be cancelled by the trigger session if the track is not in a
5692 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005693 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005694 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08005695 } else {
5696 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005697 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005698 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08005699 }
5700 }
5701
5702 {
Glenn Kasten47c20702013-08-13 15:37:35 -07005703 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08005704 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005705 if (mActiveTracks.indexOf(recordTrack) >= 0) {
5706 if (recordTrack->mState == TrackBase::PAUSING) {
5707 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005708 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005709 } else {
5710 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08005711 }
5712 return status;
5713 }
5714
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005715 // TODO consider other ways of handling this, such as changing the state to :STARTING and
5716 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
5717 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005718 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08005719 mActiveTracks.add(recordTrack);
5720 mActiveTracksGen++;
Eric Laurent83b88082014-06-20 18:31:16 -07005721 status_t status = NO_ERROR;
5722 if (recordTrack->isExternalTrack()) {
5723 mLock.unlock();
Eric Laurent4dc68062014-07-28 17:26:49 -07005724 status = AudioSystem::startInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07005725 mLock.lock();
5726 // FIXME should verify that recordTrack is still in mActiveTracks
5727 if (status != NO_ERROR) {
5728 mActiveTracks.remove(recordTrack);
5729 mActiveTracksGen++;
5730 recordTrack->clearSyncStartEvent();
5731 ALOGV("RecordThread::start error %d", status);
5732 return status;
5733 }
Eric Laurent81784c32012-11-19 14:55:58 -08005734 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005735 // Catch up with current buffer indices if thread is already running.
5736 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
5737 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
5738 // see previously buffered data before it called start(), but with greater risk of overrun.
5739
5740 recordTrack->mRsmpInFront = mRsmpInRear;
5741 recordTrack->mRsmpInUnrel = 0;
5742 // FIXME why reset?
5743 if (recordTrack->mResampler != NULL) {
5744 recordTrack->mResampler->reset();
Eric Laurent81784c32012-11-19 14:55:58 -08005745 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005746 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08005747 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08005748 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08005749 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005750 ALOGV("Record failed to start");
5751 status = BAD_VALUE;
5752 goto startError;
5753 }
Eric Laurent81784c32012-11-19 14:55:58 -08005754 return status;
5755 }
Glenn Kasten7c027242012-12-26 14:43:16 -08005756
Eric Laurent81784c32012-11-19 14:55:58 -08005757startError:
Eric Laurent83b88082014-06-20 18:31:16 -07005758 if (recordTrack->isExternalTrack()) {
Eric Laurent4dc68062014-07-28 17:26:49 -07005759 AudioSystem::stopInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07005760 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005761 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005762 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08005763 return status;
5764}
5765
Eric Laurent81784c32012-11-19 14:55:58 -08005766void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
5767{
5768 sp<SyncEvent> strongEvent = event.promote();
5769
5770 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08005771 sp<RefBase> ptr = strongEvent->cookie().promote();
5772 if (ptr != 0) {
5773 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
5774 recordTrack->handleSyncStartEvent(strongEvent);
5775 }
Eric Laurent81784c32012-11-19 14:55:58 -08005776 }
5777}
5778
Glenn Kastena8356f62013-07-25 14:37:52 -07005779bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08005780 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07005781 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005782 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08005783 return false;
5784 }
Glenn Kasten47c20702013-08-13 15:37:35 -07005785 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08005786 recordTrack->mState = TrackBase::PAUSING;
5787 // do not wait for mStartStopCond if exiting
5788 if (exitPending()) {
5789 return true;
5790 }
Glenn Kasten47c20702013-08-13 15:37:35 -07005791 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08005792 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005793 // if we have been restarted, recordTrack is in mActiveTracks here
5794 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005795 ALOGV("Record stopped OK");
5796 return true;
5797 }
5798 return false;
5799}
5800
Glenn Kasten0f11b512014-01-31 16:18:54 -08005801bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08005802{
5803 return false;
5804}
5805
Glenn Kasten0f11b512014-01-31 16:18:54 -08005806status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005807{
5808#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
5809 if (!isValidSyncEvent(event)) {
5810 return BAD_VALUE;
5811 }
5812
5813 int eventSession = event->triggerSession();
5814 status_t ret = NAME_NOT_FOUND;
5815
5816 Mutex::Autolock _l(mLock);
5817
5818 for (size_t i = 0; i < mTracks.size(); i++) {
5819 sp<RecordTrack> track = mTracks[i];
5820 if (eventSession == track->sessionId()) {
5821 (void) track->setSyncEvent(event);
5822 ret = NO_ERROR;
5823 }
5824 }
5825 return ret;
5826#else
5827 return BAD_VALUE;
5828#endif
5829}
5830
5831// destroyTrack_l() must be called with ThreadBase::mLock held
5832void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
5833{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005834 track->terminate();
5835 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08005836 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08005837 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005838 removeTrack_l(track);
5839 }
5840}
5841
5842void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
5843{
5844 mTracks.remove(track);
5845 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005846 if (track->isFastTrack()) {
5847 ALOG_ASSERT(!mFastTrackAvail);
5848 mFastTrackAvail = true;
5849 }
Eric Laurent81784c32012-11-19 14:55:58 -08005850}
5851
5852void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
5853{
5854 dumpInternals(fd, args);
5855 dumpTracks(fd, args);
5856 dumpEffectChains(fd, args);
5857}
5858
5859void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
5860{
Elliott Hughes87cebad2014-05-22 10:14:43 -07005861 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08005862
Glenn Kasten2b806402013-11-20 16:37:38 -08005863 if (mActiveTracks.size() > 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07005864 dprintf(fd, " Buffer size: %zu bytes\n", mBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005865 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07005866 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08005867 }
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005868 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005869 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Eric Laurent81784c32012-11-19 14:55:58 -08005870
Eric Laurent81784c32012-11-19 14:55:58 -08005871 dumpBase(fd, args);
5872}
5873
Glenn Kasten0f11b512014-01-31 16:18:54 -08005874void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005875{
5876 const size_t SIZE = 256;
5877 char buffer[SIZE];
5878 String8 result;
5879
Marco Nelissenb2208842014-02-07 14:00:50 -08005880 size_t numtracks = mTracks.size();
5881 size_t numactive = mActiveTracks.size();
5882 size_t numactiveseen = 0;
Elliott Hughes87cebad2014-05-22 10:14:43 -07005883 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08005884 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07005885 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08005886 RecordTrack::appendDumpHeader(result);
5887 for (size_t i = 0; i < numtracks ; ++i) {
5888 sp<RecordTrack> track = mTracks[i];
5889 if (track != 0) {
5890 bool active = mActiveTracks.indexOf(track) >= 0;
5891 if (active) {
5892 numactiveseen++;
5893 }
5894 track->dump(buffer, SIZE, active);
5895 result.append(buffer);
5896 }
Eric Laurent81784c32012-11-19 14:55:58 -08005897 }
Marco Nelissenb2208842014-02-07 14:00:50 -08005898 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07005899 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08005900 }
5901
Marco Nelissenb2208842014-02-07 14:00:50 -08005902 if (numactiveseen != numactive) {
5903 snprintf(buffer, SIZE, " The following tracks are in the active list but"
5904 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08005905 result.append(buffer);
5906 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08005907 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08005908 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08005909 if (mTracks.indexOf(track) < 0) {
5910 track->dump(buffer, SIZE, true);
5911 result.append(buffer);
5912 }
Glenn Kasten2b806402013-11-20 16:37:38 -08005913 }
Eric Laurent81784c32012-11-19 14:55:58 -08005914
5915 }
5916 write(fd, result.string(), result.size());
5917}
5918
5919// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005920status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
5921 AudioBufferProvider::Buffer* buffer, int64_t pts __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005922{
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005923 RecordTrack *activeTrack = mRecordTrack;
5924 sp<ThreadBase> threadBase = activeTrack->mThread.promote();
5925 if (threadBase == 0) {
5926 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005927 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005928 return NOT_ENOUGH_DATA;
5929 }
5930 RecordThread *recordThread = (RecordThread *) threadBase.get();
5931 int32_t rear = recordThread->mRsmpInRear;
5932 int32_t front = activeTrack->mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07005933 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005934 // FIXME should not be P2 (don't want to increase latency)
5935 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005936 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07005937 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005938 front &= recordThread->mRsmpInFramesP2 - 1;
5939 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07005940 if (part1 > (size_t) filled) {
5941 part1 = filled;
5942 }
5943 size_t ask = buffer->frameCount;
5944 ALOG_ASSERT(ask > 0);
5945 if (part1 > ask) {
5946 part1 = ask;
5947 }
5948 if (part1 == 0) {
5949 // Higher-level should keep mRsmpInBuffer full, and not call resampler if empty
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005950 LOG_ALWAYS_FATAL("RecordThread::getNextBuffer() starved");
Glenn Kasten85948432013-08-19 12:09:05 -07005951 buffer->raw = NULL;
5952 buffer->frameCount = 0;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005953 activeTrack->mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07005954 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08005955 }
5956
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005957 buffer->raw = recordThread->mRsmpInBuffer + front * recordThread->mChannelCount;
Glenn Kasten85948432013-08-19 12:09:05 -07005958 buffer->frameCount = part1;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005959 activeTrack->mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08005960 return NO_ERROR;
5961}
5962
5963// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005964void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
5965 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08005966{
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005967 RecordTrack *activeTrack = mRecordTrack;
Glenn Kasten85948432013-08-19 12:09:05 -07005968 size_t stepCount = buffer->frameCount;
5969 if (stepCount == 0) {
5970 return;
5971 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005972 ALOG_ASSERT(stepCount <= activeTrack->mRsmpInUnrel);
5973 activeTrack->mRsmpInUnrel -= stepCount;
5974 activeTrack->mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07005975 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08005976 buffer->frameCount = 0;
5977}
5978
Eric Laurent10351942014-05-08 18:49:52 -07005979bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
5980 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005981{
5982 bool reconfig = false;
5983
Eric Laurent10351942014-05-08 18:49:52 -07005984 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005985
Eric Laurent10351942014-05-08 18:49:52 -07005986 audio_format_t reqFormat = mFormat;
5987 uint32_t samplingRate = mSampleRate;
5988 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
5989
5990 AudioParameter param = AudioParameter(keyValuePair);
5991 int value;
5992 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
5993 // channel count change can be requested. Do we mandate the first client defines the
5994 // HAL sampling rate and channel count or do we allow changes on the fly?
5995 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5996 samplingRate = value;
5997 reconfig = true;
5998 }
5999 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
6000 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
6001 status = BAD_VALUE;
6002 } else {
6003 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08006004 reconfig = true;
6005 }
Eric Laurent10351942014-05-08 18:49:52 -07006006 }
6007 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
6008 audio_channel_mask_t mask = (audio_channel_mask_t) value;
6009 if (mask != AUDIO_CHANNEL_IN_MONO && mask != AUDIO_CHANNEL_IN_STEREO) {
6010 status = BAD_VALUE;
6011 } else {
6012 channelMask = mask;
6013 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006014 }
Eric Laurent10351942014-05-08 18:49:52 -07006015 }
6016 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6017 // do not accept frame count changes if tracks are open as the track buffer
6018 // size depends on frame count and correct behavior would not be guaranteed
6019 // if frame count is changed after track creation
6020 if (mActiveTracks.size() > 0) {
6021 status = INVALID_OPERATION;
6022 } else {
6023 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006024 }
Eric Laurent10351942014-05-08 18:49:52 -07006025 }
6026 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6027 // forward device change to effects that have requested to be
6028 // aware of attached audio device.
6029 for (size_t i = 0; i < mEffectChains.size(); i++) {
6030 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08006031 }
Eric Laurent81784c32012-11-19 14:55:58 -08006032
Eric Laurent10351942014-05-08 18:49:52 -07006033 // store input device and output device but do not forward output device to audio HAL.
6034 // Note that status is ignored by the caller for output device
6035 // (see AudioFlinger::setParameters()
6036 if (audio_is_output_devices(value)) {
6037 mOutDevice = value;
6038 status = BAD_VALUE;
6039 } else {
6040 mInDevice = value;
6041 // disable AEC and NS if the device is a BT SCO headset supporting those
6042 // pre processings
6043 if (mTracks.size() > 0) {
6044 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6045 mAudioFlinger->btNrecIsOff();
6046 for (size_t i = 0; i < mTracks.size(); i++) {
6047 sp<RecordTrack> track = mTracks[i];
6048 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
6049 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08006050 }
6051 }
6052 }
Eric Laurent10351942014-05-08 18:49:52 -07006053 }
6054 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
6055 mAudioSource != (audio_source_t)value) {
6056 // forward device change to effects that have requested to be
6057 // aware of attached audio device.
6058 for (size_t i = 0; i < mEffectChains.size(); i++) {
6059 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08006060 }
Eric Laurent10351942014-05-08 18:49:52 -07006061 mAudioSource = (audio_source_t)value;
6062 }
Glenn Kastene198c362013-08-13 09:13:36 -07006063
Eric Laurent10351942014-05-08 18:49:52 -07006064 if (status == NO_ERROR) {
6065 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6066 keyValuePair.string());
6067 if (status == INVALID_OPERATION) {
6068 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006069 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6070 keyValuePair.string());
Eric Laurent10351942014-05-08 18:49:52 -07006071 }
6072 if (reconfig) {
6073 if (status == BAD_VALUE &&
6074 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
6075 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
6076 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
6077 <= (2 * samplingRate)) &&
Andy Hunge5412692014-05-16 11:25:07 -07006078 audio_channel_count_from_in_mask(
6079 mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
Eric Laurent10351942014-05-08 18:49:52 -07006080 (channelMask == AUDIO_CHANNEL_IN_MONO ||
6081 channelMask == AUDIO_CHANNEL_IN_STEREO)) {
6082 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006083 }
Eric Laurent10351942014-05-08 18:49:52 -07006084 if (status == NO_ERROR) {
6085 readInputParameters_l();
6086 sendIoConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08006087 }
6088 }
Eric Laurent81784c32012-11-19 14:55:58 -08006089 }
Eric Laurent10351942014-05-08 18:49:52 -07006090
Eric Laurent81784c32012-11-19 14:55:58 -08006091 return reconfig;
6092}
6093
6094String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6095{
Eric Laurent81784c32012-11-19 14:55:58 -08006096 Mutex::Autolock _l(mLock);
6097 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07006098 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08006099 }
6100
Glenn Kastend8ea6992013-07-16 14:17:15 -07006101 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
6102 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08006103 free(s);
6104 return out_s8;
6105}
6106
Eric Laurent021cf962014-05-13 10:18:14 -07006107void AudioFlinger::RecordThread::audioConfigChanged(int event, int param __unused) {
Eric Laurent81784c32012-11-19 14:55:58 -08006108 AudioSystem::OutputDescriptor desc;
Glenn Kastenb2737d02013-08-19 12:03:11 -07006109 const void *param2 = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006110
6111 switch (event) {
6112 case AudioSystem::INPUT_OPENED:
6113 case AudioSystem::INPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07006114 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08006115 desc.samplingRate = mSampleRate;
6116 desc.format = mFormat;
6117 desc.frameCount = mFrameCount;
6118 desc.latency = 0;
6119 param2 = &desc;
6120 break;
6121
6122 case AudioSystem::INPUT_CLOSED:
6123 default:
6124 break;
6125 }
Eric Laurent021cf962014-05-13 10:18:14 -07006126 mAudioFlinger->audioConfigChanged(event, mId, param2);
Eric Laurent81784c32012-11-19 14:55:58 -08006127}
6128
Glenn Kastendeca2ae2014-02-07 10:25:56 -08006129void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006130{
Eric Laurent81784c32012-11-19 14:55:58 -08006131 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
6132 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Andy Hunge5412692014-05-16 11:25:07 -07006133 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Andy Hung463be252014-07-10 16:56:07 -07006134 mHALFormat = mInput->stream->common.get_format(&mInput->stream->common);
6135 mFormat = mHALFormat;
Glenn Kasten291bb6d2013-07-16 17:23:39 -07006136 if (mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08006137 ALOGE("HAL format %#x not supported; must be AUDIO_FORMAT_PCM_16_BIT", mFormat);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07006138 }
Eric Laurent665470b2014-07-03 16:37:08 -07006139 mFrameSize = audio_stream_in_frame_size(mInput->stream);
Glenn Kasten548efc92012-11-29 08:48:51 -08006140 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
6141 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006142 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08006143 // 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 -07006144 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08006145 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006146 // A larger value should allow more old data to be read after a track calls start(),
6147 // without increasing latency.
Glenn Kastene8426142014-02-28 16:45:03 -08006148 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07006149 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006150 delete[] mRsmpInBuffer;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006151
6152 // TODO optimize audio capture buffer sizes ...
6153 // Here we calculate the size of the sliding buffer used as a source
6154 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
6155 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
6156 // be better to have it derived from the pipe depth in the long term.
6157 // The current value is higher than necessary. However it should not add to latency.
6158
Glenn Kasten85948432013-08-19 12:09:05 -07006159 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Andy Hung8c987fa2015-09-24 16:36:56 -07006160 size_t bufferSizeInShorts = (mRsmpInFramesP2 + mFrameCount - 1) * mChannelCount;
6161 mRsmpInBuffer = new int16_t[bufferSizeInShorts];
6162 memset(mRsmpInBuffer, 0, bufferSizeInShorts * sizeof(mRsmpInBuffer[0]));
Eric Laurent81784c32012-11-19 14:55:58 -08006163
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006164 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
6165 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08006166}
6167
Glenn Kasten5f972c02014-01-13 09:59:31 -08006168uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08006169{
6170 Mutex::Autolock _l(mLock);
6171 if (initCheck() != NO_ERROR) {
6172 return 0;
6173 }
6174
6175 return mInput->stream->get_input_frames_lost(mInput->stream);
6176}
6177
6178uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
6179{
6180 Mutex::Autolock _l(mLock);
6181 uint32_t result = 0;
6182 if (getEffectChain_l(sessionId) != 0) {
6183 result = EFFECT_SESSION;
6184 }
6185
6186 for (size_t i = 0; i < mTracks.size(); ++i) {
6187 if (sessionId == mTracks[i]->sessionId()) {
6188 result |= TRACK_SESSION;
6189 break;
6190 }
6191 }
6192
6193 return result;
6194}
6195
6196KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
6197{
6198 KeyedVector<int, bool> ids;
6199 Mutex::Autolock _l(mLock);
6200 for (size_t j = 0; j < mTracks.size(); ++j) {
6201 sp<RecordThread::RecordTrack> track = mTracks[j];
6202 int sessionId = track->sessionId();
6203 if (ids.indexOfKey(sessionId) < 0) {
6204 ids.add(sessionId, true);
6205 }
6206 }
6207 return ids;
6208}
6209
6210AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
6211{
6212 Mutex::Autolock _l(mLock);
6213 AudioStreamIn *input = mInput;
6214 mInput = NULL;
6215 return input;
6216}
6217
6218// this method must always be called either with ThreadBase mLock held or inside the thread loop
6219audio_stream_t* AudioFlinger::RecordThread::stream() const
6220{
6221 if (mInput == NULL) {
6222 return NULL;
6223 }
6224 return &mInput->stream->common;
6225}
6226
6227status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6228{
6229 // only one chain per input thread
6230 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07006231 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08006232 return INVALID_OPERATION;
6233 }
6234 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07006235 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08006236 chain->setInBuffer(NULL);
6237 chain->setOutBuffer(NULL);
6238
6239 checkSuspendOnAddEffectChain_l(chain);
6240
Eric Laurent1b928682014-10-02 19:41:47 -07006241 // make sure enabled pre processing effects state is communicated to the HAL as we
6242 // just moved them to a new input stream.
6243 chain->syncHalEffectsState();
6244
Eric Laurent81784c32012-11-19 14:55:58 -08006245 mEffectChains.add(chain);
6246
6247 return NO_ERROR;
6248}
6249
6250size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6251{
6252 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
6253 ALOGW_IF(mEffectChains.size() != 1,
6254 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6255 chain.get(), mEffectChains.size(), this);
6256 if (mEffectChains.size() == 1) {
6257 mEffectChains.removeAt(0);
6258 }
6259 return 0;
6260}
6261
Eric Laurent1c333e22014-05-20 10:48:17 -07006262status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
6263 audio_patch_handle_t *handle)
6264{
6265 status_t status = NO_ERROR;
6266 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
6267 // store new device and send to effects
6268 mInDevice = patch->sources[0].ext.device.type;
6269 for (size_t i = 0; i < mEffectChains.size(); i++) {
6270 mEffectChains[i]->setDevice_l(mInDevice);
6271 }
6272
6273 // disable AEC and NS if the device is a BT SCO headset supporting those
6274 // pre processings
6275 if (mTracks.size() > 0) {
6276 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6277 mAudioFlinger->btNrecIsOff();
6278 for (size_t i = 0; i < mTracks.size(); i++) {
6279 sp<RecordTrack> track = mTracks[i];
6280 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
6281 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
6282 }
6283 }
6284
6285 // store new source and send to effects
6286 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
6287 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
6288 for (size_t i = 0; i < mEffectChains.size(); i++) {
6289 mEffectChains[i]->setAudioSource_l(mAudioSource);
6290 }
6291 }
6292
6293 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
6294 status = hwDevice->create_audio_patch(hwDevice,
6295 patch->num_sources,
6296 patch->sources,
6297 patch->num_sinks,
6298 patch->sinks,
6299 handle);
6300 } else {
6301 ALOG_ASSERT(false, "createAudioPatch_l() called on a pre 3.0 HAL");
6302 }
6303 return status;
6304}
6305
6306status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
6307{
6308 status_t status = NO_ERROR;
6309 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
6310 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
6311 status = hwDevice->release_audio_patch(hwDevice, handle);
6312 } else {
6313 ALOG_ASSERT(false, "releaseAudioPatch_l() called on a pre 3.0 HAL");
6314 }
6315 return status;
6316}
6317
Eric Laurent83b88082014-06-20 18:31:16 -07006318void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
6319{
6320 Mutex::Autolock _l(mLock);
6321 mTracks.add(record);
6322}
6323
6324void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
6325{
6326 Mutex::Autolock _l(mLock);
6327 destroyTrack_l(record);
6328}
6329
6330void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
6331{
6332 ThreadBase::getAudioPortConfig(config);
6333 config->role = AUDIO_PORT_ROLE_SINK;
6334 config->ext.mix.hw_module = mInput->audioHwDev->handle();
6335 config->ext.mix.usecase.source = mAudioSource;
6336}
Eric Laurent1c333e22014-05-20 10:48:17 -07006337
Eric Laurent81784c32012-11-19 14:55:58 -08006338}; // namespace android