blob: 792419f3e6bdcd2c1a29b13065081ee1540d98d2 [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,
Glenn Kasten9156ef32013-08-06 15:39:08 -0700895 status_t *status)
Eric Laurent81784c32012-11-19 14:55:58 -0800896{
897 sp<EffectModule> effect;
898 sp<EffectHandle> handle;
899 status_t lStatus;
900 sp<EffectChain> chain;
901 bool chainCreated = false;
902 bool effectCreated = false;
903 bool effectRegistered = false;
904
905 lStatus = initCheck();
906 if (lStatus != NO_ERROR) {
907 ALOGW("createEffect_l() Audio driver not initialized.");
908 goto Exit;
909 }
910
Andy Hung98ef9782014-03-04 14:46:50 -0800911 // Reject any effect on Direct output threads for now, since the format of
912 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
913 if (mType == DIRECT) {
914 ALOGW("createEffect_l() Cannot add effect %s on Direct output type thread %s",
915 desc->name, mName);
916 lStatus = BAD_VALUE;
917 goto Exit;
918 }
919
Andy Hung389cfdb2014-08-07 17:49:53 -0700920 // Reject any effect on mixer or duplicating multichannel sinks.
Andy Hung9a592762014-07-21 21:56:01 -0700921 // TODO: fix both format and multichannel issues with effects.
Andy Hung389cfdb2014-08-07 17:49:53 -0700922 if ((mType == MIXER || mType == DUPLICATING) && mChannelCount != FCC_2) {
923 ALOGW("createEffect_l() Cannot add effect %s for multichannel(%d) %s threads",
924 desc->name, mChannelCount, mType == MIXER ? "MIXER" : "DUPLICATING");
Andy Hung9a592762014-07-21 21:56:01 -0700925 lStatus = BAD_VALUE;
926 goto Exit;
927 }
928
Eric Laurent5baf2af2013-09-12 17:37:00 -0700929 // Allow global effects only on offloaded and mixer threads
930 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
931 switch (mType) {
932 case MIXER:
933 case OFFLOAD:
934 break;
935 case DIRECT:
936 case DUPLICATING:
937 case RECORD:
938 default:
939 ALOGW("createEffect_l() Cannot add global effect %s on thread %s", desc->name, mName);
940 lStatus = BAD_VALUE;
941 goto Exit;
942 }
Eric Laurent81784c32012-11-19 14:55:58 -0800943 }
Eric Laurent5baf2af2013-09-12 17:37:00 -0700944
Eric Laurent81784c32012-11-19 14:55:58 -0800945 // Only Pre processor effects are allowed on input threads and only on input threads
946 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
947 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
948 desc->name, desc->flags, mType);
949 lStatus = BAD_VALUE;
950 goto Exit;
951 }
952
953 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
954
955 { // scope for mLock
956 Mutex::Autolock _l(mLock);
957
958 // check for existing effect chain with the requested audio session
959 chain = getEffectChain_l(sessionId);
960 if (chain == 0) {
961 // create a new chain for this session
962 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
963 chain = new EffectChain(this, sessionId);
964 addEffectChain_l(chain);
965 chain->setStrategy(getStrategyForSession_l(sessionId));
966 chainCreated = true;
967 } else {
968 effect = chain->getEffectFromDesc_l(desc);
969 }
970
971 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
972
973 if (effect == 0) {
974 int id = mAudioFlinger->nextUniqueId();
975 // Check CPU and memory usage
976 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
977 if (lStatus != NO_ERROR) {
978 goto Exit;
979 }
980 effectRegistered = true;
981 // create a new effect module if none present in the chain
982 effect = new EffectModule(this, chain, desc, id, sessionId);
983 lStatus = effect->status();
984 if (lStatus != NO_ERROR) {
985 goto Exit;
986 }
Eric Laurent5baf2af2013-09-12 17:37:00 -0700987 effect->setOffloaded(mType == OFFLOAD, mId);
988
Eric Laurent81784c32012-11-19 14:55:58 -0800989 lStatus = chain->addEffect_l(effect);
990 if (lStatus != NO_ERROR) {
991 goto Exit;
992 }
993 effectCreated = true;
994
995 effect->setDevice(mOutDevice);
996 effect->setDevice(mInDevice);
997 effect->setMode(mAudioFlinger->getMode());
998 effect->setAudioSource(mAudioSource);
999 }
1000 // create effect handle and connect it to effect module
1001 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001002 lStatus = handle->initCheck();
1003 if (lStatus == OK) {
1004 lStatus = effect->addHandle(handle.get());
1005 }
Eric Laurent81784c32012-11-19 14:55:58 -08001006 if (enabled != NULL) {
1007 *enabled = (int)effect->isEnabled();
1008 }
1009 }
1010
1011Exit:
1012 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1013 Mutex::Autolock _l(mLock);
1014 if (effectCreated) {
1015 chain->removeEffect_l(effect);
1016 }
1017 if (effectRegistered) {
1018 AudioSystem::unregisterEffect(effect->id());
1019 }
1020 if (chainCreated) {
1021 removeEffectChain_l(chain);
1022 }
1023 handle.clear();
1024 }
1025
Glenn Kasten9156ef32013-08-06 15:39:08 -07001026 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001027 return handle;
1028}
1029
1030sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
1031{
1032 Mutex::Autolock _l(mLock);
1033 return getEffect_l(sessionId, effectId);
1034}
1035
1036sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
1037{
1038 sp<EffectChain> chain = getEffectChain_l(sessionId);
1039 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1040}
1041
1042// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1043// PlaybackThread::mLock held
1044status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1045{
1046 // check for existing effect chain with the requested audio session
1047 int sessionId = effect->sessionId();
1048 sp<EffectChain> chain = getEffectChain_l(sessionId);
1049 bool chainCreated = false;
1050
Eric Laurent5baf2af2013-09-12 17:37:00 -07001051 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
1052 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
1053 this, effect->desc().name, effect->desc().flags);
1054
Eric Laurent81784c32012-11-19 14:55:58 -08001055 if (chain == 0) {
1056 // create a new chain for this session
1057 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1058 chain = new EffectChain(this, sessionId);
1059 addEffectChain_l(chain);
1060 chain->setStrategy(getStrategyForSession_l(sessionId));
1061 chainCreated = true;
1062 }
1063 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1064
1065 if (chain->getEffectFromId_l(effect->id()) != 0) {
1066 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1067 this, effect->desc().name, chain.get());
1068 return BAD_VALUE;
1069 }
1070
Eric Laurent5baf2af2013-09-12 17:37:00 -07001071 effect->setOffloaded(mType == OFFLOAD, mId);
1072
Eric Laurent81784c32012-11-19 14:55:58 -08001073 status_t status = chain->addEffect_l(effect);
1074 if (status != NO_ERROR) {
1075 if (chainCreated) {
1076 removeEffectChain_l(chain);
1077 }
1078 return status;
1079 }
1080
1081 effect->setDevice(mOutDevice);
1082 effect->setDevice(mInDevice);
1083 effect->setMode(mAudioFlinger->getMode());
1084 effect->setAudioSource(mAudioSource);
1085 return NO_ERROR;
1086}
1087
1088void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
1089
1090 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
1091 effect_descriptor_t desc = effect->desc();
1092 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1093 detachAuxEffect_l(effect->id());
1094 }
1095
1096 sp<EffectChain> chain = effect->chain().promote();
1097 if (chain != 0) {
1098 // remove effect chain if removing last effect
1099 if (chain->removeEffect_l(effect) == 0) {
1100 removeEffectChain_l(chain);
1101 }
1102 } else {
1103 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1104 }
1105}
1106
1107void AudioFlinger::ThreadBase::lockEffectChains_l(
1108 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1109{
1110 effectChains = mEffectChains;
1111 for (size_t i = 0; i < mEffectChains.size(); i++) {
1112 mEffectChains[i]->lock();
1113 }
1114}
1115
1116void AudioFlinger::ThreadBase::unlockEffectChains(
1117 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1118{
1119 for (size_t i = 0; i < effectChains.size(); i++) {
1120 effectChains[i]->unlock();
1121 }
1122}
1123
1124sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
1125{
1126 Mutex::Autolock _l(mLock);
1127 return getEffectChain_l(sessionId);
1128}
1129
1130sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const
1131{
1132 size_t size = mEffectChains.size();
1133 for (size_t i = 0; i < size; i++) {
1134 if (mEffectChains[i]->sessionId() == sessionId) {
1135 return mEffectChains[i];
1136 }
1137 }
1138 return 0;
1139}
1140
1141void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1142{
1143 Mutex::Autolock _l(mLock);
1144 size_t size = mEffectChains.size();
1145 for (size_t i = 0; i < size; i++) {
1146 mEffectChains[i]->setMode_l(mode);
1147 }
1148}
1149
Eric Laurent83b88082014-06-20 18:31:16 -07001150void AudioFlinger::ThreadBase::getAudioPortConfig(struct audio_port_config *config)
1151{
1152 config->type = AUDIO_PORT_TYPE_MIX;
1153 config->ext.mix.handle = mId;
1154 config->sample_rate = mSampleRate;
1155 config->format = mFormat;
1156 config->channel_mask = mChannelMask;
1157 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1158 AUDIO_PORT_CONFIG_FORMAT;
1159}
1160
1161
Eric Laurent81784c32012-11-19 14:55:58 -08001162// ----------------------------------------------------------------------------
1163// Playback
1164// ----------------------------------------------------------------------------
1165
1166AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1167 AudioStreamOut* output,
1168 audio_io_handle_t id,
1169 audio_devices_t device,
1170 type_t type)
1171 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type),
Andy Hung2098f272014-02-27 14:00:06 -08001172 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001173 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001174 mMixerBuffer(NULL),
1175 mMixerBufferSize(0),
1176 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1177 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001178 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001179 mEffectBuffer(NULL),
1180 mEffectBufferSize(0),
1181 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1182 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001183 mSuspended(0), mBytesWritten(0),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001184 mActiveTracksGeneration(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001185 // mStreamTypes[] initialized in constructor body
1186 mOutput(output),
1187 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
1188 mMixerStatus(MIXER_IDLE),
1189 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
1190 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001191 mBytesRemaining(0),
1192 mCurrentWriteLength(0),
1193 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001194 mWriteAckSequence(0),
1195 mDrainSequence(0),
Eric Laurentede6c3b2013-09-19 14:37:46 -07001196 mSignalPending(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001197 mScreenState(AudioFlinger::mScreenState),
1198 // index 0 is reserved for normal mixer's submix
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001199 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1),
1200 // mLatchD, mLatchQ,
1201 mLatchDValid(false), mLatchQValid(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001202{
1203 snprintf(mName, kNameLength, "AudioOut_%X", id);
Glenn Kasten9e58b552013-01-18 15:09:48 -08001204 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mName);
Eric Laurent81784c32012-11-19 14:55:58 -08001205
1206 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1207 // it would be safer to explicitly pass initial masterVolume/masterMute as
1208 // parameter.
1209 //
1210 // If the HAL we are using has support for master volume or master mute,
1211 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1212 // and the mute set to false).
1213 mMasterVolume = audioFlinger->masterVolume_l();
1214 mMasterMute = audioFlinger->masterMute_l();
1215 if (mOutput && mOutput->audioHwDev) {
1216 if (mOutput->audioHwDev->canSetMasterVolume()) {
1217 mMasterVolume = 1.0;
1218 }
1219
1220 if (mOutput->audioHwDev->canSetMasterMute()) {
1221 mMasterMute = false;
1222 }
1223 }
1224
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001225 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001226
Eric Laurent223fd5c2014-11-11 13:43:36 -08001227 // ++ operator does not compile
Glenn Kasten66e46352014-01-16 17:44:23 -08001228 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001229 stream = (audio_stream_type_t) (stream + 1)) {
1230 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1231 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1232 }
Eric Laurent81784c32012-11-19 14:55:58 -08001233}
1234
1235AudioFlinger::PlaybackThread::~PlaybackThread()
1236{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001237 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001238 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001239 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001240 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001241}
1242
1243void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1244{
1245 dumpInternals(fd, args);
1246 dumpTracks(fd, args);
1247 dumpEffectChains(fd, args);
1248}
1249
Glenn Kasten0f11b512014-01-31 16:18:54 -08001250void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001251{
1252 const size_t SIZE = 256;
1253 char buffer[SIZE];
1254 String8 result;
1255
Marco Nelissenb2208842014-02-07 14:00:50 -08001256 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001257 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1258 const stream_type_t *st = &mStreamTypes[i];
1259 if (i > 0) {
1260 result.appendFormat(", ");
1261 }
1262 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1263 if (st->mute) {
1264 result.append("M");
1265 }
1266 }
1267 result.append("\n");
1268 write(fd, result.string(), result.length());
1269 result.clear();
1270
Eric Laurent81784c32012-11-19 14:55:58 -08001271 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1272 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001273 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001274 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001275
1276 size_t numtracks = mTracks.size();
1277 size_t numactive = mActiveTracks.size();
Elliott Hughes87cebad2014-05-22 10:14:43 -07001278 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001279 size_t numactiveseen = 0;
1280 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07001281 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08001282 Track::appendDumpHeader(result);
1283 for (size_t i = 0; i < numtracks; ++i) {
1284 sp<Track> track = mTracks[i];
1285 if (track != 0) {
1286 bool active = mActiveTracks.indexOf(track) >= 0;
1287 if (active) {
1288 numactiveseen++;
1289 }
1290 track->dump(buffer, SIZE, active);
1291 result.append(buffer);
1292 }
1293 }
1294 } else {
1295 result.append("\n");
1296 }
1297 if (numactiveseen != numactive) {
1298 // some tracks in the active list were not in the tracks list
1299 snprintf(buffer, SIZE, " The following tracks are in the active list but"
1300 " not in the track list\n");
1301 result.append(buffer);
1302 Track::appendDumpHeader(result);
1303 for (size_t i = 0; i < numactive; ++i) {
1304 sp<Track> track = mActiveTracks[i].promote();
1305 if (track != 0 && mTracks.indexOf(track) < 0) {
1306 track->dump(buffer, SIZE, true);
1307 result.append(buffer);
1308 }
1309 }
1310 }
1311
1312 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001313}
1314
1315void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1316{
Elliott Hughes87cebad2014-05-22 10:14:43 -07001317 dprintf(fd, "\nOutput thread %p:\n", this);
1318 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
1319 dprintf(fd, " Last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1320 dprintf(fd, " Total writes: %d\n", mNumWrites);
1321 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1322 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1323 dprintf(fd, " Suspend count: %d\n", mSuspended);
1324 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1325 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1326 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1327 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent81784c32012-11-19 14:55:58 -08001328
1329 dumpBase(fd, args);
1330}
1331
1332// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001333
1334void AudioFlinger::PlaybackThread::onFirstRef()
1335{
1336 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
1337}
1338
1339// ThreadBase virtuals
1340void AudioFlinger::PlaybackThread::preExit()
1341{
1342 ALOGV(" preExit()");
1343 // FIXME this is using hard-coded strings but in the future, this functionality will be
1344 // converted to use audio HAL extensions required to support tunneling
1345 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1346}
1347
1348// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1349sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1350 const sp<AudioFlinger::Client>& client,
1351 audio_stream_type_t streamType,
1352 uint32_t sampleRate,
1353 audio_format_t format,
1354 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001355 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001356 const sp<IMemory>& sharedBuffer,
1357 int sessionId,
1358 IAudioFlinger::track_flags_t *flags,
1359 pid_t tid,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001360 int uid,
Eric Laurent81784c32012-11-19 14:55:58 -08001361 status_t *status)
1362{
Glenn Kasten74935e42013-12-19 08:56:45 -08001363 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001364 sp<Track> track;
1365 status_t lStatus;
1366
1367 bool isTimed = (*flags & IAudioFlinger::TRACK_TIMED) != 0;
1368
1369 // client expresses a preference for FAST, but we get the final say
1370 if (*flags & IAudioFlinger::TRACK_FAST) {
1371 if (
1372 // not timed
1373 (!isTimed) &&
1374 // either of these use cases:
1375 (
1376 // use case 1: shared buffer with any frame count
1377 (
1378 (sharedBuffer != 0)
1379 ) ||
1380 // use case 2: callback handler and frame count is default or at least as large as HAL
1381 (
1382 (tid != -1) &&
1383 ((frameCount == 0) ||
Glenn Kastenb5fed682013-12-03 09:06:43 -08001384 (frameCount >= mFrameCount))
Eric Laurent81784c32012-11-19 14:55:58 -08001385 )
1386 ) &&
1387 // PCM data
1388 audio_is_linear_pcm(format) &&
Andy Hung9a592762014-07-21 21:56:01 -07001389 // identical channel mask to sink, or mono in and stereo sink
1390 (channelMask == mChannelMask ||
1391 (channelMask == AUDIO_CHANNEL_OUT_MONO &&
1392 mChannelMask == AUDIO_CHANNEL_OUT_STEREO)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001393 // hardware sample rate
1394 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001395 // normal mixer has an associated fast mixer
1396 hasFastMixer() &&
1397 // there are sufficient fast track slots available
1398 (mFastTrackAvailMask != 0)
1399 // FIXME test that MixerThread for this fast track has a capable output HAL
1400 // FIXME add a permission test also?
1401 ) {
1402 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1403 if (frameCount == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001404 // read the fast track multiplier property the first time it is needed
1405 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1406 if (ok != 0) {
1407 ALOGE("%s pthread_once failed: %d", __func__, ok);
1408 }
1409 frameCount = mFrameCount * sFastTrackMultiplier;
Eric Laurent81784c32012-11-19 14:55:58 -08001410 }
1411 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
1412 frameCount, mFrameCount);
1413 } else {
1414 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
Andy Hung6146c082014-03-18 11:56:15 -07001415 "mFrameCount=%d format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
1416 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001417 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Andy Hung6146c082014-03-18 11:56:15 -07001418 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001419 audio_is_linear_pcm(format),
1420 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
1421 *flags &= ~IAudioFlinger::TRACK_FAST;
1422 // For compatibility with AudioTrack calculation, buffer depth is forced
1423 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1424 // This is probably too conservative, but legacy application code may depend on it.
1425 // If you change this calculation, also review the start threshold which is related.
1426 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1427 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1428 if (minBufCount < 2) {
1429 minBufCount = 2;
1430 }
1431 size_t minFrameCount = mNormalFrameCount * minBufCount;
1432 if (frameCount < minFrameCount) {
1433 frameCount = minFrameCount;
1434 }
1435 }
1436 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001437 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001438
Glenn Kastenc3df8382014-03-13 15:05:25 -07001439 switch (mType) {
1440
1441 case DIRECT:
Glenn Kasten993fa062014-05-02 11:14:34 -07001442 if (audio_is_linear_pcm(format)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001443 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001444 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1445 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001446 sampleRate, format, channelMask, mOutput, mFormat);
1447 lStatus = BAD_VALUE;
1448 goto Exit;
1449 }
1450 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001451 break;
1452
1453 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001454 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001455 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1456 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001457 sampleRate, format, channelMask, mOutput, mFormat);
1458 lStatus = BAD_VALUE;
1459 goto Exit;
1460 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001461 break;
1462
1463 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07001464 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001465 ALOGE("createTrack_l() Bad parameter: format %#x \""
1466 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001467 format, mOutput, mFormat);
1468 lStatus = BAD_VALUE;
1469 goto Exit;
1470 }
Andy Hungcd044842014-08-07 11:04:34 -07001471 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08001472 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1473 lStatus = BAD_VALUE;
1474 goto Exit;
1475 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001476 break;
1477
Eric Laurent81784c32012-11-19 14:55:58 -08001478 }
1479
1480 lStatus = initCheck();
1481 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07001482 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08001483 goto Exit;
1484 }
1485
1486 { // scope for mLock
1487 Mutex::Autolock _l(mLock);
1488
1489 // all tracks in same audio session must share the same routing strategy otherwise
1490 // conflicts will happen when tracks are moved from one output to another by audio policy
1491 // manager
1492 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1493 for (size_t i = 0; i < mTracks.size(); ++i) {
1494 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07001495 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001496 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1497 if (sessionId == t->sessionId() && strategy != actual) {
1498 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1499 strategy, actual);
1500 lStatus = BAD_VALUE;
1501 goto Exit;
1502 }
1503 }
1504 }
1505
1506 if (!isTimed) {
1507 track = new Track(this, client, streamType, sampleRate, format,
Eric Laurent83b88082014-06-20 18:31:16 -07001508 channelMask, frameCount, NULL, sharedBuffer,
1509 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08001510 } else {
1511 track = TimedTrack::create(this, client, streamType, sampleRate, format,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001512 channelMask, frameCount, sharedBuffer, sessionId, uid);
Eric Laurent81784c32012-11-19 14:55:58 -08001513 }
Glenn Kasten03003332013-08-06 15:40:54 -07001514
1515 // new Track always returns non-NULL,
1516 // but TimedTrack::create() is a factory that could fail by returning NULL
1517 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
1518 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08001519 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001520 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08001521 goto Exit;
1522 }
1523 mTracks.add(track);
1524
1525 sp<EffectChain> chain = getEffectChain_l(sessionId);
1526 if (chain != 0) {
1527 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1528 track->setMainBuffer(chain->inBuffer());
1529 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1530 chain->incTrackCnt();
1531 }
1532
1533 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1534 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1535 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1536 // so ask activity manager to do this on our behalf
1537 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1538 }
1539 }
1540
1541 lStatus = NO_ERROR;
1542
1543Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001544 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001545 return track;
1546}
1547
1548uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1549{
1550 return latency;
1551}
1552
1553uint32_t AudioFlinger::PlaybackThread::latency() const
1554{
1555 Mutex::Autolock _l(mLock);
1556 return latency_l();
1557}
1558uint32_t AudioFlinger::PlaybackThread::latency_l() const
1559{
1560 if (initCheck() == NO_ERROR) {
1561 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
1562 } else {
1563 return 0;
1564 }
1565}
1566
1567void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1568{
1569 Mutex::Autolock _l(mLock);
1570 // Don't apply master volume in SW if our HAL can do it for us.
1571 if (mOutput && mOutput->audioHwDev &&
1572 mOutput->audioHwDev->canSetMasterVolume()) {
1573 mMasterVolume = 1.0;
1574 } else {
1575 mMasterVolume = value;
1576 }
1577}
1578
1579void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1580{
1581 Mutex::Autolock _l(mLock);
1582 // Don't apply master mute in SW if our HAL can do it for us.
1583 if (mOutput && mOutput->audioHwDev &&
1584 mOutput->audioHwDev->canSetMasterMute()) {
1585 mMasterMute = false;
1586 } else {
1587 mMasterMute = muted;
1588 }
1589}
1590
1591void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
1592{
1593 Mutex::Autolock _l(mLock);
1594 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001595 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001596}
1597
1598void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
1599{
1600 Mutex::Autolock _l(mLock);
1601 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001602 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001603}
1604
1605float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
1606{
1607 Mutex::Autolock _l(mLock);
1608 return mStreamTypes[stream].volume;
1609}
1610
1611// addTrack_l() must be called with ThreadBase::mLock held
1612status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1613{
1614 status_t status = ALREADY_EXISTS;
1615
1616 // set retry count for buffer fill
1617 track->mRetryCount = kMaxTrackStartupRetries;
1618 if (mActiveTracks.indexOf(track) < 0) {
1619 // the track is newly added, make sure it fills up all its
1620 // buffers before playing. This is to ensure the client will
1621 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07001622 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001623 TrackBase::track_state state = track->mState;
1624 mLock.unlock();
1625 status = AudioSystem::startOutput(mId, track->streamType(), track->sessionId());
1626 mLock.lock();
1627 // abort track was stopped/paused while we released the lock
1628 if (state != track->mState) {
1629 if (status == NO_ERROR) {
1630 mLock.unlock();
1631 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
1632 mLock.lock();
1633 }
1634 return INVALID_OPERATION;
1635 }
1636 // abort if start is rejected by audio policy manager
1637 if (status != NO_ERROR) {
1638 return PERMISSION_DENIED;
1639 }
1640#ifdef ADD_BATTERY_DATA
1641 // to track the speaker usage
1642 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
1643#endif
1644 }
1645
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001646 track->mFillingUpStatus = track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent81784c32012-11-19 14:55:58 -08001647 track->mResetDone = false;
1648 track->mPresentationCompleteFrames = 0;
1649 mActiveTracks.add(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001650 mWakeLockUids.add(track->uid());
1651 mActiveTracksGeneration++;
Eric Laurentfd477972013-10-25 18:10:40 -07001652 mLatestActiveTrack = track;
Eric Laurentd0107bc2013-06-11 14:38:48 -07001653 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1654 if (chain != 0) {
1655 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
1656 track->sessionId());
1657 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08001658 }
1659
1660 status = NO_ERROR;
1661 }
1662
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08001663 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001664 return status;
1665}
1666
Eric Laurentbfb1b832013-01-07 09:53:42 -08001667bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08001668{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001669 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08001670 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001671 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
1672 track->mState = TrackBase::STOPPED;
1673 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08001674 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07001675 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001676 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08001677 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001678
1679 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08001680}
1681
1682void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1683{
1684 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
1685 mTracks.remove(track);
1686 deleteTrackName_l(track->name());
1687 // redundant as track is about to be destroyed, for dumpsys only
1688 track->mName = -1;
1689 if (track->isFastTrack()) {
1690 int index = track->mFastIndex;
1691 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
1692 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1693 mFastTrackAvailMask |= 1 << index;
1694 // redundant as track is about to be destroyed, for dumpsys only
1695 track->mFastIndex = -1;
1696 }
1697 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1698 if (chain != 0) {
1699 chain->decTrackCnt();
1700 }
1701}
1702
Eric Laurentede6c3b2013-09-19 14:37:46 -07001703void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001704{
1705 // Thread could be blocked waiting for async
1706 // so signal it to handle state changes immediately
1707 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1708 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1709 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001710 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001711}
1712
Eric Laurent81784c32012-11-19 14:55:58 -08001713String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1714{
Eric Laurent81784c32012-11-19 14:55:58 -08001715 Mutex::Autolock _l(mLock);
1716 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07001717 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08001718 }
1719
Glenn Kastend8ea6992013-07-16 14:17:15 -07001720 char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
1721 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08001722 free(s);
1723 return out_s8;
1724}
1725
Eric Laurent021cf962014-05-13 10:18:14 -07001726void AudioFlinger::PlaybackThread::audioConfigChanged(int event, int param) {
Eric Laurent81784c32012-11-19 14:55:58 -08001727 AudioSystem::OutputDescriptor desc;
1728 void *param2 = NULL;
1729
Eric Laurent021cf962014-05-13 10:18:14 -07001730 ALOGV("PlaybackThread::audioConfigChanged, thread %p, event %d, param %d", this, event,
Eric Laurent81784c32012-11-19 14:55:58 -08001731 param);
1732
1733 switch (event) {
1734 case AudioSystem::OUTPUT_OPENED:
1735 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07001736 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08001737 desc.samplingRate = mSampleRate;
1738 desc.format = mFormat;
1739 desc.frameCount = mNormalFrameCount; // FIXME see
1740 // AudioFlinger::frameCount(audio_io_handle_t)
Eric Laurent10351942014-05-08 18:49:52 -07001741 desc.latency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001742 param2 = &desc;
1743 break;
1744
1745 case AudioSystem::STREAM_CONFIG_CHANGED:
1746 param2 = &param;
1747 case AudioSystem::OUTPUT_CLOSED:
1748 default:
1749 break;
1750 }
Eric Laurent021cf962014-05-13 10:18:14 -07001751 mAudioFlinger->audioConfigChanged(event, mId, param2);
Eric Laurent81784c32012-11-19 14:55:58 -08001752}
1753
Eric Laurentbfb1b832013-01-07 09:53:42 -08001754void AudioFlinger::PlaybackThread::writeCallback()
1755{
1756 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001757 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001758}
1759
1760void AudioFlinger::PlaybackThread::drainCallback()
1761{
1762 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001763 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001764}
1765
Eric Laurent3b4529e2013-09-05 18:09:19 -07001766void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001767{
1768 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001769 // reject out of sequence requests
1770 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
1771 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001772 mWaitWorkCV.signal();
1773 }
1774}
1775
Eric Laurent3b4529e2013-09-05 18:09:19 -07001776void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001777{
1778 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001779 // reject out of sequence requests
1780 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
1781 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001782 mWaitWorkCV.signal();
1783 }
1784}
1785
1786// static
1787int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
Glenn Kasten0f11b512014-01-31 16:18:54 -08001788 void *param __unused,
Eric Laurentbfb1b832013-01-07 09:53:42 -08001789 void *cookie)
1790{
1791 AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
1792 ALOGV("asyncCallback() event %d", event);
1793 switch (event) {
1794 case STREAM_CBK_EVENT_WRITE_READY:
1795 me->writeCallback();
1796 break;
1797 case STREAM_CBK_EVENT_DRAIN_READY:
1798 me->drainCallback();
1799 break;
1800 default:
1801 ALOGW("asyncCallback() unknown event %d", event);
1802 break;
1803 }
1804 return 0;
1805}
1806
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001807void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001808{
Glenn Kastenadad3d72014-02-21 14:51:43 -08001809 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Eric Laurent81784c32012-11-19 14:55:58 -08001810 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
1811 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001812 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08001813 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001814 }
Andy Hung9a592762014-07-21 21:56:01 -07001815 if ((mType == MIXER || mType == DUPLICATING)
1816 && !isValidPcmSinkChannelMask(mChannelMask)) {
1817 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
1818 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001819 }
Andy Hunge5412692014-05-16 11:25:07 -07001820 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Andy Hung463be252014-07-10 16:56:07 -07001821 mHALFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
1822 mFormat = mHALFormat;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001823 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08001824 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001825 }
Andy Hung6146c082014-03-18 11:56:15 -07001826 if ((mType == MIXER || mType == DUPLICATING)
1827 && !isValidPcmSinkFormat(mFormat)) {
1828 LOG_FATAL("HAL format %#x not supported for mixed output",
1829 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001830 }
Eric Laurent665470b2014-07-03 16:37:08 -07001831 mFrameSize = audio_stream_out_frame_size(mOutput->stream);
Glenn Kasten70949c42013-08-06 07:40:12 -07001832 mBufferSize = mOutput->stream->common.get_buffer_size(&mOutput->stream->common);
1833 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08001834 if (mFrameCount & 15) {
1835 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
1836 mFrameCount);
1837 }
1838
Eric Laurentbfb1b832013-01-07 09:53:42 -08001839 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
1840 (mOutput->stream->set_callback != NULL)) {
1841 if (mOutput->stream->set_callback(mOutput->stream,
1842 AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
1843 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07001844 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001845 }
1846 }
1847
Andy Hung09a50072014-02-27 14:30:47 -08001848 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08001849 double multiplier = 1.0;
1850 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
1851 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08001852 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
1853 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Eric Laurent81784c32012-11-19 14:55:58 -08001854 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
1855 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
1856 maxNormalFrameCount = maxNormalFrameCount & ~15;
1857 if (maxNormalFrameCount < minNormalFrameCount) {
1858 maxNormalFrameCount = minNormalFrameCount;
1859 }
1860 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
1861 if (multiplier <= 1.0) {
1862 multiplier = 1.0;
1863 } else if (multiplier <= 2.0) {
1864 if (2 * mFrameCount <= maxNormalFrameCount) {
1865 multiplier = 2.0;
1866 } else {
1867 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
1868 }
1869 } else {
1870 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
Andy Hung09a50072014-02-27 14:30:47 -08001871 // 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 -08001872 // track, but we sometimes have to do this to satisfy the maximum frame count
1873 // constraint)
1874 // FIXME this rounding up should not be done if no HAL SRC
1875 uint32_t truncMult = (uint32_t) multiplier;
1876 if ((truncMult & 1)) {
1877 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
1878 ++truncMult;
1879 }
1880 }
1881 multiplier = (double) truncMult;
1882 }
1883 }
1884 mNormalFrameCount = multiplier * mFrameCount;
1885 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07001886 if (mType == MIXER || mType == DUPLICATING) {
1887 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
1888 }
Andy Hung09a50072014-02-27 14:30:47 -08001889 ALOGI("HAL output buffer size %u frames, normal sink buffer size %u frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001890 mNormalFrameCount);
1891
Andy Hung010a1a12014-03-13 13:57:33 -07001892 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
1893 // Originally this was int16_t[] array, need to remove legacy implications.
1894 free(mSinkBuffer);
1895 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07001896 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
1897 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
1898 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07001899 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08001900
Andy Hung69aed5f2014-02-25 17:24:40 -08001901 // We resize the mMixerBuffer according to the requirements of the sink buffer which
1902 // drives the output.
1903 free(mMixerBuffer);
1904 mMixerBuffer = NULL;
1905 if (mMixerBufferEnabled) {
1906 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
1907 mMixerBufferSize = mNormalFrameCount * mChannelCount
1908 * audio_bytes_per_sample(mMixerBufferFormat);
1909 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
1910 }
Andy Hung98ef9782014-03-04 14:46:50 -08001911 free(mEffectBuffer);
1912 mEffectBuffer = NULL;
1913 if (mEffectBufferEnabled) {
1914 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
1915 mEffectBufferSize = mNormalFrameCount * mChannelCount
1916 * audio_bytes_per_sample(mEffectBufferFormat);
1917 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
1918 }
Andy Hung69aed5f2014-02-25 17:24:40 -08001919
Eric Laurent81784c32012-11-19 14:55:58 -08001920 // force reconfiguration of effect chains and engines to take new buffer size and audio
1921 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001922 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08001923 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1924 // matter.
1925 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1926 Vector< sp<EffectChain> > effectChains = mEffectChains;
1927 for (size_t i = 0; i < effectChains.size(); i ++) {
1928 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
1929 }
1930}
1931
1932
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001933status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08001934{
1935 if (halFrames == NULL || dspFrames == NULL) {
1936 return BAD_VALUE;
1937 }
1938 Mutex::Autolock _l(mLock);
1939 if (initCheck() != NO_ERROR) {
1940 return INVALID_OPERATION;
1941 }
1942 size_t framesWritten = mBytesWritten / mFrameSize;
1943 *halFrames = framesWritten;
1944
1945 if (isSuspended()) {
1946 // return an estimation of rendered frames when the output is suspended
1947 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
1948 *dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0;
1949 return NO_ERROR;
1950 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001951 status_t status;
1952 uint32_t frames;
1953 status = mOutput->stream->get_render_position(mOutput->stream, &frames);
1954 *dspFrames = (size_t)frames;
1955 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08001956 }
1957}
1958
1959uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
1960{
1961 Mutex::Autolock _l(mLock);
1962 uint32_t result = 0;
1963 if (getEffectChain_l(sessionId) != 0) {
1964 result = EFFECT_SESSION;
1965 }
1966
1967 for (size_t i = 0; i < mTracks.size(); ++i) {
1968 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08001969 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001970 result |= TRACK_SESSION;
1971 break;
1972 }
1973 }
1974
1975 return result;
1976}
1977
1978uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1979{
1980 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
1981 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
1982 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1983 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
1984 }
1985 for (size_t i = 0; i < mTracks.size(); i++) {
1986 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08001987 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001988 return AudioSystem::getStrategyForStream(track->streamType());
1989 }
1990 }
1991 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
1992}
1993
1994
1995AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
1996{
1997 Mutex::Autolock _l(mLock);
1998 return mOutput;
1999}
2000
2001AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
2002{
2003 Mutex::Autolock _l(mLock);
2004 AudioStreamOut *output = mOutput;
2005 mOutput = NULL;
2006 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2007 // must push a NULL and wait for ack
2008 mOutputSink.clear();
2009 mPipeSink.clear();
2010 mNormalSink.clear();
2011 return output;
2012}
2013
2014// this method must always be called either with ThreadBase mLock held or inside the thread loop
2015audio_stream_t* AudioFlinger::PlaybackThread::stream() const
2016{
2017 if (mOutput == NULL) {
2018 return NULL;
2019 }
2020 return &mOutput->stream->common;
2021}
2022
2023uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2024{
2025 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2026}
2027
2028status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2029{
2030 if (!isValidSyncEvent(event)) {
2031 return BAD_VALUE;
2032 }
2033
2034 Mutex::Autolock _l(mLock);
2035
2036 for (size_t i = 0; i < mTracks.size(); ++i) {
2037 sp<Track> track = mTracks[i];
2038 if (event->triggerSession() == track->sessionId()) {
2039 (void) track->setSyncEvent(event);
2040 return NO_ERROR;
2041 }
2042 }
2043
2044 return NAME_NOT_FOUND;
2045}
2046
2047bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2048{
2049 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2050}
2051
2052void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2053 const Vector< sp<Track> >& tracksToRemove)
2054{
2055 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002056 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002057 for (size_t i = 0 ; i < count ; i++) {
2058 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002059 if (track->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002060 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002061#ifdef ADD_BATTERY_DATA
2062 // to track the speaker usage
2063 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2064#endif
2065 if (track->isTerminated()) {
2066 AudioSystem::releaseOutput(mId);
2067 }
Eric Laurent81784c32012-11-19 14:55:58 -08002068 }
2069 }
2070 }
Eric Laurent81784c32012-11-19 14:55:58 -08002071}
2072
2073void AudioFlinger::PlaybackThread::checkSilentMode_l()
2074{
2075 if (!mMasterMute) {
2076 char value[PROPERTY_VALUE_MAX];
2077 if (property_get("ro.audio.silent", value, "0") > 0) {
2078 char *endptr;
2079 unsigned long ul = strtoul(value, &endptr, 0);
2080 if (*endptr == '\0' && ul != 0) {
2081 ALOGD("Silence is golden");
2082 // The setprop command will not allow a property to be changed after
2083 // the first time it is set, so we don't have to worry about un-muting.
2084 setMasterMute_l(true);
2085 }
2086 }
2087 }
2088}
2089
2090// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002091ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002092{
2093 // FIXME rewrite to reduce number of system calls
2094 mLastWriteTime = systemTime();
2095 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002096 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002097 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002098
2099 // If an NBAIO sink is present, use it to write the normal mixer's submix
2100 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002101
Andy Hung010a1a12014-03-13 13:57:33 -07002102 const size_t count = mBytesRemaining / mFrameSize;
2103
Simon Wilson2d590962012-11-29 15:18:50 -08002104 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002105 // update the setpoint when AudioFlinger::mScreenState changes
2106 uint32_t screenState = AudioFlinger::mScreenState;
2107 if (screenState != mScreenState) {
2108 mScreenState = screenState;
2109 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2110 if (pipe != NULL) {
2111 pipe->setAvgFrames((mScreenState & 1) ?
2112 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2113 }
2114 }
Andy Hung010a1a12014-03-13 13:57:33 -07002115 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002116 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002117 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002118 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002119 } else {
2120 bytesWritten = framesWritten;
2121 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002122 status_t status = mNormalSink->getTimestamp(mLatchD.mTimestamp);
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002123 if (status == NO_ERROR) {
2124 size_t totalFramesWritten = mNormalSink->framesWritten();
2125 if (totalFramesWritten >= mLatchD.mTimestamp.mPosition) {
2126 mLatchD.mUnpresentedFrames = totalFramesWritten - mLatchD.mTimestamp.mPosition;
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002127 // mLatchD.mFramesReleased is set immediately before D is clocked into Q
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002128 mLatchDValid = true;
2129 }
2130 }
Eric Laurent81784c32012-11-19 14:55:58 -08002131 // otherwise use the HAL / AudioStreamOut directly
2132 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002133 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002134
Eric Laurentbfb1b832013-01-07 09:53:42 -08002135 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002136 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2137 mWriteAckSequence += 2;
2138 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002139 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002140 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002141 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002142 // FIXME We should have an implementation of timestamps for direct output threads.
2143 // They are used e.g for multichannel PCM playback over HDMI.
Eric Laurentbfb1b832013-01-07 09:53:42 -08002144 bytesWritten = mOutput->stream->write(mOutput->stream,
Andy Hung2098f272014-02-27 14:00:06 -08002145 (char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002146 if (mUseAsyncWrite &&
2147 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2148 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002149 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002150 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002151 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002152 }
Eric Laurent81784c32012-11-19 14:55:58 -08002153 }
2154
Eric Laurent81784c32012-11-19 14:55:58 -08002155 mNumWrites++;
2156 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002157 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002158 return bytesWritten;
2159}
2160
2161void AudioFlinger::PlaybackThread::threadLoop_drain()
2162{
2163 if (mOutput->stream->drain) {
2164 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2165 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002166 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2167 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002168 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002169 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002170 }
2171 mOutput->stream->drain(mOutput->stream,
2172 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
2173 : AUDIO_DRAIN_ALL);
2174 }
2175}
2176
2177void AudioFlinger::PlaybackThread::threadLoop_exit()
2178{
2179 // Default implementation has nothing to do
Eric Laurent81784c32012-11-19 14:55:58 -08002180}
2181
2182/*
2183The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002184 - mSinkBufferSize from frame count * frame size
Eric Laurent81784c32012-11-19 14:55:58 -08002185 - activeSleepTime from activeSleepTimeUs()
2186 - idleSleepTime from idleSleepTimeUs()
2187 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
2188 - maxPeriod from frame count and sample rate (MIXER only)
2189
2190The parameters that affect these derived values are:
2191 - frame count
2192 - frame size
2193 - sample rate
2194 - device type: A2DP or not
2195 - device latency
2196 - format: PCM or not
2197 - active sleep time
2198 - idle sleep time
2199*/
2200
2201void AudioFlinger::PlaybackThread::cacheParameters_l()
2202{
Andy Hung25c2dac2014-02-27 14:56:00 -08002203 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002204 activeSleepTime = activeSleepTimeUs();
2205 idleSleepTime = idleSleepTimeUs();
2206}
2207
2208void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2209{
Glenn Kasten7c027242012-12-26 14:43:16 -08002210 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurent81784c32012-11-19 14:55:58 -08002211 this, streamType, mTracks.size());
2212 Mutex::Autolock _l(mLock);
2213
2214 size_t size = mTracks.size();
2215 for (size_t i = 0; i < size; i++) {
2216 sp<Track> t = mTracks[i];
2217 if (t->streamType() == streamType) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002218 t->invalidate();
Eric Laurent81784c32012-11-19 14:55:58 -08002219 }
2220 }
2221}
2222
2223status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2224{
2225 int session = chain->sessionId();
Andy Hung010a1a12014-03-13 13:57:33 -07002226 int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled
2227 ? mEffectBuffer : mSinkBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002228 bool ownsBuffer = false;
2229
2230 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
2231 if (session > 0) {
2232 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002233 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002234 if (mType != DIRECT) {
2235 size_t numSamples = mNormalFrameCount * mChannelCount;
2236 buffer = new int16_t[numSamples];
2237 memset(buffer, 0, numSamples * sizeof(int16_t));
2238 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2239 ownsBuffer = true;
2240 }
2241
2242 // Attach all tracks with same session ID to this chain.
2243 for (size_t i = 0; i < mTracks.size(); ++i) {
2244 sp<Track> track = mTracks[i];
2245 if (session == track->sessionId()) {
2246 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2247 buffer);
2248 track->setMainBuffer(buffer);
2249 chain->incTrackCnt();
2250 }
2251 }
2252
2253 // indicate all active tracks in the chain
2254 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2255 sp<Track> track = mActiveTracks[i].promote();
2256 if (track == 0) {
2257 continue;
2258 }
2259 if (session == track->sessionId()) {
2260 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2261 chain->incActiveTrackCnt();
2262 }
2263 }
2264 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002265 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08002266 chain->setInBuffer(buffer, ownsBuffer);
Andy Hung010a1a12014-03-13 13:57:33 -07002267 chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled
2268 ? mEffectBuffer : mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002269 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
2270 // chains list in order to be processed last as it contains output stage effects
2271 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2272 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
2273 // after track specific effects and before output stage
2274 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
2275 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
2276 // Effect chain for other sessions are inserted at beginning of effect
2277 // chains list to be processed before output mix effects. Relative order between other
2278 // sessions is not important
2279 size_t size = mEffectChains.size();
2280 size_t i = 0;
2281 for (i = 0; i < size; i++) {
2282 if (mEffectChains[i]->sessionId() < session) {
2283 break;
2284 }
2285 }
2286 mEffectChains.insertAt(chain, i);
2287 checkSuspendOnAddEffectChain_l(chain);
2288
2289 return NO_ERROR;
2290}
2291
2292size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2293{
2294 int session = chain->sessionId();
2295
2296 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2297
2298 for (size_t i = 0; i < mEffectChains.size(); i++) {
2299 if (chain == mEffectChains[i]) {
2300 mEffectChains.removeAt(i);
2301 // detach all active tracks from the chain
2302 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2303 sp<Track> track = mActiveTracks[i].promote();
2304 if (track == 0) {
2305 continue;
2306 }
2307 if (session == track->sessionId()) {
2308 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2309 chain.get(), session);
2310 chain->decActiveTrackCnt();
2311 }
2312 }
2313
2314 // detach all tracks with same session ID from this chain
2315 for (size_t i = 0; i < mTracks.size(); ++i) {
2316 sp<Track> track = mTracks[i];
2317 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002318 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002319 chain->decTrackCnt();
2320 }
2321 }
2322 break;
2323 }
2324 }
2325 return mEffectChains.size();
2326}
2327
2328status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2329 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2330{
2331 Mutex::Autolock _l(mLock);
2332 return attachAuxEffect_l(track, EffectId);
2333}
2334
2335status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2336 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2337{
2338 status_t status = NO_ERROR;
2339
2340 if (EffectId == 0) {
2341 track->setAuxBuffer(0, NULL);
2342 } else {
2343 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2344 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2345 if (effect != 0) {
2346 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2347 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2348 } else {
2349 status = INVALID_OPERATION;
2350 }
2351 } else {
2352 status = BAD_VALUE;
2353 }
2354 }
2355 return status;
2356}
2357
2358void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2359{
2360 for (size_t i = 0; i < mTracks.size(); ++i) {
2361 sp<Track> track = mTracks[i];
2362 if (track->auxEffectId() == effectId) {
2363 attachAuxEffect_l(track, 0);
2364 }
2365 }
2366}
2367
2368bool AudioFlinger::PlaybackThread::threadLoop()
2369{
2370 Vector< sp<Track> > tracksToRemove;
2371
2372 standbyTime = systemTime();
2373
2374 // MIXER
2375 nsecs_t lastWarning = 0;
2376
2377 // DUPLICATING
2378 // FIXME could this be made local to while loop?
2379 writeFrames = 0;
2380
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002381 int lastGeneration = 0;
2382
Eric Laurent81784c32012-11-19 14:55:58 -08002383 cacheParameters_l();
2384 sleepTime = idleSleepTime;
2385
2386 if (mType == MIXER) {
2387 sleepTimeShift = 0;
2388 }
2389
2390 CpuStats cpuStats;
2391 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2392
2393 acquireWakeLock();
2394
Glenn Kasten9e58b552013-01-18 15:09:48 -08002395 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2396 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2397 // and then that string will be logged at the next convenient opportunity.
2398 const char *logString = NULL;
2399
Eric Laurent664539d2013-09-23 18:24:31 -07002400 checkSilentMode_l();
2401
Eric Laurent81784c32012-11-19 14:55:58 -08002402 while (!exitPending())
2403 {
2404 cpuStats.sample(myName);
2405
2406 Vector< sp<EffectChain> > effectChains;
2407
Eric Laurent81784c32012-11-19 14:55:58 -08002408 { // scope for mLock
2409
2410 Mutex::Autolock _l(mLock);
2411
Eric Laurent021cf962014-05-13 10:18:14 -07002412 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07002413
Glenn Kasten9e58b552013-01-18 15:09:48 -08002414 if (logString != NULL) {
2415 mNBLogWriter->logTimestamp();
2416 mNBLogWriter->log(logString);
2417 logString = NULL;
2418 }
2419
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002420 // Gather the framesReleased counters for all active tracks,
2421 // and latch them atomically with the timestamp.
2422 // FIXME We're using raw pointers as indices. A unique track ID would be a better index.
2423 mLatchD.mFramesReleased.clear();
2424 size_t size = mActiveTracks.size();
2425 for (size_t i = 0; i < size; i++) {
2426 sp<Track> t = mActiveTracks[i].promote();
2427 if (t != 0) {
2428 mLatchD.mFramesReleased.add(t.get(),
2429 t->mAudioTrackServerProxy->framesReleased());
2430 }
2431 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002432 if (mLatchDValid) {
2433 mLatchQ = mLatchD;
2434 mLatchDValid = false;
2435 mLatchQValid = true;
2436 }
2437
Eric Laurent81784c32012-11-19 14:55:58 -08002438 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002439 if (mSignalPending) {
2440 // A signal was raised while we were unlocked
2441 mSignalPending = false;
2442 } else if (waitingAsyncCallback_l()) {
2443 if (exitPending()) {
2444 break;
2445 }
2446 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002447 mWakeLockUids.clear();
2448 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002449 ALOGV("wait async completion");
2450 mWaitWorkCV.wait(mLock);
2451 ALOGV("async completion/wake");
2452 acquireWakeLock_l();
Eric Laurent972a1732013-09-04 09:42:59 -07002453 standbyTime = systemTime() + standbyDelay;
2454 sleepTime = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002455
2456 continue;
2457 }
2458 if ((!mActiveTracks.size() && systemTime() > standbyTime) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08002459 isSuspended()) {
2460 // put audio hardware into standby after short delay
2461 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002462
2463 threadLoop_standby();
2464
2465 mStandby = true;
2466 }
2467
2468 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2469 // we're about to wait, flush the binder command buffer
2470 IPCThreadState::self()->flushCommands();
2471
2472 clearOutputTracks();
2473
2474 if (exitPending()) {
2475 break;
2476 }
2477
2478 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002479 mWakeLockUids.clear();
2480 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002481 // wait until we have something to do...
2482 ALOGV("%s going to sleep", myName.string());
2483 mWaitWorkCV.wait(mLock);
2484 ALOGV("%s waking up", myName.string());
2485 acquireWakeLock_l();
2486
2487 mMixerStatus = MIXER_IDLE;
2488 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2489 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002490 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002491 checkSilentMode_l();
2492
2493 standbyTime = systemTime() + standbyDelay;
2494 sleepTime = idleSleepTime;
2495 if (mType == MIXER) {
2496 sleepTimeShift = 0;
2497 }
2498
2499 continue;
2500 }
2501 }
Eric Laurent81784c32012-11-19 14:55:58 -08002502 // mMixerStatusIgnoringFastTracks is also updated internally
2503 mMixerStatus = prepareTracks_l(&tracksToRemove);
2504
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002505 // compare with previously applied list
2506 if (lastGeneration != mActiveTracksGeneration) {
2507 // update wakelock
2508 updateWakeLockUids_l(mWakeLockUids);
2509 lastGeneration = mActiveTracksGeneration;
2510 }
2511
Eric Laurent81784c32012-11-19 14:55:58 -08002512 // prevent any changes in effect chain list and in each effect chain
2513 // during mixing and effect process as the audio buffers could be deleted
2514 // or modified if an effect is created or deleted
2515 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002516 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08002517
Eric Laurentbfb1b832013-01-07 09:53:42 -08002518 if (mBytesRemaining == 0) {
2519 mCurrentWriteLength = 0;
2520 if (mMixerStatus == MIXER_TRACKS_READY) {
2521 // threadLoop_mix() sets mCurrentWriteLength
2522 threadLoop_mix();
2523 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
2524 && (mMixerStatus != MIXER_DRAIN_ALL)) {
2525 // threadLoop_sleepTime sets sleepTime to 0 if data
2526 // must be written to HAL
2527 threadLoop_sleepTime();
2528 if (sleepTime == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08002529 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002530 }
2531 }
Andy Hung98ef9782014-03-04 14:46:50 -08002532 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
2533 // mMixerBuffer with data if mMixerBufferValid is true and sleepTime == 0.
2534 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
2535 // or mSinkBuffer (if there are no effects).
2536 //
2537 // This is done pre-effects computation; if effects change to
2538 // support higher precision, this needs to move.
2539 //
2540 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
2541 // TODO use sleepTime == 0 as an additional condition.
2542 if (mMixerBufferValid) {
2543 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
2544 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
2545
2546 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
2547 mNormalFrameCount * mChannelCount);
2548 }
2549
Eric Laurentbfb1b832013-01-07 09:53:42 -08002550 mBytesRemaining = mCurrentWriteLength;
2551 if (isSuspended()) {
2552 sleepTime = suspendSleepTimeUs();
2553 // simulate write to HAL when suspended
Andy Hung25c2dac2014-02-27 14:56:00 -08002554 mBytesWritten += mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002555 mBytesRemaining = 0;
2556 }
Eric Laurent81784c32012-11-19 14:55:58 -08002557
Eric Laurentbfb1b832013-01-07 09:53:42 -08002558 // only process effects if we're going to write
Eric Laurent59fe0102013-09-27 18:48:26 -07002559 if (sleepTime == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002560 for (size_t i = 0; i < effectChains.size(); i ++) {
2561 effectChains[i]->process_l();
2562 }
Eric Laurent81784c32012-11-19 14:55:58 -08002563 }
2564 }
Eric Laurent59fe0102013-09-27 18:48:26 -07002565 // Process effect chains for offloaded thread even if no audio
2566 // was read from audio track: process only updates effect state
2567 // and thus does have to be synchronized with audio writes but may have
2568 // to be called while waiting for async write callback
2569 if (mType == OFFLOAD) {
2570 for (size_t i = 0; i < effectChains.size(); i ++) {
2571 effectChains[i]->process_l();
2572 }
2573 }
Eric Laurent81784c32012-11-19 14:55:58 -08002574
Andy Hung98ef9782014-03-04 14:46:50 -08002575 // Only if the Effects buffer is enabled and there is data in the
2576 // Effects buffer (buffer valid), we need to
2577 // copy into the sink buffer.
2578 // TODO use sleepTime == 0 as an additional condition.
2579 if (mEffectBufferValid) {
2580 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
2581 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
2582 mNormalFrameCount * mChannelCount);
2583 }
2584
Eric Laurent81784c32012-11-19 14:55:58 -08002585 // enable changes in effect chain
2586 unlockEffectChains(effectChains);
2587
Eric Laurentbfb1b832013-01-07 09:53:42 -08002588 if (!waitingAsyncCallback()) {
2589 // sleepTime == 0 means we must write to audio hardware
2590 if (sleepTime == 0) {
2591 if (mBytesRemaining) {
2592 ssize_t ret = threadLoop_write();
2593 if (ret < 0) {
2594 mBytesRemaining = 0;
2595 } else {
2596 mBytesWritten += ret;
2597 mBytesRemaining -= ret;
2598 }
2599 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
2600 (mMixerStatus == MIXER_DRAIN_ALL)) {
2601 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08002602 }
Glenn Kasten4944acb2013-08-19 08:39:20 -07002603 if (mType == MIXER) {
2604 // write blocked detection
2605 nsecs_t now = systemTime();
2606 nsecs_t delta = now - mLastWriteTime;
2607 if (!mStandby && delta > maxPeriod) {
2608 mNumDelayedWrites++;
2609 if ((now - lastWarning) > kWarningThrottleNs) {
2610 ATRACE_NAME("underrun");
2611 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2612 ns2ms(delta), mNumDelayedWrites, this);
2613 lastWarning = now;
2614 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002615 }
2616 }
Eric Laurent81784c32012-11-19 14:55:58 -08002617
Eric Laurentbfb1b832013-01-07 09:53:42 -08002618 } else {
2619 usleep(sleepTime);
2620 }
Eric Laurent81784c32012-11-19 14:55:58 -08002621 }
2622
2623 // Finally let go of removed track(s), without the lock held
2624 // since we can't guarantee the destructors won't acquire that
2625 // same lock. This will also mutate and push a new fast mixer state.
2626 threadLoop_removeTracks(tracksToRemove);
2627 tracksToRemove.clear();
2628
2629 // FIXME I don't understand the need for this here;
2630 // it was in the original code but maybe the
2631 // assignment in saveOutputTracks() makes this unnecessary?
2632 clearOutputTracks();
2633
2634 // Effect chains will be actually deleted here if they were removed from
2635 // mEffectChains list during mixing or effects processing
2636 effectChains.clear();
2637
2638 // FIXME Note that the above .clear() is no longer necessary since effectChains
2639 // is now local to this block, but will keep it for now (at least until merge done).
2640 }
2641
Eric Laurentbfb1b832013-01-07 09:53:42 -08002642 threadLoop_exit();
2643
Eric Laurentcf817a22014-08-04 20:36:31 -07002644 if (!mStandby) {
2645 threadLoop_standby();
2646 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08002647 }
2648
2649 releaseWakeLock();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002650 mWakeLockUids.clear();
2651 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002652
2653 ALOGV("Thread %p type %d exiting", this, mType);
2654 return false;
2655}
2656
Eric Laurentbfb1b832013-01-07 09:53:42 -08002657// removeTracks_l() must be called with ThreadBase::mLock held
2658void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
2659{
2660 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002661 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002662 for (size_t i=0 ; i<count ; i++) {
2663 const sp<Track>& track = tracksToRemove.itemAt(i);
2664 mActiveTracks.remove(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002665 mWakeLockUids.remove(track->uid());
2666 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002667 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
2668 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2669 if (chain != 0) {
2670 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
2671 track->sessionId());
2672 chain->decActiveTrackCnt();
2673 }
2674 if (track->isTerminated()) {
2675 removeTrack_l(track);
2676 }
2677 }
2678 }
2679
2680}
Eric Laurent81784c32012-11-19 14:55:58 -08002681
Eric Laurentaccc1472013-09-20 09:36:34 -07002682status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
2683{
2684 if (mNormalSink != 0) {
2685 return mNormalSink->getTimestamp(timestamp);
2686 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07002687 if ((mType == OFFLOAD || mType == DIRECT) && mOutput->stream->get_presentation_position) {
Eric Laurentaccc1472013-09-20 09:36:34 -07002688 uint64_t position64;
2689 int ret = mOutput->stream->get_presentation_position(
2690 mOutput->stream, &position64, &timestamp.mTime);
2691 if (ret == 0) {
2692 timestamp.mPosition = (uint32_t)position64;
2693 return NO_ERROR;
2694 }
2695 }
2696 return INVALID_OPERATION;
2697}
Eric Laurent1c333e22014-05-20 10:48:17 -07002698
2699status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
2700 audio_patch_handle_t *handle)
2701{
2702 status_t status = NO_ERROR;
2703 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
2704 // store new device and send to effects
2705 audio_devices_t type = AUDIO_DEVICE_NONE;
2706 for (unsigned int i = 0; i < patch->num_sinks; i++) {
2707 type |= patch->sinks[i].ext.device.type;
2708 }
2709 mOutDevice = type;
2710 for (size_t i = 0; i < mEffectChains.size(); i++) {
2711 mEffectChains[i]->setDevice_l(mOutDevice);
2712 }
2713
2714 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
2715 status = hwDevice->create_audio_patch(hwDevice,
2716 patch->num_sources,
2717 patch->sources,
2718 patch->num_sinks,
2719 patch->sinks,
2720 handle);
2721 } else {
2722 ALOG_ASSERT(false, "createAudioPatch_l() called on a pre 3.0 HAL");
2723 }
2724 return status;
2725}
2726
2727status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
2728{
2729 status_t status = NO_ERROR;
2730 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
2731 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
2732 status = hwDevice->release_audio_patch(hwDevice, handle);
2733 } else {
2734 ALOG_ASSERT(false, "releaseAudioPatch_l() called on a pre 3.0 HAL");
2735 }
2736 return status;
2737}
2738
Eric Laurent83b88082014-06-20 18:31:16 -07002739void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
2740{
2741 Mutex::Autolock _l(mLock);
2742 mTracks.add(track);
2743}
2744
2745void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
2746{
2747 Mutex::Autolock _l(mLock);
2748 destroyTrack_l(track);
2749}
2750
2751void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
2752{
2753 ThreadBase::getAudioPortConfig(config);
2754 config->role = AUDIO_PORT_ROLE_SOURCE;
2755 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
2756 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
2757}
2758
Eric Laurent81784c32012-11-19 14:55:58 -08002759// ----------------------------------------------------------------------------
2760
2761AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
2762 audio_io_handle_t id, audio_devices_t device, type_t type)
2763 : PlaybackThread(audioFlinger, output, id, device, type),
2764 // mAudioMixer below
2765 // mFastMixer below
2766 mFastMixerFutex(0)
2767 // mOutputSink below
2768 // mPipeSink below
2769 // mNormalSink below
2770{
2771 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07002772 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, "
Eric Laurent81784c32012-11-19 14:55:58 -08002773 "mFrameCount=%d, mNormalFrameCount=%d",
2774 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2775 mNormalFrameCount);
2776 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2777
Eric Laurent81784c32012-11-19 14:55:58 -08002778 // create an NBAIO sink for the HAL output stream, and negotiate
2779 mOutputSink = new AudioStreamOutSink(output->stream);
2780 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08002781 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Eric Laurent81784c32012-11-19 14:55:58 -08002782 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2783 ALOG_ASSERT(index == 0);
2784
2785 // initialize fast mixer depending on configuration
2786 bool initFastMixer;
2787 switch (kUseFastMixer) {
2788 case FastMixer_Never:
2789 initFastMixer = false;
2790 break;
2791 case FastMixer_Always:
2792 initFastMixer = true;
2793 break;
2794 case FastMixer_Static:
2795 case FastMixer_Dynamic:
2796 initFastMixer = mFrameCount < mNormalFrameCount;
2797 break;
2798 }
2799 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07002800 audio_format_t fastMixerFormat;
2801 if (mMixerBufferEnabled && mEffectBufferEnabled) {
2802 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
2803 } else {
2804 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
2805 }
2806 if (mFormat != fastMixerFormat) {
2807 // change our Sink format to accept our intermediate precision
2808 mFormat = fastMixerFormat;
2809 free(mSinkBuffer);
2810 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2811 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
2812 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
2813 }
Eric Laurent81784c32012-11-19 14:55:58 -08002814
2815 // create a MonoPipe to connect our submix to FastMixer
2816 NBAIO_Format format = mOutputSink->format();
Glenn Kastenba0b34c2014-09-28 13:06:06 -07002817 NBAIO_Format origformat = format;
Andy Hung1258c1a2014-05-23 21:22:17 -07002818 // adjust format to match that of the Fast Mixer
2819 format.mFormat = fastMixerFormat;
2820 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
2821
Eric Laurent81784c32012-11-19 14:55:58 -08002822 // This pipe depth compensates for scheduling latency of the normal mixer thread.
2823 // When it wakes up after a maximum latency, it runs a few cycles quickly before
2824 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
2825 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
2826 const NBAIO_Format offers[1] = {format};
2827 size_t numCounterOffers = 0;
2828 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2829 ALOG_ASSERT(index == 0);
2830 monoPipe->setAvgFrames((mScreenState & 1) ?
2831 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2832 mPipeSink = monoPipe;
2833
Glenn Kasten46909e72013-02-26 09:20:22 -08002834#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08002835 if (mTeeSinkOutputEnabled) {
2836 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07002837 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
2838 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08002839 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07002840 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08002841 ALOG_ASSERT(index == 0);
2842 mTeeSink = teeSink;
2843 PipeReader *teeSource = new PipeReader(*teeSink);
2844 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07002845 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08002846 ALOG_ASSERT(index == 0);
2847 mTeeSource = teeSource;
2848 }
Glenn Kasten46909e72013-02-26 09:20:22 -08002849#endif
Eric Laurent81784c32012-11-19 14:55:58 -08002850
2851 // create fast mixer and configure it initially with just one fast track for our submix
2852 mFastMixer = new FastMixer();
2853 FastMixerStateQueue *sq = mFastMixer->sq();
2854#ifdef STATE_QUEUE_DUMP
2855 sq->setObserverDump(&mStateQueueObserverDump);
2856 sq->setMutatorDump(&mStateQueueMutatorDump);
2857#endif
2858 FastMixerState *state = sq->begin();
2859 FastTrack *fastTrack = &state->mFastTracks[0];
2860 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2861 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2862 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07002863 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
2864 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08002865 fastTrack->mGeneration++;
2866 state->mFastTracksGen++;
2867 state->mTrackMask = 1;
2868 // fast mixer will use the HAL output sink
2869 state->mOutputSink = mOutputSink.get();
2870 state->mOutputSinkGen++;
2871 state->mFrameCount = mFrameCount;
2872 state->mCommand = FastMixerState::COLD_IDLE;
2873 // already done in constructor initialization list
2874 //mFastMixerFutex = 0;
2875 state->mColdFutexAddr = &mFastMixerFutex;
2876 state->mColdGen++;
2877 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08002878#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08002879 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08002880#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08002881 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
2882 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08002883 sq->end();
2884 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2885
2886 // start the fast mixer
2887 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
2888 pid_t tid = mFastMixer->getTid();
2889 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2890 if (err != 0) {
2891 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2892 kPriorityFastMixer, getpid_cached, tid, err);
2893 }
2894
2895#ifdef AUDIO_WATCHDOG
2896 // create and start the watchdog
2897 mAudioWatchdog = new AudioWatchdog();
2898 mAudioWatchdog->setDump(&mAudioWatchdogDump);
2899 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
2900 tid = mAudioWatchdog->getTid();
2901 err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2902 if (err != 0) {
2903 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2904 kPriorityFastMixer, getpid_cached, tid, err);
2905 }
2906#endif
2907
Eric Laurent81784c32012-11-19 14:55:58 -08002908 }
2909
2910 switch (kUseFastMixer) {
2911 case FastMixer_Never:
2912 case FastMixer_Dynamic:
2913 mNormalSink = mOutputSink;
2914 break;
2915 case FastMixer_Always:
2916 mNormalSink = mPipeSink;
2917 break;
2918 case FastMixer_Static:
2919 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2920 break;
2921 }
2922}
2923
2924AudioFlinger::MixerThread::~MixerThread()
2925{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07002926 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002927 FastMixerStateQueue *sq = mFastMixer->sq();
2928 FastMixerState *state = sq->begin();
2929 if (state->mCommand == FastMixerState::COLD_IDLE) {
2930 int32_t old = android_atomic_inc(&mFastMixerFutex);
2931 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07002932 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08002933 }
2934 }
2935 state->mCommand = FastMixerState::EXIT;
2936 sq->end();
2937 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2938 mFastMixer->join();
2939 // Though the fast mixer thread has exited, it's state queue is still valid.
2940 // We'll use that extract the final state which contains one remaining fast track
2941 // corresponding to our sub-mix.
2942 state = sq->begin();
2943 ALOG_ASSERT(state->mTrackMask == 1);
2944 FastTrack *fastTrack = &state->mFastTracks[0];
2945 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2946 delete fastTrack->mBufferProvider;
2947 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07002948 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08002949#ifdef AUDIO_WATCHDOG
2950 if (mAudioWatchdog != 0) {
2951 mAudioWatchdog->requestExit();
2952 mAudioWatchdog->requestExitAndWait();
2953 mAudioWatchdog.clear();
2954 }
2955#endif
2956 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08002957 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08002958 delete mAudioMixer;
2959}
2960
2961
2962uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
2963{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07002964 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002965 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2966 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
2967 }
2968 return latency;
2969}
2970
2971
2972void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2973{
2974 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
2975}
2976
Eric Laurentbfb1b832013-01-07 09:53:42 -08002977ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002978{
2979 // FIXME we should only do one push per cycle; confirm this is true
2980 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07002981 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002982 FastMixerStateQueue *sq = mFastMixer->sq();
2983 FastMixerState *state = sq->begin();
2984 if (state->mCommand != FastMixerState::MIX_WRITE &&
2985 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
2986 if (state->mCommand == FastMixerState::COLD_IDLE) {
2987 int32_t old = android_atomic_inc(&mFastMixerFutex);
2988 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07002989 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08002990 }
2991#ifdef AUDIO_WATCHDOG
2992 if (mAudioWatchdog != 0) {
2993 mAudioWatchdog->resume();
2994 }
2995#endif
2996 }
2997 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002998 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
2999 FastMixerDumpState::kSamplingNforLowRamDevice : FastMixerDumpState::kSamplingN);
Eric Laurent81784c32012-11-19 14:55:58 -08003000 sq->end();
3001 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3002 if (kUseFastMixer == FastMixer_Dynamic) {
3003 mNormalSink = mPipeSink;
3004 }
3005 } else {
3006 sq->end(false /*didModify*/);
3007 }
3008 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003009 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003010}
3011
3012void AudioFlinger::MixerThread::threadLoop_standby()
3013{
3014 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003015 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003016 FastMixerStateQueue *sq = mFastMixer->sq();
3017 FastMixerState *state = sq->begin();
3018 if (!(state->mCommand & FastMixerState::IDLE)) {
3019 state->mCommand = FastMixerState::COLD_IDLE;
3020 state->mColdFutexAddr = &mFastMixerFutex;
3021 state->mColdGen++;
3022 mFastMixerFutex = 0;
3023 sq->end();
3024 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3025 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3026 if (kUseFastMixer == FastMixer_Dynamic) {
3027 mNormalSink = mOutputSink;
3028 }
3029#ifdef AUDIO_WATCHDOG
3030 if (mAudioWatchdog != 0) {
3031 mAudioWatchdog->pause();
3032 }
3033#endif
3034 } else {
3035 sq->end(false /*didModify*/);
3036 }
3037 }
3038 PlaybackThread::threadLoop_standby();
3039}
3040
Eric Laurentbfb1b832013-01-07 09:53:42 -08003041bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3042{
3043 return false;
3044}
3045
3046bool AudioFlinger::PlaybackThread::shouldStandby_l()
3047{
3048 return !mStandby;
3049}
3050
3051bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3052{
3053 Mutex::Autolock _l(mLock);
3054 return waitingAsyncCallback_l();
3055}
3056
Eric Laurent81784c32012-11-19 14:55:58 -08003057// shared by MIXER and DIRECT, overridden by DUPLICATING
3058void AudioFlinger::PlaybackThread::threadLoop_standby()
3059{
3060 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
3061 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003062 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003063 // discard any pending drain or write ack by incrementing sequence
3064 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3065 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003066 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003067 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3068 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003069 }
Eric Laurent81784c32012-11-19 14:55:58 -08003070}
3071
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003072void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3073{
3074 ALOGV("signal playback thread");
3075 broadcast_l();
3076}
3077
Eric Laurent81784c32012-11-19 14:55:58 -08003078void AudioFlinger::MixerThread::threadLoop_mix()
3079{
3080 // obtain the presentation timestamp of the next output buffer
3081 int64_t pts;
3082 status_t status = INVALID_OPERATION;
3083
3084 if (mNormalSink != 0) {
3085 status = mNormalSink->getNextWriteTimestamp(&pts);
3086 } else {
3087 status = mOutputSink->getNextWriteTimestamp(&pts);
3088 }
3089
3090 if (status != NO_ERROR) {
3091 pts = AudioBufferProvider::kInvalidPTS;
3092 }
3093
3094 // mix buffers...
3095 mAudioMixer->process(pts);
Andy Hung25c2dac2014-02-27 14:56:00 -08003096 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003097 // increase sleep time progressively when application underrun condition clears.
3098 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3099 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3100 // such that we would underrun the audio HAL.
3101 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
3102 sleepTimeShift--;
3103 }
3104 sleepTime = 0;
3105 standbyTime = systemTime() + standbyDelay;
3106 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003107
Eric Laurent81784c32012-11-19 14:55:58 -08003108}
3109
3110void AudioFlinger::MixerThread::threadLoop_sleepTime()
3111{
3112 // If no tracks are ready, sleep once for the duration of an output
3113 // buffer size, then write 0s to the output
3114 if (sleepTime == 0) {
3115 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3116 sleepTime = activeSleepTime >> sleepTimeShift;
3117 if (sleepTime < kMinThreadSleepTimeUs) {
3118 sleepTime = kMinThreadSleepTimeUs;
3119 }
3120 // reduce sleep time in case of consecutive application underruns to avoid
3121 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3122 // duration we would end up writing less data than needed by the audio HAL if
3123 // the condition persists.
3124 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3125 sleepTimeShift++;
3126 }
3127 } else {
3128 sleepTime = idleSleepTime;
3129 }
3130 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003131 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3132 // before effects processing or output.
3133 if (mMixerBufferValid) {
3134 memset(mMixerBuffer, 0, mMixerBufferSize);
3135 } else {
3136 memset(mSinkBuffer, 0, mSinkBufferSize);
3137 }
Eric Laurent81784c32012-11-19 14:55:58 -08003138 sleepTime = 0;
3139 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3140 "anticipated start");
3141 }
3142 // TODO add standby time extension fct of effect tail
3143}
3144
3145// prepareTracks_l() must be called with ThreadBase::mLock held
3146AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3147 Vector< sp<Track> > *tracksToRemove)
3148{
3149
3150 mixer_state mixerStatus = MIXER_IDLE;
3151 // find out which tracks need to be processed
3152 size_t count = mActiveTracks.size();
3153 size_t mixedTracks = 0;
3154 size_t tracksWithEffect = 0;
3155 // counts only _active_ fast tracks
3156 size_t fastTracks = 0;
3157 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
3158
3159 float masterVolume = mMasterVolume;
3160 bool masterMute = mMasterMute;
3161
3162 if (masterMute) {
3163 masterVolume = 0;
3164 }
3165 // Delegate master volume control to effect in output mix effect chain if needed
3166 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3167 if (chain != 0) {
3168 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
3169 chain->setVolume_l(&v, &v);
3170 masterVolume = (float)((v + (1 << 23)) >> 24);
3171 chain.clear();
3172 }
3173
3174 // prepare a new state to push
3175 FastMixerStateQueue *sq = NULL;
3176 FastMixerState *state = NULL;
3177 bool didModify = false;
3178 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003179 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003180 sq = mFastMixer->sq();
3181 state = sq->begin();
3182 }
3183
Andy Hung69aed5f2014-02-25 17:24:40 -08003184 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08003185 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08003186
Eric Laurent81784c32012-11-19 14:55:58 -08003187 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003188 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003189 if (t == 0) {
3190 continue;
3191 }
3192
3193 // this const just means the local variable doesn't change
3194 Track* const track = t.get();
3195
3196 // process fast tracks
3197 if (track->isFastTrack()) {
3198
3199 // It's theoretically possible (though unlikely) for a fast track to be created
3200 // and then removed within the same normal mix cycle. This is not a problem, as
3201 // the track never becomes active so it's fast mixer slot is never touched.
3202 // The converse, of removing an (active) track and then creating a new track
3203 // at the identical fast mixer slot within the same normal mix cycle,
3204 // is impossible because the slot isn't marked available until the end of each cycle.
3205 int j = track->mFastIndex;
3206 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
3207 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
3208 FastTrack *fastTrack = &state->mFastTracks[j];
3209
3210 // Determine whether the track is currently in underrun condition,
3211 // and whether it had a recent underrun.
3212 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
3213 FastTrackUnderruns underruns = ftDump->mUnderruns;
3214 uint32_t recentFull = (underruns.mBitFields.mFull -
3215 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
3216 uint32_t recentPartial = (underruns.mBitFields.mPartial -
3217 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
3218 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
3219 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
3220 uint32_t recentUnderruns = recentPartial + recentEmpty;
3221 track->mObservedUnderruns = underruns;
3222 // don't count underruns that occur while stopping or pausing
3223 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07003224 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
3225 recentUnderruns > 0) {
3226 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
3227 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003228 }
3229
3230 // This is similar to the state machine for normal tracks,
3231 // with a few modifications for fast tracks.
3232 bool isActive = true;
3233 switch (track->mState) {
3234 case TrackBase::STOPPING_1:
3235 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08003236 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003237 track->mState = TrackBase::STOPPING_2;
3238 }
3239 break;
3240 case TrackBase::PAUSING:
3241 // ramp down is not yet implemented
3242 track->setPaused();
3243 break;
3244 case TrackBase::RESUMING:
3245 // ramp up is not yet implemented
3246 track->mState = TrackBase::ACTIVE;
3247 break;
3248 case TrackBase::ACTIVE:
3249 if (recentFull > 0 || recentPartial > 0) {
3250 // track has provided at least some frames recently: reset retry count
3251 track->mRetryCount = kMaxTrackRetries;
3252 }
3253 if (recentUnderruns == 0) {
3254 // no recent underruns: stay active
3255 break;
3256 }
3257 // there has recently been an underrun of some kind
3258 if (track->sharedBuffer() == 0) {
3259 // were any of the recent underruns "empty" (no frames available)?
3260 if (recentEmpty == 0) {
3261 // no, then ignore the partial underruns as they are allowed indefinitely
3262 break;
3263 }
3264 // there has recently been an "empty" underrun: decrement the retry counter
3265 if (--(track->mRetryCount) > 0) {
3266 break;
3267 }
3268 // indicate to client process that the track was disabled because of underrun;
3269 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003270 android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003271 // remove from active list, but state remains ACTIVE [confusing but true]
3272 isActive = false;
3273 break;
3274 }
3275 // fall through
3276 case TrackBase::STOPPING_2:
3277 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003278 case TrackBase::STOPPED:
3279 case TrackBase::FLUSHED: // flush() while active
3280 // Check for presentation complete if track is inactive
3281 // We have consumed all the buffers of this track.
3282 // This would be incomplete if we auto-paused on underrun
3283 {
3284 size_t audioHALFrames =
3285 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3286 size_t framesWritten = mBytesWritten / mFrameSize;
3287 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
3288 // track stays in active list until presentation is complete
3289 break;
3290 }
3291 }
3292 if (track->isStopping_2()) {
3293 track->mState = TrackBase::STOPPED;
3294 }
3295 if (track->isStopped()) {
3296 // Can't reset directly, as fast mixer is still polling this track
3297 // track->reset();
3298 // So instead mark this track as needing to be reset after push with ack
3299 resetMask |= 1 << i;
3300 }
3301 isActive = false;
3302 break;
3303 case TrackBase::IDLE:
3304 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08003305 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08003306 }
3307
3308 if (isActive) {
3309 // was it previously inactive?
3310 if (!(state->mTrackMask & (1 << j))) {
3311 ExtendedAudioBufferProvider *eabp = track;
3312 VolumeProvider *vp = track;
3313 fastTrack->mBufferProvider = eabp;
3314 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08003315 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003316 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08003317 fastTrack->mGeneration++;
3318 state->mTrackMask |= 1 << j;
3319 didModify = true;
3320 // no acknowledgement required for newly active tracks
3321 }
3322 // cache the combined master volume and stream type volume for fast mixer; this
3323 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08003324 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08003325 ++fastTracks;
3326 } else {
3327 // was it previously active?
3328 if (state->mTrackMask & (1 << j)) {
3329 fastTrack->mBufferProvider = NULL;
3330 fastTrack->mGeneration++;
3331 state->mTrackMask &= ~(1 << j);
3332 didModify = true;
3333 // If any fast tracks were removed, we must wait for acknowledgement
3334 // because we're about to decrement the last sp<> on those tracks.
3335 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3336 } else {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003337 LOG_ALWAYS_FATAL("fast track %d should have been active", j);
Eric Laurent81784c32012-11-19 14:55:58 -08003338 }
3339 tracksToRemove->add(track);
3340 // Avoids a misleading display in dumpsys
3341 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
3342 }
3343 continue;
3344 }
3345
3346 { // local variable scope to avoid goto warning
3347
3348 audio_track_cblk_t* cblk = track->cblk();
3349
3350 // The first time a track is added we wait
3351 // for all its buffers to be filled before processing it
3352 int name = track->name();
3353 // make sure that we have enough frames to mix one full buffer.
3354 // enforce this condition only once to enable draining the buffer in case the client
3355 // app does not call stop() and relies on underrun to stop:
3356 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
3357 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003358 size_t desiredFrames;
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003359 uint32_t sr = track->sampleRate();
3360 if (sr == mSampleRate) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003361 desiredFrames = mNormalFrameCount;
3362 } else {
3363 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003364 desiredFrames = (mNormalFrameCount * sr) / mSampleRate + 1 + 1;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003365 // add frames already consumed but not yet released by the resampler
Glenn Kasten2fc14732013-08-05 14:58:14 -07003366 // because mAudioTrackServerProxy->framesReady() will include these frames
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003367 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
Glenn Kasten74935e42013-12-19 08:56:45 -08003368#if 0
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003369 // the minimum track buffer size is normally twice the number of frames necessary
3370 // to fill one buffer and the resampler should not leave more than one buffer worth
3371 // of unreleased frames after each pass, but just in case...
3372 ALOG_ASSERT(desiredFrames <= cblk->frameCount_);
Glenn Kasten74935e42013-12-19 08:56:45 -08003373#endif
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003374 }
Eric Laurent81784c32012-11-19 14:55:58 -08003375 uint32_t minFrames = 1;
3376 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
3377 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003378 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08003379 }
Eric Laurent13e4c962013-12-20 17:36:01 -08003380
3381 size_t framesReady = track->framesReady();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003382 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08003383 !track->isPaused() && !track->isTerminated())
3384 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003385 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003386
3387 mixedTracks++;
3388
Andy Hung69aed5f2014-02-25 17:24:40 -08003389 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
3390 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08003391 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08003392 if (track->mainBuffer() != mSinkBuffer &&
3393 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08003394 if (mEffectBufferEnabled) {
3395 mEffectBufferValid = true; // Later can set directly.
3396 }
Eric Laurent81784c32012-11-19 14:55:58 -08003397 chain = getEffectChain_l(track->sessionId());
3398 // Delegate volume control to effect in track effect chain if needed
3399 if (chain != 0) {
3400 tracksWithEffect++;
3401 } else {
3402 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
3403 "session %d",
3404 name, track->sessionId());
3405 }
3406 }
3407
3408
3409 int param = AudioMixer::VOLUME;
3410 if (track->mFillingUpStatus == Track::FS_FILLED) {
3411 // no ramp for the first volume setting
3412 track->mFillingUpStatus = Track::FS_ACTIVE;
3413 if (track->mState == TrackBase::RESUMING) {
3414 track->mState = TrackBase::ACTIVE;
3415 param = AudioMixer::RAMP_VOLUME;
3416 }
3417 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003418 // FIXME should not make a decision based on mServer
3419 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003420 // If the track is stopped before the first frame was mixed,
3421 // do not apply ramp
3422 param = AudioMixer::RAMP_VOLUME;
3423 }
3424
3425 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07003426 uint32_t vl, vr; // in U8.24 integer format
3427 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08003428 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07003429 vl = vr = 0;
3430 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08003431 if (track->isPausing()) {
3432 track->setPaused();
3433 }
3434 } else {
3435
3436 // read original volumes with volume control
3437 float typeVolume = mStreamTypes[track->streamType()].volume;
3438 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003439 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07003440 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07003441 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
3442 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08003443 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07003444 if (vlf > GAIN_FLOAT_UNITY) {
3445 ALOGV("Track left volume out of range: %.3g", vlf);
3446 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003447 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07003448 if (vrf > GAIN_FLOAT_UNITY) {
3449 ALOGV("Track right volume out of range: %.3g", vrf);
3450 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003451 }
3452 // now apply the master volume and stream type volume
Andy Hung6be49402014-05-30 10:42:03 -07003453 vlf *= v;
3454 vrf *= v;
Eric Laurent81784c32012-11-19 14:55:58 -08003455 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07003456 // then derive vl and vr as U8.24 versions for the effect chain
3457 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
3458 vl = (uint32_t) (scaleto8_24 * vlf);
3459 vr = (uint32_t) (scaleto8_24 * vrf);
3460 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08003461 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08003462 // send level comes from shared memory and so may be corrupt
3463 if (sendLevel > MAX_GAIN_INT) {
3464 ALOGV("Track send level out of range: %04X", sendLevel);
3465 sendLevel = MAX_GAIN_INT;
3466 }
Andy Hung6be49402014-05-30 10:42:03 -07003467 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
3468 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08003469 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003470
Eric Laurent81784c32012-11-19 14:55:58 -08003471 // Delegate volume control to effect in track effect chain if needed
3472 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3473 // Do not ramp volume if volume is controlled by effect
3474 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08003475 // Update remaining floating point volume levels
3476 vlf = (float)vl / (1 << 24);
3477 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08003478 track->mHasVolumeController = true;
3479 } else {
3480 // force no volume ramp when volume controller was just disabled or removed
3481 // from effect chain to avoid volume spike
3482 if (track->mHasVolumeController) {
3483 param = AudioMixer::VOLUME;
3484 }
3485 track->mHasVolumeController = false;
3486 }
3487
Eric Laurent81784c32012-11-19 14:55:58 -08003488 // XXX: these things DON'T need to be done each time
3489 mAudioMixer->setBufferProvider(name, track);
3490 mAudioMixer->enable(name);
3491
Andy Hung6be49402014-05-30 10:42:03 -07003492 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
3493 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
3494 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08003495 mAudioMixer->setParameter(
3496 name,
3497 AudioMixer::TRACK,
3498 AudioMixer::FORMAT, (void *)track->format());
3499 mAudioMixer->setParameter(
3500 name,
3501 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003502 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07003503 mAudioMixer->setParameter(
3504 name,
3505 AudioMixer::TRACK,
3506 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08003507 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07003508 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003509 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08003510 if (reqSampleRate == 0) {
3511 reqSampleRate = mSampleRate;
3512 } else if (reqSampleRate > maxSampleRate) {
3513 reqSampleRate = maxSampleRate;
3514 }
Eric Laurent81784c32012-11-19 14:55:58 -08003515 mAudioMixer->setParameter(
3516 name,
3517 AudioMixer::RESAMPLE,
3518 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003519 (void *)(uintptr_t)reqSampleRate);
Andy Hung69aed5f2014-02-25 17:24:40 -08003520 /*
3521 * Select the appropriate output buffer for the track.
3522 *
Andy Hung98ef9782014-03-04 14:46:50 -08003523 * Tracks with effects go into their own effects chain buffer
3524 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08003525 *
3526 * Other tracks can use mMixerBuffer for higher precision
3527 * channel accumulation. If this buffer is enabled
3528 * (mMixerBufferEnabled true), then selected tracks will accumulate
3529 * into it.
3530 *
3531 */
3532 if (mMixerBufferEnabled
3533 && (track->mainBuffer() == mSinkBuffer
3534 || track->mainBuffer() == mMixerBuffer)) {
3535 mAudioMixer->setParameter(
3536 name,
3537 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08003538 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08003539 mAudioMixer->setParameter(
3540 name,
3541 AudioMixer::TRACK,
3542 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
3543 // TODO: override track->mainBuffer()?
3544 mMixerBufferValid = true;
3545 } else {
3546 mAudioMixer->setParameter(
3547 name,
3548 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08003549 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08003550 mAudioMixer->setParameter(
3551 name,
3552 AudioMixer::TRACK,
3553 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3554 }
Eric Laurent81784c32012-11-19 14:55:58 -08003555 mAudioMixer->setParameter(
3556 name,
3557 AudioMixer::TRACK,
3558 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3559
3560 // reset retry count
3561 track->mRetryCount = kMaxTrackRetries;
3562
3563 // If one track is ready, set the mixer ready if:
3564 // - the mixer was not ready during previous round OR
3565 // - no other track is not ready
3566 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
3567 mixerStatus != MIXER_TRACKS_ENABLED) {
3568 mixerStatus = MIXER_TRACKS_READY;
3569 }
3570 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003571 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Glenn Kasten82aaf942013-07-17 16:05:07 -07003572 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003573 }
Eric Laurent81784c32012-11-19 14:55:58 -08003574 // clear effect chain input buffer if an active track underruns to avoid sending
3575 // previous audio buffer again to effects
3576 chain = getEffectChain_l(track->sessionId());
3577 if (chain != 0) {
3578 chain->clearInputBuffer();
3579 }
3580
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003581 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003582 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3583 track->isStopped() || track->isPaused()) {
3584 // We have consumed all the buffers of this track.
3585 // Remove it from the list of active tracks.
3586 // TODO: use actual buffer filling status instead of latency when available from
3587 // audio HAL
3588 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3589 size_t framesWritten = mBytesWritten / mFrameSize;
3590 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
3591 if (track->isStopped()) {
3592 track->reset();
3593 }
3594 tracksToRemove->add(track);
3595 }
3596 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08003597 // No buffers for this track. Give it a few chances to
3598 // fill a buffer, then remove it from active list.
3599 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08003600 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003601 tracksToRemove->add(track);
3602 // indicate to client process that the track was disabled because of underrun;
3603 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003604 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003605 // If one track is not ready, mark the mixer also not ready if:
3606 // - the mixer was ready during previous round OR
3607 // - no other track is ready
3608 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
3609 mixerStatus != MIXER_TRACKS_READY) {
3610 mixerStatus = MIXER_TRACKS_ENABLED;
3611 }
3612 }
3613 mAudioMixer->disable(name);
3614 }
3615
3616 } // local variable scope to avoid goto warning
3617track_is_ready: ;
3618
3619 }
3620
3621 // Push the new FastMixer state if necessary
3622 bool pauseAudioWatchdog = false;
3623 if (didModify) {
3624 state->mFastTracksGen++;
3625 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3626 if (kUseFastMixer == FastMixer_Dynamic &&
3627 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3628 state->mCommand = FastMixerState::COLD_IDLE;
3629 state->mColdFutexAddr = &mFastMixerFutex;
3630 state->mColdGen++;
3631 mFastMixerFutex = 0;
3632 if (kUseFastMixer == FastMixer_Dynamic) {
3633 mNormalSink = mOutputSink;
3634 }
3635 // If we go into cold idle, need to wait for acknowledgement
3636 // so that fast mixer stops doing I/O.
3637 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3638 pauseAudioWatchdog = true;
3639 }
Eric Laurent81784c32012-11-19 14:55:58 -08003640 }
3641 if (sq != NULL) {
3642 sq->end(didModify);
3643 sq->push(block);
3644 }
3645#ifdef AUDIO_WATCHDOG
3646 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3647 mAudioWatchdog->pause();
3648 }
3649#endif
3650
3651 // Now perform the deferred reset on fast tracks that have stopped
3652 while (resetMask != 0) {
3653 size_t i = __builtin_ctz(resetMask);
3654 ALOG_ASSERT(i < count);
3655 resetMask &= ~(1 << i);
3656 sp<Track> t = mActiveTracks[i].promote();
3657 if (t == 0) {
3658 continue;
3659 }
3660 Track* track = t.get();
3661 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3662 track->reset();
3663 }
3664
3665 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08003666 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08003667
Eric Laurent97d547d2014-09-02 14:45:53 -07003668 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
3669 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07003670 }
3671
3672 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07003673 // as long as there are effects we should clear the effects buffer, to avoid
3674 // passing a non-clean buffer to the effect chain
3675 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07003676 }
Andy Hung69aed5f2014-02-25 17:24:40 -08003677 // sink or mix buffer must be cleared if all tracks are connected to an
3678 // effect chain as in this case the mixer will not write to the sink or mix buffer
3679 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08003680 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3681 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08003682 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08003683 if (mMixerBufferValid) {
3684 memset(mMixerBuffer, 0, mMixerBufferSize);
3685 // TODO: In testing, mSinkBuffer below need not be cleared because
3686 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
3687 // after mixing.
3688 //
3689 // To enforce this guarantee:
3690 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3691 // (mixedTracks == 0 && fastTracks > 0))
3692 // must imply MIXER_TRACKS_READY.
3693 // Later, we may clear buffers regardless, and skip much of this logic.
3694 }
Andy Hung98ef9782014-03-04 14:46:50 -08003695 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07003696 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003697 }
3698
3699 // if any fast tracks, then status is ready
3700 mMixerStatusIgnoringFastTracks = mixerStatus;
3701 if (fastTracks > 0) {
3702 mixerStatus = MIXER_TRACKS_READY;
3703 }
3704 return mixerStatus;
3705}
3706
3707// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07003708int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
3709 audio_format_t format, int sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08003710{
Andy Hunge8a1ced2014-05-09 15:02:21 -07003711 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08003712}
3713
3714// deleteTrackName_l() must be called with ThreadBase::mLock held
3715void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3716{
3717 ALOGV("remove track (%d) and delete from mixer", name);
3718 mAudioMixer->deleteTrackName(name);
3719}
3720
Eric Laurent10351942014-05-08 18:49:52 -07003721// checkForNewParameter_l() must be called with ThreadBase::mLock held
3722bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
3723 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08003724{
Eric Laurent81784c32012-11-19 14:55:58 -08003725 bool reconfig = false;
3726
Eric Laurent10351942014-05-08 18:49:52 -07003727 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08003728
Eric Laurent10351942014-05-08 18:49:52 -07003729 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3730 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003731 if (mFastMixer != 0) {
Eric Laurent10351942014-05-08 18:49:52 -07003732 FastMixerStateQueue *sq = mFastMixer->sq();
3733 FastMixerState *state = sq->begin();
3734 if (!(state->mCommand & FastMixerState::IDLE)) {
3735 previousCommand = state->mCommand;
3736 state->mCommand = FastMixerState::HOT_IDLE;
3737 sq->end();
3738 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3739 } else {
3740 sq->end(false /*didModify*/);
Eric Laurent81784c32012-11-19 14:55:58 -08003741 }
Eric Laurent10351942014-05-08 18:49:52 -07003742 }
Eric Laurent81784c32012-11-19 14:55:58 -08003743
Eric Laurent10351942014-05-08 18:49:52 -07003744 AudioParameter param = AudioParameter(keyValuePair);
3745 int value;
3746 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3747 reconfig = true;
3748 }
3749 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07003750 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07003751 status = BAD_VALUE;
3752 } else {
3753 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08003754 reconfig = true;
3755 }
Eric Laurent10351942014-05-08 18:49:52 -07003756 }
3757 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07003758 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07003759 status = BAD_VALUE;
3760 } else {
3761 // no need to save value, since it's constant
3762 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003763 }
Eric Laurent10351942014-05-08 18:49:52 -07003764 }
3765 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3766 // do not accept frame count changes if tracks are open as the track buffer
3767 // size depends on frame count and correct behavior would not be guaranteed
3768 // if frame count is changed after track creation
3769 if (!mTracks.isEmpty()) {
3770 status = INVALID_OPERATION;
3771 } else {
3772 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003773 }
Eric Laurent10351942014-05-08 18:49:52 -07003774 }
3775 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08003776#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07003777 // when changing the audio output device, call addBatteryData to notify
3778 // the change
3779 if (mOutDevice != value) {
3780 uint32_t params = 0;
3781 // check whether speaker is on
3782 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
3783 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08003784 }
Eric Laurent10351942014-05-08 18:49:52 -07003785
3786 audio_devices_t deviceWithoutSpeaker
3787 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3788 // check if any other device (except speaker) is on
3789 if (value & deviceWithoutSpeaker ) {
3790 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3791 }
3792
3793 if (params != 0) {
3794 addBatteryData(params);
3795 }
3796 }
Eric Laurent81784c32012-11-19 14:55:58 -08003797#endif
3798
Eric Laurent10351942014-05-08 18:49:52 -07003799 // forward device change to effects that have requested to be
3800 // aware of attached audio device.
3801 if (value != AUDIO_DEVICE_NONE) {
3802 mOutDevice = value;
3803 for (size_t i = 0; i < mEffectChains.size(); i++) {
3804 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08003805 }
3806 }
Eric Laurent10351942014-05-08 18:49:52 -07003807 }
Eric Laurent81784c32012-11-19 14:55:58 -08003808
Eric Laurent10351942014-05-08 18:49:52 -07003809 if (status == NO_ERROR) {
3810 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3811 keyValuePair.string());
3812 if (!mStandby && status == INVALID_OPERATION) {
3813 mOutput->stream->common.standby(&mOutput->stream->common);
3814 mStandby = true;
3815 mBytesWritten = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003816 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Eric Laurent10351942014-05-08 18:49:52 -07003817 keyValuePair.string());
Eric Laurent81784c32012-11-19 14:55:58 -08003818 }
Eric Laurent10351942014-05-08 18:49:52 -07003819 if (status == NO_ERROR && reconfig) {
3820 readOutputParameters_l();
3821 delete mAudioMixer;
3822 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3823 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07003824 int name = getTrackName_l(mTracks[i]->mChannelMask,
3825 mTracks[i]->mFormat, mTracks[i]->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07003826 if (name < 0) {
3827 break;
3828 }
3829 mTracks[i]->mName = name;
3830 }
3831 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3832 }
Eric Laurent81784c32012-11-19 14:55:58 -08003833 }
3834
3835 if (!(previousCommand & FastMixerState::IDLE)) {
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003836 ALOG_ASSERT(mFastMixer != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08003837 FastMixerStateQueue *sq = mFastMixer->sq();
3838 FastMixerState *state = sq->begin();
3839 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3840 state->mCommand = previousCommand;
3841 sq->end();
3842 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3843 }
3844
3845 return reconfig;
3846}
3847
3848
3849void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
3850{
3851 const size_t SIZE = 256;
3852 char buffer[SIZE];
3853 String8 result;
3854
3855 PlaybackThread::dumpInternals(fd, args);
3856
Elliott Hughes87cebad2014-05-22 10:14:43 -07003857 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Eric Laurent81784c32012-11-19 14:55:58 -08003858
3859 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003860 const FastMixerDumpState copy(mFastMixerDumpState);
Eric Laurent81784c32012-11-19 14:55:58 -08003861 copy.dump(fd);
3862
3863#ifdef STATE_QUEUE_DUMP
3864 // Similar for state queue
3865 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
3866 observerCopy.dump(fd);
3867 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
3868 mutatorCopy.dump(fd);
3869#endif
3870
Glenn Kasten46909e72013-02-26 09:20:22 -08003871#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003872 // Write the tee output to a .wav file
3873 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08003874#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003875
3876#ifdef AUDIO_WATCHDOG
3877 if (mAudioWatchdog != 0) {
3878 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
3879 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
3880 wdCopy.dump(fd);
3881 }
3882#endif
3883}
3884
3885uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
3886{
3887 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
3888}
3889
3890uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
3891{
3892 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3893}
3894
3895void AudioFlinger::MixerThread::cacheParameters_l()
3896{
3897 PlaybackThread::cacheParameters_l();
3898
3899 // FIXME: Relaxed timing because of a certain device that can't meet latency
3900 // Should be reduced to 2x after the vendor fixes the driver issue
3901 // increase threshold again due to low power audio mode. The way this warning
3902 // threshold is calculated and its usefulness should be reconsidered anyway.
3903 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
3904}
3905
3906// ----------------------------------------------------------------------------
3907
3908AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3909 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
3910 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
3911 // mLeftVolFloat, mRightVolFloat
3912{
3913}
3914
Eric Laurentbfb1b832013-01-07 09:53:42 -08003915AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3916 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
3917 ThreadBase::type_t type)
3918 : PlaybackThread(audioFlinger, output, id, device, type)
3919 // mLeftVolFloat, mRightVolFloat
3920{
3921}
3922
Eric Laurent81784c32012-11-19 14:55:58 -08003923AudioFlinger::DirectOutputThread::~DirectOutputThread()
3924{
3925}
3926
Eric Laurentbfb1b832013-01-07 09:53:42 -08003927void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
3928{
3929 audio_track_cblk_t* cblk = track->cblk();
3930 float left, right;
3931
3932 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
3933 left = right = 0;
3934 } else {
3935 float typeVolume = mStreamTypes[track->streamType()].volume;
3936 float v = mMasterVolume * typeVolume;
3937 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07003938 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
3939 left = float_from_gain(gain_minifloat_unpack_left(vlr));
3940 if (left > GAIN_FLOAT_UNITY) {
3941 left = GAIN_FLOAT_UNITY;
3942 }
3943 left *= v;
3944 right = float_from_gain(gain_minifloat_unpack_right(vlr));
3945 if (right > GAIN_FLOAT_UNITY) {
3946 right = GAIN_FLOAT_UNITY;
3947 }
3948 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003949 }
3950
3951 if (lastTrack) {
3952 if (left != mLeftVolFloat || right != mRightVolFloat) {
3953 mLeftVolFloat = left;
3954 mRightVolFloat = right;
3955
3956 // Convert volumes from float to 8.24
3957 uint32_t vl = (uint32_t)(left * (1 << 24));
3958 uint32_t vr = (uint32_t)(right * (1 << 24));
3959
3960 // Delegate volume control to effect in track effect chain if needed
3961 // only one effect chain can be present on DirectOutputThread, so if
3962 // there is one, the track is connected to it
3963 if (!mEffectChains.isEmpty()) {
3964 mEffectChains[0]->setVolume_l(&vl, &vr);
3965 left = (float)vl / (1 << 24);
3966 right = (float)vr / (1 << 24);
3967 }
3968 if (mOutput->stream->set_volume) {
3969 mOutput->stream->set_volume(mOutput->stream, left, right);
3970 }
3971 }
3972 }
3973}
3974
3975
Eric Laurent81784c32012-11-19 14:55:58 -08003976AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
3977 Vector< sp<Track> > *tracksToRemove
3978)
3979{
Eric Laurentd595b7c2013-04-03 17:27:56 -07003980 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08003981 mixer_state mixerStatus = MIXER_IDLE;
3982
3983 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07003984 for (size_t i = 0; i < count; i++) {
3985 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003986 // The track died recently
3987 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003988 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08003989 }
3990
3991 Track* const track = t.get();
3992 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07003993 // Only consider last track started for volume and mixer state control.
3994 // In theory an older track could underrun and restart after the new one starts
3995 // but as we only care about the transition phase between two tracks on a
3996 // direct output, it is not a problem to ignore the underrun case.
3997 sp<Track> l = mLatestActiveTrack.promote();
3998 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08003999
4000 // The first time a track is added we wait
4001 // for all its buffers to be filled before processing it
4002 uint32_t minFrames;
Eric Laurentab5cdba2014-06-09 17:22:27 -07004003 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004004 minFrames = mNormalFrameCount;
4005 } else {
4006 minFrames = 1;
4007 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004008
Eric Laurentab5cdba2014-06-09 17:22:27 -07004009 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4010 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08004011 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004012 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08004013
4014 if (track->mFillingUpStatus == Track::FS_FILLED) {
4015 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004016 // make sure processVolume_l() will apply new volume even if 0
4017 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurent81784c32012-11-19 14:55:58 -08004018 if (track->mState == TrackBase::RESUMING) {
4019 track->mState = TrackBase::ACTIVE;
4020 }
4021 }
4022
4023 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004024 processVolume_l(track, last);
4025 if (last) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004026 // reset retry count
4027 track->mRetryCount = kMaxTrackRetriesDirect;
4028 mActiveTrack = t;
4029 mixerStatus = MIXER_TRACKS_READY;
4030 }
Eric Laurent81784c32012-11-19 14:55:58 -08004031 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004032 // clear effect chain input buffer if the last active track started underruns
4033 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07004034 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004035 mEffectChains[0]->clearInputBuffer();
4036 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004037 if (track->isStopping_1()) {
4038 track->mState = TrackBase::STOPPING_2;
4039 }
4040 if ((track->sharedBuffer() != 0) || track->isStopped() ||
4041 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004042 // We have consumed all the buffers of this track.
4043 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07004044 size_t audioHALFrames;
4045 if (audio_is_linear_pcm(mFormat)) {
4046 audioHALFrames = (latency_l() * mSampleRate) / 1000;
4047 } else {
4048 audioHALFrames = 0;
4049 }
4050
Eric Laurent81784c32012-11-19 14:55:58 -08004051 size_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07004052 if (mStandby || !last ||
4053 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004054 if (track->isStopping_2()) {
4055 track->mState = TrackBase::STOPPED;
4056 }
Eric Laurent81784c32012-11-19 14:55:58 -08004057 if (track->isStopped()) {
Eric Laurente659ef42014-09-29 13:06:46 -07004058 if (track->mState == TrackBase::FLUSHED) {
4059 flushHw_l();
4060 }
Eric Laurent81784c32012-11-19 14:55:58 -08004061 track->reset();
4062 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004063 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08004064 }
4065 } else {
4066 // No buffers for this track. Give it a few chances to
4067 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07004068 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08004069 if (--(track->mRetryCount) <= 0) {
4070 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07004071 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004072 // indicate to client process that the track was disabled because of underrun;
4073 // it will then automatically call start() when data is available
4074 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004075 } else if (last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004076 mixerStatus = MIXER_TRACKS_ENABLED;
4077 }
4078 }
4079 }
4080 }
4081
Eric Laurent81784c32012-11-19 14:55:58 -08004082 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004083 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004084
4085 return mixerStatus;
4086}
4087
4088void AudioFlinger::DirectOutputThread::threadLoop_mix()
4089{
Eric Laurent81784c32012-11-19 14:55:58 -08004090 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08004091 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004092 // output audio to hardware
4093 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07004094 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004095 buffer.frameCount = frameCount;
4096 mActiveTrack->getNextBuffer(&buffer);
Glenn Kastenfa319e62013-07-29 17:17:38 -07004097 if (buffer.raw == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08004098 memset(curBuf, 0, frameCount * mFrameSize);
4099 break;
4100 }
4101 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
4102 frameCount -= buffer.frameCount;
4103 curBuf += buffer.frameCount * mFrameSize;
4104 mActiveTrack->releaseBuffer(&buffer);
4105 }
Andy Hung2098f272014-02-27 14:00:06 -08004106 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004107 sleepTime = 0;
4108 standbyTime = systemTime() + standbyDelay;
4109 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004110}
4111
4112void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
4113{
4114 if (sleepTime == 0) {
4115 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4116 sleepTime = activeSleepTime;
4117 } else {
4118 sleepTime = idleSleepTime;
4119 }
4120 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08004121 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004122 sleepTime = 0;
4123 }
4124}
4125
4126// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004127int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Andy Hunge8a1ced2014-05-09 15:02:21 -07004128 audio_format_t format __unused, int sessionId __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004129{
4130 return 0;
4131}
4132
4133// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004134void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004135{
4136}
4137
Eric Laurent10351942014-05-08 18:49:52 -07004138// checkForNewParameter_l() must be called with ThreadBase::mLock held
4139bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
4140 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004141{
4142 bool reconfig = false;
4143
Eric Laurent10351942014-05-08 18:49:52 -07004144 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004145
Eric Laurent10351942014-05-08 18:49:52 -07004146 AudioParameter param = AudioParameter(keyValuePair);
4147 int value;
4148 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4149 // forward device change to effects that have requested to be
4150 // aware of attached audio device.
4151 if (value != AUDIO_DEVICE_NONE) {
4152 mOutDevice = value;
4153 for (size_t i = 0; i < mEffectChains.size(); i++) {
4154 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07004155 }
4156 }
Eric Laurent81784c32012-11-19 14:55:58 -08004157 }
Eric Laurent10351942014-05-08 18:49:52 -07004158 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4159 // do not accept frame count changes if tracks are open as the track buffer
4160 // size depends on frame count and correct behavior would not be garantied
4161 // if frame count is changed after track creation
4162 if (!mTracks.isEmpty()) {
4163 status = INVALID_OPERATION;
4164 } else {
4165 reconfig = true;
4166 }
4167 }
4168 if (status == NO_ERROR) {
4169 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4170 keyValuePair.string());
4171 if (!mStandby && status == INVALID_OPERATION) {
4172 mOutput->stream->common.standby(&mOutput->stream->common);
4173 mStandby = true;
4174 mBytesWritten = 0;
4175 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4176 keyValuePair.string());
4177 }
4178 if (status == NO_ERROR && reconfig) {
4179 readOutputParameters_l();
4180 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
4181 }
4182 }
4183
Eric Laurent81784c32012-11-19 14:55:58 -08004184 return reconfig;
4185}
4186
4187uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
4188{
4189 uint32_t time;
4190 if (audio_is_linear_pcm(mFormat)) {
4191 time = PlaybackThread::activeSleepTimeUs();
4192 } else {
4193 time = 10000;
4194 }
4195 return time;
4196}
4197
4198uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
4199{
4200 uint32_t time;
4201 if (audio_is_linear_pcm(mFormat)) {
4202 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
4203 } else {
4204 time = 10000;
4205 }
4206 return time;
4207}
4208
4209uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
4210{
4211 uint32_t time;
4212 if (audio_is_linear_pcm(mFormat)) {
4213 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
4214 } else {
4215 time = 10000;
4216 }
4217 return time;
4218}
4219
4220void AudioFlinger::DirectOutputThread::cacheParameters_l()
4221{
4222 PlaybackThread::cacheParameters_l();
4223
4224 // use shorter standby delay as on normal output to release
4225 // hardware resources as soon as possible
Eric Laurent972a1732013-09-04 09:42:59 -07004226 if (audio_is_linear_pcm(mFormat)) {
4227 standbyDelay = microseconds(activeSleepTime*2);
4228 } else {
4229 standbyDelay = kOffloadStandbyDelayNs;
4230 }
Eric Laurent81784c32012-11-19 14:55:58 -08004231}
4232
Eric Laurente659ef42014-09-29 13:06:46 -07004233void AudioFlinger::DirectOutputThread::flushHw_l()
4234{
4235 if (mOutput->stream->flush != NULL)
4236 mOutput->stream->flush(mOutput->stream);
4237}
4238
Eric Laurent81784c32012-11-19 14:55:58 -08004239// ----------------------------------------------------------------------------
4240
Eric Laurentbfb1b832013-01-07 09:53:42 -08004241AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07004242 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004243 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07004244 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07004245 mWriteAckSequence(0),
4246 mDrainSequence(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004247{
4248}
4249
4250AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
4251{
4252}
4253
4254void AudioFlinger::AsyncCallbackThread::onFirstRef()
4255{
4256 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
4257}
4258
4259bool AudioFlinger::AsyncCallbackThread::threadLoop()
4260{
4261 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004262 uint32_t writeAckSequence;
4263 uint32_t drainSequence;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004264
4265 {
4266 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08004267 while (!((mWriteAckSequence & 1) ||
4268 (mDrainSequence & 1) ||
4269 exitPending())) {
4270 mWaitWorkCV.wait(mLock);
4271 }
4272
Eric Laurentbfb1b832013-01-07 09:53:42 -08004273 if (exitPending()) {
4274 break;
4275 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004276 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
4277 mWriteAckSequence, mDrainSequence);
4278 writeAckSequence = mWriteAckSequence;
4279 mWriteAckSequence &= ~1;
4280 drainSequence = mDrainSequence;
4281 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004282 }
4283 {
Eric Laurent4de95592013-09-26 15:28:21 -07004284 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
4285 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004286 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004287 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004288 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004289 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004290 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004291 }
4292 }
4293 }
4294 }
4295 return false;
4296}
4297
4298void AudioFlinger::AsyncCallbackThread::exit()
4299{
4300 ALOGV("AsyncCallbackThread::exit");
4301 Mutex::Autolock _l(mLock);
4302 requestExit();
4303 mWaitWorkCV.broadcast();
4304}
4305
Eric Laurent3b4529e2013-09-05 18:09:19 -07004306void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004307{
4308 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004309 // bit 0 is cleared
4310 mWriteAckSequence = sequence << 1;
4311}
4312
4313void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
4314{
4315 Mutex::Autolock _l(mLock);
4316 // ignore unexpected callbacks
4317 if (mWriteAckSequence & 2) {
4318 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004319 mWaitWorkCV.signal();
4320 }
4321}
4322
Eric Laurent3b4529e2013-09-05 18:09:19 -07004323void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004324{
4325 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004326 // bit 0 is cleared
4327 mDrainSequence = sequence << 1;
4328}
4329
4330void AudioFlinger::AsyncCallbackThread::resetDraining()
4331{
4332 Mutex::Autolock _l(mLock);
4333 // ignore unexpected callbacks
4334 if (mDrainSequence & 2) {
4335 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004336 mWaitWorkCV.signal();
4337 }
4338}
4339
4340
4341// ----------------------------------------------------------------------------
4342AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
4343 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
4344 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD),
4345 mHwPaused(false),
Eric Laurentea0fade2013-10-04 16:23:48 -07004346 mFlushPending(false),
Eric Laurentd7e59222013-11-15 12:02:28 -08004347 mPausedBytesRemaining(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004348{
Eric Laurentfd477972013-10-25 18:10:40 -07004349 //FIXME: mStandby should be set to true by ThreadBase constructor
4350 mStandby = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004351}
4352
Eric Laurentbfb1b832013-01-07 09:53:42 -08004353void AudioFlinger::OffloadThread::threadLoop_exit()
4354{
4355 if (mFlushPending || mHwPaused) {
4356 // If a flush is pending or track was paused, just discard buffered data
4357 flushHw_l();
4358 } else {
4359 mMixerStatus = MIXER_DRAIN_ALL;
4360 threadLoop_drain();
4361 }
Uday Gupta56604aa2014-05-13 11:19:17 -07004362 if (mUseAsyncWrite) {
4363 ALOG_ASSERT(mCallbackThread != 0);
4364 mCallbackThread->exit();
4365 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004366 PlaybackThread::threadLoop_exit();
4367}
4368
4369AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
4370 Vector< sp<Track> > *tracksToRemove
4371)
4372{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004373 size_t count = mActiveTracks.size();
4374
4375 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07004376 bool doHwPause = false;
4377 bool doHwResume = false;
4378
Eric Laurentede6c3b2013-09-19 14:37:46 -07004379 ALOGV("OffloadThread::prepareTracks_l active tracks %d", count);
4380
Eric Laurentbfb1b832013-01-07 09:53:42 -08004381 // find out which tracks need to be processed
4382 for (size_t i = 0; i < count; i++) {
4383 sp<Track> t = mActiveTracks[i].promote();
4384 // The track died recently
4385 if (t == 0) {
4386 continue;
4387 }
4388 Track* const track = t.get();
4389 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07004390 // Only consider last track started for volume and mixer state control.
4391 // In theory an older track could underrun and restart after the new one starts
4392 // but as we only care about the transition phase between two tracks on a
4393 // direct output, it is not a problem to ignore the underrun case.
4394 sp<Track> l = mLatestActiveTrack.promote();
4395 bool last = l.get() == track;
4396
Haynes Mathew George7844f672014-01-15 12:32:55 -08004397 if (track->isInvalid()) {
4398 ALOGW("An invalidated track shouldn't be in active list");
4399 tracksToRemove->add(track);
4400 continue;
4401 }
4402
4403 if (track->mState == TrackBase::IDLE) {
4404 ALOGW("An idle track shouldn't be in active list");
4405 continue;
4406 }
4407
Eric Laurentbfb1b832013-01-07 09:53:42 -08004408 if (track->isPausing()) {
4409 track->setPaused();
4410 if (last) {
4411 if (!mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07004412 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004413 mHwPaused = true;
4414 }
4415 // If we were part way through writing the mixbuffer to
4416 // the HAL we must save this until we resume
4417 // BUG - this will be wrong if a different track is made active,
4418 // in that case we want to discard the pending data in the
4419 // mixbuffer and tell the client to present it again when the
4420 // track is resumed
4421 mPausedWriteLength = mCurrentWriteLength;
4422 mPausedBytesRemaining = mBytesRemaining;
4423 mBytesRemaining = 0; // stop writing
4424 }
4425 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08004426 } else if (track->isFlushPending()) {
4427 track->flushAck();
4428 if (last) {
4429 mFlushPending = true;
4430 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08004431 } else if (track->isResumePending()){
4432 track->resumeAck();
4433 if (last) {
4434 if (mPausedBytesRemaining) {
4435 // Need to continue write that was interrupted
4436 mCurrentWriteLength = mPausedWriteLength;
4437 mBytesRemaining = mPausedBytesRemaining;
4438 mPausedBytesRemaining = 0;
4439 }
4440 if (mHwPaused) {
4441 doHwResume = true;
4442 mHwPaused = false;
4443 // threadLoop_mix() will handle the case that we need to
4444 // resume an interrupted write
4445 }
4446 // enable write to audio HAL
4447 sleepTime = 0;
4448
4449 // Do not handle new data in this iteration even if track->framesReady()
4450 mixerStatus = MIXER_TRACKS_ENABLED;
4451 }
4452 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07004453 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004454 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004455 if (track->mFillingUpStatus == Track::FS_FILLED) {
4456 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004457 // make sure processVolume_l() will apply new volume even if 0
4458 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004459 }
4460
4461 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08004462 sp<Track> previousTrack = mPreviousTrack.promote();
4463 if (previousTrack != 0) {
4464 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08004465 // Flush any data still being written from last track
4466 mBytesRemaining = 0;
4467 if (mPausedBytesRemaining) {
4468 // Last track was paused so we also need to flush saved
4469 // mixbuffer state and invalidate track so that it will
4470 // re-submit that unwritten data when it is next resumed
4471 mPausedBytesRemaining = 0;
4472 // Invalidate is a bit drastic - would be more efficient
4473 // to have a flag to tell client that some of the
4474 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08004475 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004476 }
4477 // flush data already sent to the DSP if changing audio session as audio
4478 // comes from a different source. Also invalidate previous track to force a
4479 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08004480 if (previousTrack->sessionId() != track->sessionId()) {
4481 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004482 }
4483 }
4484 }
4485 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004486 // reset retry count
4487 track->mRetryCount = kMaxTrackRetriesOffload;
4488 mActiveTrack = t;
4489 mixerStatus = MIXER_TRACKS_READY;
4490 }
4491 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004492 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004493 if (track->isStopping_1()) {
4494 // Hardware buffer can hold a large amount of audio so we must
4495 // wait for all current track's data to drain before we say
4496 // that the track is stopped.
4497 if (mBytesRemaining == 0) {
4498 // Only start draining when all data in mixbuffer
4499 // has been written
4500 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
4501 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004502 // do not drain if no data was ever sent to HAL (mStandby == true)
4503 if (last && !mStandby) {
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004504 // do not modify drain sequence if we are already draining. This happens
4505 // when resuming from pause after drain.
4506 if ((mDrainSequence & 1) == 0) {
4507 sleepTime = 0;
4508 standbyTime = systemTime() + standbyDelay;
4509 mixerStatus = MIXER_DRAIN_TRACK;
4510 mDrainSequence += 2;
4511 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004512 if (mHwPaused) {
4513 // It is possible to move from PAUSED to STOPPING_1 without
4514 // a resume so we must ensure hardware is running
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004515 doHwResume = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004516 mHwPaused = false;
4517 }
4518 }
4519 }
4520 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004521 // Drain has completed or we are in standby, signal presentation complete
4522 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004523 track->mState = TrackBase::STOPPED;
4524 size_t audioHALFrames =
4525 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
4526 size_t framesWritten =
Eric Laurent665470b2014-07-03 16:37:08 -07004527 mBytesWritten / audio_stream_out_frame_size(mOutput->stream);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004528 track->presentationComplete(framesWritten, audioHALFrames);
4529 track->reset();
4530 tracksToRemove->add(track);
4531 }
4532 } else {
4533 // No buffers for this track. Give it a few chances to
4534 // fill a buffer, then remove it from active list.
4535 if (--(track->mRetryCount) <= 0) {
4536 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
4537 track->name());
4538 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004539 // indicate to client process that the track was disabled because of underrun;
4540 // it will then automatically call start() when data is available
4541 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004542 } else if (last){
4543 mixerStatus = MIXER_TRACKS_ENABLED;
4544 }
4545 }
4546 }
4547 // compute volume for this track
4548 processVolume_l(track, last);
4549 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004550
Eric Laurentea0fade2013-10-04 16:23:48 -07004551 // make sure the pause/flush/resume sequence is executed in the right order.
4552 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4553 // before flush and then resume HW. This can happen in case of pause/flush/resume
4554 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07004555 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurent972a1732013-09-04 09:42:59 -07004556 mOutput->stream->pause(mOutput->stream);
4557 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004558 if (mFlushPending) {
4559 flushHw_l();
4560 mFlushPending = false;
4561 }
Eric Laurentfd477972013-10-25 18:10:40 -07004562 if (!mStandby && doHwResume) {
Eric Laurent972a1732013-09-04 09:42:59 -07004563 mOutput->stream->resume(mOutput->stream);
4564 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004565
Eric Laurentbfb1b832013-01-07 09:53:42 -08004566 // remove all the tracks that need to be...
4567 removeTracks_l(*tracksToRemove);
4568
4569 return mixerStatus;
4570}
4571
Eric Laurentbfb1b832013-01-07 09:53:42 -08004572// must be called with thread mutex locked
4573bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
4574{
Eric Laurent3b4529e2013-09-05 18:09:19 -07004575 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
4576 mWriteAckSequence, mDrainSequence);
4577 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004578 return true;
4579 }
4580 return false;
4581}
4582
4583// must be called with thread mutex locked
4584bool AudioFlinger::OffloadThread::shouldStandby_l()
4585{
Glenn Kastene6f35b12013-08-19 09:58:50 -07004586 bool trackPaused = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004587
4588 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4589 // after a timeout and we will enter standby then.
4590 if (mTracks.size() > 0) {
Glenn Kastene6f35b12013-08-19 09:58:50 -07004591 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004592 }
4593
Glenn Kastene6f35b12013-08-19 09:58:50 -07004594 return !mStandby && !trackPaused;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004595}
4596
4597
4598bool AudioFlinger::OffloadThread::waitingAsyncCallback()
4599{
4600 Mutex::Autolock _l(mLock);
4601 return waitingAsyncCallback_l();
4602}
4603
4604void AudioFlinger::OffloadThread::flushHw_l()
4605{
Eric Laurente659ef42014-09-29 13:06:46 -07004606 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004607 // Flush anything still waiting in the mixbuffer
4608 mCurrentWriteLength = 0;
4609 mBytesRemaining = 0;
4610 mPausedWriteLength = 0;
4611 mPausedBytesRemaining = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08004612 mHwPaused = false;
4613
Eric Laurentbfb1b832013-01-07 09:53:42 -08004614 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004615 // discard any pending drain or write ack by incrementing sequence
4616 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4617 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004618 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004619 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4620 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004621 }
4622}
4623
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08004624void AudioFlinger::OffloadThread::onAddNewTrack_l()
4625{
4626 sp<Track> previousTrack = mPreviousTrack.promote();
4627 sp<Track> latestTrack = mLatestActiveTrack.promote();
4628
4629 if (previousTrack != 0 && latestTrack != 0 &&
4630 (previousTrack->sessionId() != latestTrack->sessionId())) {
4631 mFlushPending = true;
4632 }
4633 PlaybackThread::onAddNewTrack_l();
4634}
4635
Eric Laurentbfb1b832013-01-07 09:53:42 -08004636// ----------------------------------------------------------------------------
4637
Eric Laurent81784c32012-11-19 14:55:58 -08004638AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
4639 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
4640 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
4641 DUPLICATING),
4642 mWaitTimeMs(UINT_MAX)
4643{
4644 addOutputTrack(mainThread);
4645}
4646
4647AudioFlinger::DuplicatingThread::~DuplicatingThread()
4648{
4649 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4650 mOutputTracks[i]->destroy();
4651 }
4652}
4653
4654void AudioFlinger::DuplicatingThread::threadLoop_mix()
4655{
4656 // mix buffers...
4657 if (outputsReady(outputTracks)) {
4658 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
4659 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08004660 if (mMixerBufferValid) {
4661 memset(mMixerBuffer, 0, mMixerBufferSize);
4662 } else {
4663 memset(mSinkBuffer, 0, mSinkBufferSize);
4664 }
Eric Laurent81784c32012-11-19 14:55:58 -08004665 }
4666 sleepTime = 0;
4667 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08004668 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004669 standbyTime = systemTime() + standbyDelay;
4670}
4671
4672void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
4673{
4674 if (sleepTime == 0) {
4675 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4676 sleepTime = activeSleepTime;
4677 } else {
4678 sleepTime = idleSleepTime;
4679 }
4680 } else if (mBytesWritten != 0) {
4681 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4682 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08004683 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004684 } else {
4685 // flush remaining overflow buffers in output tracks
4686 writeFrames = 0;
4687 }
4688 sleepTime = 0;
4689 }
4690}
4691
Eric Laurentbfb1b832013-01-07 09:53:42 -08004692ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004693{
Haynes Mathew Georgeec0eeaf2014-11-20 11:32:27 -08004694 // We convert the duplicating thread format to AUDIO_FORMAT_PCM_16_BIT
4695 // for delivery downstream as needed. This in-place conversion is safe as
4696 // AUDIO_FORMAT_PCM_16_BIT is smaller than any other supported format
4697 // (AUDIO_FORMAT_PCM_8_BIT is not allowed here).
4698 if (mFormat != AUDIO_FORMAT_PCM_16_BIT) {
4699 memcpy_by_audio_format(mSinkBuffer, AUDIO_FORMAT_PCM_16_BIT,
4700 mSinkBuffer, mFormat, writeFrames * mChannelCount);
4701 }
Eric Laurent81784c32012-11-19 14:55:58 -08004702 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung010a1a12014-03-13 13:57:33 -07004703 outputTracks[i]->write(reinterpret_cast<int16_t*>(mSinkBuffer), writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08004704 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07004705 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08004706 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004707}
4708
4709void AudioFlinger::DuplicatingThread::threadLoop_standby()
4710{
4711 // DuplicatingThread implements standby by stopping all tracks
4712 for (size_t i = 0; i < outputTracks.size(); i++) {
4713 outputTracks[i]->stop();
4714 }
4715}
4716
4717void AudioFlinger::DuplicatingThread::saveOutputTracks()
4718{
4719 outputTracks = mOutputTracks;
4720}
4721
4722void AudioFlinger::DuplicatingThread::clearOutputTracks()
4723{
4724 outputTracks.clear();
4725}
4726
4727void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
4728{
4729 Mutex::Autolock _l(mLock);
4730 // FIXME explain this formula
4731 size_t frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
Andy Hung010a1a12014-03-13 13:57:33 -07004732 // OutputTrack is forced to AUDIO_FORMAT_PCM_16_BIT regardless of mFormat
4733 // due to current usage case and restrictions on the AudioBufferProvider.
4734 // Actual buffer conversion is done in threadLoop_write().
4735 //
4736 // TODO: This may change in the future, depending on multichannel
4737 // (and non int16_t*) support on AF::PlaybackThread::OutputTrack
Eric Laurent81784c32012-11-19 14:55:58 -08004738 OutputTrack *outputTrack = new OutputTrack(thread,
4739 this,
4740 mSampleRate,
Andy Hung010a1a12014-03-13 13:57:33 -07004741 AUDIO_FORMAT_PCM_16_BIT,
Eric Laurent81784c32012-11-19 14:55:58 -08004742 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004743 frameCount,
4744 IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08004745 if (outputTrack->cblk() != NULL) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004746 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
Eric Laurent81784c32012-11-19 14:55:58 -08004747 mOutputTracks.add(outputTrack);
4748 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
4749 updateWaitTime_l();
4750 }
4751}
4752
4753void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
4754{
4755 Mutex::Autolock _l(mLock);
4756 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4757 if (mOutputTracks[i]->thread() == thread) {
4758 mOutputTracks[i]->destroy();
4759 mOutputTracks.removeAt(i);
4760 updateWaitTime_l();
4761 return;
4762 }
4763 }
4764 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
4765}
4766
4767// caller must hold mLock
4768void AudioFlinger::DuplicatingThread::updateWaitTime_l()
4769{
4770 mWaitTimeMs = UINT_MAX;
4771 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4772 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
4773 if (strong != 0) {
4774 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4775 if (waitTimeMs < mWaitTimeMs) {
4776 mWaitTimeMs = waitTimeMs;
4777 }
4778 }
4779 }
4780}
4781
4782
4783bool AudioFlinger::DuplicatingThread::outputsReady(
4784 const SortedVector< sp<OutputTrack> > &outputTracks)
4785{
4786 for (size_t i = 0; i < outputTracks.size(); i++) {
4787 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
4788 if (thread == 0) {
4789 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
4790 outputTracks[i].get());
4791 return false;
4792 }
4793 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4794 // see note at standby() declaration
4795 if (playbackThread->standby() && !playbackThread->isSuspended()) {
4796 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
4797 thread.get());
4798 return false;
4799 }
4800 }
4801 return true;
4802}
4803
4804uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
4805{
4806 return (mWaitTimeMs * 1000) / 2;
4807}
4808
4809void AudioFlinger::DuplicatingThread::cacheParameters_l()
4810{
4811 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
4812 updateWaitTime_l();
4813
4814 MixerThread::cacheParameters_l();
4815}
4816
4817// ----------------------------------------------------------------------------
4818// Record
4819// ----------------------------------------------------------------------------
4820
4821AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4822 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08004823 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08004824 audio_devices_t outDevice,
Glenn Kasten46909e72013-02-26 09:20:22 -08004825 audio_devices_t inDevice
4826#ifdef TEE_SINK
4827 , const sp<NBAIO_Sink>& teeSink
4828#endif
4829 ) :
Eric Laurentd3922f72013-02-01 17:57:04 -08004830 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD),
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004831 mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
Glenn Kastendeca2ae2014-02-07 10:25:56 -08004832 // mRsmpInFrames and mRsmpInFramesP2 are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08004833 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08004834#ifdef TEE_SINK
4835 , mTeeSink(teeSink)
4836#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07004837 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
4838 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07004839 // mFastCapture below
4840 , mFastCaptureFutex(0)
4841 // mInputSource
4842 // mPipeSink
4843 // mPipeSource
4844 , mPipeFramesP2(0)
4845 // mPipeMemory
4846 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07004847 , mFastTrackAvail(false)
Eric Laurent81784c32012-11-19 14:55:58 -08004848{
4849 snprintf(mName, kNameLength, "AudioIn_%X", id);
Glenn Kasten481fb672013-09-30 14:39:28 -07004850 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mName);
Eric Laurent81784c32012-11-19 14:55:58 -08004851
Glenn Kastendeca2ae2014-02-07 10:25:56 -08004852 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07004853
4854 // create an NBAIO source for the HAL input stream, and negotiate
4855 mInputSource = new AudioStreamInSource(input->stream);
4856 size_t numCounterOffers = 0;
4857 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
4858 ssize_t index = mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
4859 ALOG_ASSERT(index == 0);
4860
4861 // initialize fast capture depending on configuration
4862 bool initFastCapture;
4863 switch (kUseFastCapture) {
4864 case FastCapture_Never:
4865 initFastCapture = false;
4866 break;
4867 case FastCapture_Always:
4868 initFastCapture = true;
4869 break;
4870 case FastCapture_Static:
4871 uint32_t primaryOutputSampleRate;
4872 {
4873 AutoMutex _l(audioFlinger->mHardwareLock);
4874 primaryOutputSampleRate = audioFlinger->mPrimaryOutputSampleRate;
4875 }
4876 initFastCapture =
4877 // either capture sample rate is same as (a reasonable) primary output sample rate
4878 (((primaryOutputSampleRate == 44100 || primaryOutputSampleRate == 48000) &&
4879 (mSampleRate == primaryOutputSampleRate)) ||
4880 // or primary output sample rate is unknown, and capture sample rate is reasonable
4881 ((primaryOutputSampleRate == 0) &&
4882 ((mSampleRate == 44100 || mSampleRate == 48000)))) &&
Glenn Kasten9f81de32014-07-27 15:02:23 -07004883 // and the buffer size is < 12 ms
4884 (mFrameCount * 1000) / mSampleRate < 12;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07004885 break;
4886 // case FastCapture_Dynamic:
4887 }
4888
4889 if (initFastCapture) {
4890 // create a Pipe for FastMixer to write to, and for us and fast tracks to read from
4891 NBAIO_Format format = mInputSource->format();
Glenn Kasten49d00ad2014-07-21 11:22:03 -07004892 size_t pipeFramesP2 = roundup(mSampleRate / 25); // double-buffering of 20 ms each
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07004893 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
4894 void *pipeBuffer;
4895 const sp<MemoryDealer> roHeap(readOnlyHeap());
4896 sp<IMemory> pipeMemory;
4897 if ((roHeap == 0) ||
4898 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
4899 (pipeBuffer = pipeMemory->pointer()) == NULL) {
4900 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
4901 goto failed;
4902 }
4903 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
4904 memset(pipeBuffer, 0, pipeSize);
4905 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
4906 const NBAIO_Format offers[1] = {format};
4907 size_t numCounterOffers = 0;
4908 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
4909 ALOG_ASSERT(index == 0);
4910 mPipeSink = pipe;
4911 PipeReader *pipeReader = new PipeReader(*pipe);
4912 numCounterOffers = 0;
4913 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
4914 ALOG_ASSERT(index == 0);
4915 mPipeSource = pipeReader;
4916 mPipeFramesP2 = pipeFramesP2;
4917 mPipeMemory = pipeMemory;
4918
4919 // create fast capture
4920 mFastCapture = new FastCapture();
4921 FastCaptureStateQueue *sq = mFastCapture->sq();
4922#ifdef STATE_QUEUE_DUMP
4923 // FIXME
4924#endif
4925 FastCaptureState *state = sq->begin();
4926 state->mCblk = NULL;
4927 state->mInputSource = mInputSource.get();
4928 state->mInputSourceGen++;
4929 state->mPipeSink = pipe;
4930 state->mPipeSinkGen++;
4931 state->mFrameCount = mFrameCount;
4932 state->mCommand = FastCaptureState::COLD_IDLE;
4933 // already done in constructor initialization list
4934 //mFastCaptureFutex = 0;
4935 state->mColdFutexAddr = &mFastCaptureFutex;
4936 state->mColdGen++;
4937 state->mDumpState = &mFastCaptureDumpState;
4938#ifdef TEE_SINK
4939 // FIXME
4940#endif
4941 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
4942 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
4943 sq->end();
4944 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
4945
4946 // start the fast capture
4947 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
4948 pid_t tid = mFastCapture->getTid();
4949 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
4950 if (err != 0) {
4951 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
4952 kPriorityFastCapture, getpid_cached, tid, err);
4953 }
4954
4955#ifdef AUDIO_WATCHDOG
4956 // FIXME
4957#endif
4958
Glenn Kasten6e6704c2014-07-03 10:20:00 -07004959 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07004960 }
4961failed: ;
4962
4963 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08004964}
4965
4966
4967AudioFlinger::RecordThread::~RecordThread()
4968{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07004969 if (mFastCapture != 0) {
4970 FastCaptureStateQueue *sq = mFastCapture->sq();
4971 FastCaptureState *state = sq->begin();
4972 if (state->mCommand == FastCaptureState::COLD_IDLE) {
4973 int32_t old = android_atomic_inc(&mFastCaptureFutex);
4974 if (old == -1) {
4975 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
4976 }
4977 }
4978 state->mCommand = FastCaptureState::EXIT;
4979 sq->end();
4980 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
4981 mFastCapture->join();
4982 mFastCapture.clear();
4983 }
4984 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07004985 mAudioFlinger->unregisterWriter(mNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08004986 delete[] mRsmpInBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004987}
4988
4989void AudioFlinger::RecordThread::onFirstRef()
4990{
4991 run(mName, PRIORITY_URGENT_AUDIO);
4992}
4993
Eric Laurent81784c32012-11-19 14:55:58 -08004994bool AudioFlinger::RecordThread::threadLoop()
4995{
Eric Laurent81784c32012-11-19 14:55:58 -08004996 nsecs_t lastWarning = 0;
4997
4998 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08004999
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005000reacquire_wakelock:
5001 sp<RecordTrack> activeTrack;
Glenn Kasten2b806402013-11-20 16:37:38 -08005002 int activeTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005003 {
5004 Mutex::Autolock _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005005 size_t size = mActiveTracks.size();
5006 activeTracksGen = mActiveTracksGen;
5007 if (size > 0) {
5008 // FIXME an arbitrary choice
5009 activeTrack = mActiveTracks[0];
5010 acquireWakeLock_l(activeTrack->uid());
5011 if (size > 1) {
5012 SortedVector<int> tmp;
5013 for (size_t i = 0; i < size; i++) {
5014 tmp.add(mActiveTracks[i]->uid());
5015 }
5016 updateWakeLockUids_l(tmp);
5017 }
5018 } else {
5019 acquireWakeLock_l(-1);
5020 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005021 }
5022
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005023 // used to request a deferred sleep, to be executed later while mutex is unlocked
5024 uint32_t sleepUs = 0;
5025
5026 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005027 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005028 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07005029
Glenn Kasten5edadd42013-08-14 16:30:49 -07005030 // sleep with mutex unlocked
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005031 if (sleepUs > 0) {
5032 usleep(sleepUs);
5033 sleepUs = 0;
Glenn Kasten5edadd42013-08-14 16:30:49 -07005034 }
5035
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005036 // activeTracks accumulates a copy of a subset of mActiveTracks
5037 Vector< sp<RecordTrack> > activeTracks;
5038
Glenn Kasten735f45f2014-08-18 15:51:59 -07005039 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005040 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07005041
Glenn Kasten735f45f2014-08-18 15:51:59 -07005042 // reference to a fast track which is about to be removed
5043 sp<RecordTrack> fastTrackToRemove;
5044
Eric Laurent81784c32012-11-19 14:55:58 -08005045 { // scope for mLock
5046 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08005047
Eric Laurent021cf962014-05-13 10:18:14 -07005048 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005049
Eric Laurent000a4192014-01-29 15:17:32 -08005050 // check exitPending here because checkForNewParameters_l() and
5051 // checkForNewParameters_l() can temporarily release mLock
5052 if (exitPending()) {
5053 break;
5054 }
5055
Glenn Kasten2b806402013-11-20 16:37:38 -08005056 // if no active track(s), then standby and release wakelock
5057 size_t size = mActiveTracks.size();
5058 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07005059 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005060 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08005061 releaseWakeLock_l();
5062 ALOGV("RecordThread: loop stopping");
5063 // go to sleep
5064 mWaitWorkCV.wait(mLock);
5065 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005066 goto reacquire_wakelock;
5067 }
5068
Glenn Kasten2b806402013-11-20 16:37:38 -08005069 if (mActiveTracksGen != activeTracksGen) {
5070 activeTracksGen = mActiveTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005071 SortedVector<int> tmp;
Glenn Kasten2b806402013-11-20 16:37:38 -08005072 for (size_t i = 0; i < size; i++) {
5073 tmp.add(mActiveTracks[i]->uid());
5074 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005075 updateWakeLockUids_l(tmp);
Eric Laurent81784c32012-11-19 14:55:58 -08005076 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005077
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005078 bool doBroadcast = false;
5079 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07005080
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005081 activeTrack = mActiveTracks[i];
5082 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07005083 if (activeTrack->isFastTrack()) {
5084 ALOG_ASSERT(fastTrackToRemove == 0);
5085 fastTrackToRemove = activeTrack;
5086 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005087 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08005088 mActiveTracks.remove(activeTrack);
5089 mActiveTracksGen++;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005090 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07005091 continue;
5092 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005093
5094 TrackBase::track_state activeTrackState = activeTrack->mState;
5095 switch (activeTrackState) {
5096
5097 case TrackBase::PAUSING:
5098 mActiveTracks.remove(activeTrack);
5099 mActiveTracksGen++;
5100 doBroadcast = true;
5101 size--;
5102 continue;
5103
5104 case TrackBase::STARTING_1:
5105 sleepUs = 10000;
5106 i++;
5107 continue;
5108
5109 case TrackBase::STARTING_2:
5110 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005111 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07005112 activeTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005113 break;
5114
5115 case TrackBase::ACTIVE:
5116 break;
5117
5118 case TrackBase::IDLE:
5119 i++;
5120 continue;
5121
5122 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08005123 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07005124 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005125
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005126 activeTracks.add(activeTrack);
5127 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07005128
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005129 if (activeTrack->isFastTrack()) {
5130 ALOG_ASSERT(!mFastTrackAvail);
5131 ALOG_ASSERT(fastTrack == 0);
5132 fastTrack = activeTrack;
5133 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005134 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005135 if (doBroadcast) {
5136 mStartStopCond.broadcast();
5137 }
5138
5139 // sleep if there are no active tracks to process
5140 if (activeTracks.size() == 0) {
5141 if (sleepUs == 0) {
5142 sleepUs = kRecordThreadSleepUs;
5143 }
5144 continue;
5145 }
5146 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07005147
Eric Laurent81784c32012-11-19 14:55:58 -08005148 lockEffectChains_l(effectChains);
5149 }
5150
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005151 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07005152
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005153 size_t size = effectChains.size();
5154 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005155 // thread mutex is not locked, but effect chain is locked
5156 effectChains[i]->process_l();
5157 }
5158
Glenn Kasten735f45f2014-08-18 15:51:59 -07005159 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005160 if (mFastCapture != 0) {
5161 FastCaptureStateQueue *sq = mFastCapture->sq();
5162 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07005163 bool didModify = false;
5164 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005165 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
5166 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
5167 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5168 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5169 if (old == -1) {
5170 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5171 }
5172 }
5173 state->mCommand = FastCaptureState::READ_WRITE;
5174#if 0 // FIXME
5175 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
5176 FastCaptureDumpState::kSamplingNforLowRamDevice : FastMixerDumpState::kSamplingN);
5177#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07005178 didModify = true;
5179 }
5180 audio_track_cblk_t *cblkOld = state->mCblk;
5181 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
5182 if (cblkNew != cblkOld) {
5183 state->mCblk = cblkNew;
5184 // block until acked if removing a fast track
5185 if (cblkOld != NULL) {
5186 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
5187 }
5188 didModify = true;
5189 }
5190 sq->end(didModify);
5191 if (didModify) {
5192 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005193#if 0
5194 if (kUseFastCapture == FastCapture_Dynamic) {
5195 mNormalSource = mPipeSource;
5196 }
5197#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005198 }
5199 }
5200
Glenn Kasten735f45f2014-08-18 15:51:59 -07005201 // now run the fast track destructor with thread mutex unlocked
5202 fastTrackToRemove.clear();
5203
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005204 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
5205 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
5206 // slow, then this RecordThread will overrun by not calling HAL read often enough.
5207 // If destination is non-contiguous, first read past the nominal end of buffer, then
5208 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005209
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005210 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005211 ssize_t framesRead;
5212
5213 // If an NBAIO source is present, use it to read the normal capture's data
5214 if (mPipeSource != 0) {
5215 size_t framesToRead = mBufferSize / mFrameSize;
5216 framesRead = mPipeSource->read(&mRsmpInBuffer[rear * mChannelCount],
5217 framesToRead, AudioBufferProvider::kInvalidPTS);
5218 if (framesRead == 0) {
5219 // since pipe is non-blocking, simulate blocking input
5220 sleepUs = (framesToRead * 1000000LL) / mSampleRate;
5221 }
5222 // otherwise use the HAL / AudioStreamIn directly
5223 } else {
5224 ssize_t bytesRead = mInput->stream->read(mInput->stream,
5225 &mRsmpInBuffer[rear * mChannelCount], mBufferSize);
5226 if (bytesRead < 0) {
5227 framesRead = bytesRead;
5228 } else {
5229 framesRead = bytesRead / mFrameSize;
5230 }
5231 }
5232
5233 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
5234 ALOGE("read failed: framesRead=%d", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005235 // Force input into standby so that it tries to recover at next read attempt
5236 inputStandBy();
5237 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005238 }
5239 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005240 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005241 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005242 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005243
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005244 if (mTeeSink != 0) {
5245 (void) mTeeSink->write(&mRsmpInBuffer[rear * mChannelCount], framesRead);
5246 }
5247 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005248 {
5249 size_t part1 = mRsmpInFramesP2 - rear;
5250 if ((size_t) framesRead > part1) {
5251 memcpy(mRsmpInBuffer, &mRsmpInBuffer[mRsmpInFramesP2 * mChannelCount],
5252 (framesRead - part1) * mFrameSize);
5253 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005254 }
5255 rear = mRsmpInRear += framesRead;
5256
5257 size = activeTracks.size();
5258 // loop over each active track
5259 for (size_t i = 0; i < size; i++) {
5260 activeTrack = activeTracks[i];
5261
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005262 // skip fast tracks, as those are handled directly by FastCapture
5263 if (activeTrack->isFastTrack()) {
5264 continue;
5265 }
5266
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005267 enum {
5268 OVERRUN_UNKNOWN,
5269 OVERRUN_TRUE,
5270 OVERRUN_FALSE
5271 } overrun = OVERRUN_UNKNOWN;
5272
5273 // loop over getNextBuffer to handle circular sink
5274 for (;;) {
5275
5276 activeTrack->mSink.frameCount = ~0;
5277 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
5278 size_t framesOut = activeTrack->mSink.frameCount;
5279 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
5280
5281 int32_t front = activeTrack->mRsmpInFront;
5282 ssize_t filled = rear - front;
5283 size_t framesIn;
5284
5285 if (filled < 0) {
5286 // should not happen, but treat like a massive overrun and re-sync
5287 framesIn = 0;
5288 activeTrack->mRsmpInFront = rear;
5289 overrun = OVERRUN_TRUE;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005290 } else if ((size_t) filled <= mRsmpInFrames) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005291 framesIn = (size_t) filled;
5292 } else {
5293 // client is not keeping up with server, but give it latest data
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005294 framesIn = mRsmpInFrames;
5295 activeTrack->mRsmpInFront = front = rear - framesIn;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005296 overrun = OVERRUN_TRUE;
5297 }
5298
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005299 if (framesOut == 0 || framesIn == 0) {
5300 break;
5301 }
5302
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005303 if (activeTrack->mResampler == NULL) {
5304 // no resampling
5305 if (framesIn > framesOut) {
5306 framesIn = framesOut;
5307 } else {
5308 framesOut = framesIn;
5309 }
5310 int8_t *dst = activeTrack->mSink.i8;
5311 while (framesIn > 0) {
5312 front &= mRsmpInFramesP2 - 1;
5313 size_t part1 = mRsmpInFramesP2 - front;
5314 if (part1 > framesIn) {
5315 part1 = framesIn;
5316 }
5317 int8_t *src = (int8_t *)mRsmpInBuffer + (front * mFrameSize);
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005318 if (mChannelCount == activeTrack->mChannelCount) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005319 memcpy(dst, src, part1 * mFrameSize);
5320 } else if (mChannelCount == 1) {
Glenn Kastencd704212014-07-14 17:26:36 -07005321 upmix_to_stereo_i16_from_mono_i16((int16_t *)dst, (const int16_t *)src,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005322 part1);
5323 } else {
Glenn Kastencd704212014-07-14 17:26:36 -07005324 downmix_to_mono_i16_from_stereo_i16((int16_t *)dst, (const int16_t *)src,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005325 part1);
5326 }
5327 dst += part1 * activeTrack->mFrameSize;
5328 front += part1;
5329 framesIn -= part1;
5330 }
5331 activeTrack->mRsmpInFront += framesOut;
5332
5333 } else {
5334 // resampling
5335 // FIXME framesInNeeded should really be part of resampler API, and should
5336 // depend on the SRC ratio
5337 // to keep mRsmpInBuffer full so resampler always has sufficient input
5338 size_t framesInNeeded;
5339 // FIXME only re-calculate when it changes, and optimize for common ratios
Andy Hung8661aaf2014-07-28 14:38:41 -07005340 // Do not precompute in/out because floating point is not associative
5341 // e.g. a*b/c != a*(b/c).
5342 const double in(mSampleRate);
5343 const double out(activeTrack->mSampleRate);
5344 framesInNeeded = ceil(framesOut * in / out) + 1;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005345 ALOGV("need %u frames in to produce %u out given in/out ratio of %.4g",
Andy Hung8661aaf2014-07-28 14:38:41 -07005346 framesInNeeded, framesOut, in / out);
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005347 // Although we theoretically have framesIn in circular buffer, some of those are
5348 // unreleased frames, and thus must be discounted for purpose of budgeting.
5349 size_t unreleased = activeTrack->mRsmpInUnrel;
5350 framesIn = framesIn > unreleased ? framesIn - unreleased : 0;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005351 if (framesIn < framesInNeeded) {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005352 ALOGV("not enough to resample: have %u frames in but need %u in to "
5353 "produce %u out given in/out ratio of %.4g",
Andy Hung8661aaf2014-07-28 14:38:41 -07005354 framesIn, framesInNeeded, framesOut, in / out);
5355 size_t newFramesOut = framesIn > 0 ? floor((framesIn - 1) * out / in) : 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005356 LOG_ALWAYS_FATAL_IF(newFramesOut >= framesOut);
5357 if (newFramesOut == 0) {
5358 break;
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005359 }
Andy Hung8661aaf2014-07-28 14:38:41 -07005360 framesInNeeded = ceil(newFramesOut * in / out) + 1;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005361 ALOGV("now need %u frames in to produce %u out given out/in ratio of %.4g",
Andy Hung8661aaf2014-07-28 14:38:41 -07005362 framesInNeeded, newFramesOut, out / in);
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005363 LOG_ALWAYS_FATAL_IF(framesIn < framesInNeeded);
5364 ALOGV("success 2: have %u frames in and need %u in to produce %u out "
5365 "given in/out ratio of %.4g",
Andy Hung8661aaf2014-07-28 14:38:41 -07005366 framesIn, framesInNeeded, newFramesOut, in / out);
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005367 framesOut = newFramesOut;
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005368 } else {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005369 ALOGV("success 1: have %u in and need %u in to produce %u out "
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005370 "given in/out ratio of %.4g",
Andy Hung8661aaf2014-07-28 14:38:41 -07005371 framesIn, framesInNeeded, framesOut, in / out);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005372 }
5373
5374 // reallocate mRsmpOutBuffer as needed; we will grow but never shrink
5375 if (activeTrack->mRsmpOutFrameCount < framesOut) {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005376 // FIXME why does each track need it's own mRsmpOutBuffer? can't they share?
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005377 delete[] activeTrack->mRsmpOutBuffer;
5378 // resampler always outputs stereo
5379 activeTrack->mRsmpOutBuffer = new int32_t[framesOut * FCC_2];
5380 activeTrack->mRsmpOutFrameCount = framesOut;
5381 }
5382
5383 // resampler accumulates, but we only have one source track
5384 memset(activeTrack->mRsmpOutBuffer, 0, framesOut * FCC_2 * sizeof(int32_t));
5385 activeTrack->mResampler->resample(activeTrack->mRsmpOutBuffer, framesOut,
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005386 // FIXME how about having activeTrack implement this interface itself?
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005387 activeTrack->mResamplerBufferProvider
5388 /*this*/ /* AudioBufferProvider* */);
5389 // ditherAndClamp() works as long as all buffers returned by
5390 // activeTrack->getNextBuffer() are 32 bit aligned which should be always true.
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005391 if (activeTrack->mChannelCount == 1) {
Andy Hung84a0c6e2014-04-02 11:24:53 -07005392 // temporarily type pun mRsmpOutBuffer from Q4.27 to int16_t
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005393 ditherAndClamp(activeTrack->mRsmpOutBuffer, activeTrack->mRsmpOutBuffer,
5394 framesOut);
5395 // the resampler always outputs stereo samples:
5396 // do post stereo to mono conversion
5397 downmix_to_mono_i16_from_stereo_i16(activeTrack->mSink.i16,
Glenn Kastencd704212014-07-14 17:26:36 -07005398 (const int16_t *)activeTrack->mRsmpOutBuffer, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005399 } else {
5400 ditherAndClamp((int32_t *)activeTrack->mSink.raw,
5401 activeTrack->mRsmpOutBuffer, framesOut);
5402 }
5403 // now done with mRsmpOutBuffer
5404
5405 }
5406
5407 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
5408 overrun = OVERRUN_FALSE;
5409 }
5410
5411 if (activeTrack->mFramesToDrop == 0) {
5412 if (framesOut > 0) {
5413 activeTrack->mSink.frameCount = framesOut;
5414 activeTrack->releaseBuffer(&activeTrack->mSink);
5415 }
5416 } else {
5417 // FIXME could do a partial drop of framesOut
5418 if (activeTrack->mFramesToDrop > 0) {
5419 activeTrack->mFramesToDrop -= framesOut;
5420 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005421 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005422 }
5423 } else {
5424 activeTrack->mFramesToDrop += framesOut;
5425 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
5426 activeTrack->mSyncStartEvent->isCancelled()) {
5427 ALOGW("Synced record %s, session %d, trigger session %d",
5428 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
5429 activeTrack->sessionId(),
5430 (activeTrack->mSyncStartEvent != 0) ?
5431 activeTrack->mSyncStartEvent->triggerSession() : 0);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005432 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005433 }
5434 }
5435 }
5436
5437 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005438 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005439 }
5440 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005441
5442 switch (overrun) {
5443 case OVERRUN_TRUE:
5444 // client isn't retrieving buffers fast enough
5445 if (!activeTrack->setOverflow()) {
5446 nsecs_t now = systemTime();
5447 // FIXME should lastWarning per track?
5448 if ((now - lastWarning) > kWarningThrottleNs) {
5449 ALOGW("RecordThread: buffer overflow");
5450 lastWarning = now;
5451 }
5452 }
5453 break;
5454 case OVERRUN_FALSE:
5455 activeTrack->clearOverflow();
5456 break;
5457 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005458 break;
5459 }
5460
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005461 }
5462
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005463unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08005464 // enable changes in effect chain
5465 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005466 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08005467 }
5468
Glenn Kasten93e471f2013-08-19 08:40:07 -07005469 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08005470
5471 {
5472 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07005473 for (size_t i = 0; i < mTracks.size(); i++) {
5474 sp<RecordTrack> track = mTracks[i];
5475 track->invalidate();
5476 }
Glenn Kasten2b806402013-11-20 16:37:38 -08005477 mActiveTracks.clear();
5478 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08005479 mStartStopCond.broadcast();
5480 }
5481
5482 releaseWakeLock();
5483
5484 ALOGV("RecordThread %p exiting", this);
5485 return false;
5486}
5487
Glenn Kasten93e471f2013-08-19 08:40:07 -07005488void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08005489{
5490 if (!mStandby) {
5491 inputStandBy();
5492 mStandby = true;
5493 }
5494}
5495
5496void AudioFlinger::RecordThread::inputStandBy()
5497{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005498 // Idle the fast capture if it's currently running
5499 if (mFastCapture != 0) {
5500 FastCaptureStateQueue *sq = mFastCapture->sq();
5501 FastCaptureState *state = sq->begin();
5502 if (!(state->mCommand & FastCaptureState::IDLE)) {
5503 state->mCommand = FastCaptureState::COLD_IDLE;
5504 state->mColdFutexAddr = &mFastCaptureFutex;
5505 state->mColdGen++;
5506 mFastCaptureFutex = 0;
5507 sq->end();
5508 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
5509 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
5510#if 0
5511 if (kUseFastCapture == FastCapture_Dynamic) {
5512 // FIXME
5513 }
5514#endif
5515#ifdef AUDIO_WATCHDOG
5516 // FIXME
5517#endif
5518 } else {
5519 sq->end(false /*didModify*/);
5520 }
5521 }
Eric Laurent81784c32012-11-19 14:55:58 -08005522 mInput->stream->common.standby(&mInput->stream->common);
5523}
5524
Glenn Kasten05997e22014-03-13 15:08:33 -07005525// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07005526sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08005527 const sp<AudioFlinger::Client>& client,
5528 uint32_t sampleRate,
5529 audio_format_t format,
5530 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08005531 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08005532 int sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07005533 size_t *notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005534 int uid,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07005535 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08005536 pid_t tid,
5537 status_t *status)
5538{
Glenn Kasten74935e42013-12-19 08:56:45 -08005539 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005540 sp<RecordTrack> track;
5541 status_t lStatus;
5542
Glenn Kasten90e58b12013-07-31 16:16:02 -07005543 // client expresses a preference for FAST, but we get the final say
5544 if (*flags & IAudioFlinger::TRACK_FAST) {
5545 if (
Glenn Kasten74105912014-07-03 12:28:53 -07005546 // use case: callback handler
5547 (tid != -1) &&
5548 // frame count is not specified, or is exactly the pipe depth
5549 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005550 // PCM data
5551 audio_is_linear_pcm(format) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005552 // native format
5553 (format == mFormat) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005554 // native channel mask
5555 (channelMask == mChannelMask) &&
5556 // native hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07005557 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005558 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005559 hasFastCapture() &&
5560 // there are sufficient fast track slots available
5561 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07005562 ) {
Glenn Kasten74105912014-07-03 12:28:53 -07005563 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%u mFrameCount=%u",
Glenn Kasten90e58b12013-07-31 16:16:02 -07005564 frameCount, mFrameCount);
5565 } else {
Glenn Kasten74105912014-07-03 12:28:53 -07005566 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%u mFrameCount=%u mPipeFramesP2=%u "
5567 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005568 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Glenn Kasten74105912014-07-03 12:28:53 -07005569 frameCount, mFrameCount, mPipeFramesP2,
5570 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
5571 hasFastCapture(), tid, mFastTrackAvail);
Glenn Kasten90e58b12013-07-31 16:16:02 -07005572 *flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kasten74105912014-07-03 12:28:53 -07005573 }
5574 }
5575
5576 // compute track buffer size in frames, and suggest the notification frame count
5577 if (*flags & IAudioFlinger::TRACK_FAST) {
5578 // fast track: frame count is exactly the pipe depth
5579 frameCount = mPipeFramesP2;
5580 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
5581 *notificationFrames = mFrameCount;
5582 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07005583 // not fast track: max notification period is resampled equivalent of one HAL buffer time
5584 // or 20 ms if there is a fast capture
5585 // TODO This could be a roundupRatio inline, and const
5586 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
5587 * sampleRate + mSampleRate - 1) / mSampleRate;
5588 // minimum number of notification periods is at least kMinNotifications,
5589 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
5590 static const size_t kMinNotifications = 3;
5591 static const uint32_t kMinMs = 30;
5592 // TODO This could be a roundupRatio inline
5593 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
5594 // TODO This could be a roundupRatio inline
5595 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
5596 maxNotificationFrames;
5597 const size_t minFrameCount = maxNotificationFrames *
5598 max(kMinNotifications, minNotificationsByMs);
5599 frameCount = max(frameCount, minFrameCount);
5600 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
5601 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07005602 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07005603 }
Glenn Kasten74935e42013-12-19 08:56:45 -08005604 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07005605
Glenn Kasten15e57982013-09-24 11:52:37 -07005606 lStatus = initCheck();
5607 if (lStatus != NO_ERROR) {
5608 ALOGE("createRecordTrack_l() audio driver not initialized");
5609 goto Exit;
5610 }
Eric Laurent81784c32012-11-19 14:55:58 -08005611
5612 { // scope for mLock
5613 Mutex::Autolock _l(mLock);
5614
5615 track = new RecordTrack(this, client, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07005616 format, channelMask, frameCount, NULL, sessionId, uid,
5617 *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08005618
Glenn Kasten03003332013-08-06 15:40:54 -07005619 lStatus = track->initCheck();
5620 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07005621 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08005622 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08005623 goto Exit;
5624 }
5625 mTracks.add(track);
5626
5627 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5628 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
5629 mAudioFlinger->btNrecIsOff();
5630 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
5631 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07005632
5633 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
5634 pid_t callingPid = IPCThreadState::self()->getCallingPid();
5635 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
5636 // so ask activity manager to do this on our behalf
5637 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
5638 }
Eric Laurent81784c32012-11-19 14:55:58 -08005639 }
Glenn Kasten05997e22014-03-13 15:08:33 -07005640
Eric Laurent81784c32012-11-19 14:55:58 -08005641 lStatus = NO_ERROR;
5642
5643Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07005644 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08005645 return track;
5646}
5647
5648status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
5649 AudioSystem::sync_event_t event,
5650 int triggerSession)
5651{
5652 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
5653 sp<ThreadBase> strongMe = this;
5654 status_t status = NO_ERROR;
5655
5656 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005657 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08005658 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005659 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08005660 triggerSession,
5661 recordTrack->sessionId(),
5662 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005663 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08005664 // Sync event can be cancelled by the trigger session if the track is not in a
5665 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005666 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005667 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08005668 } else {
5669 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005670 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005671 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08005672 }
5673 }
5674
5675 {
Glenn Kasten47c20702013-08-13 15:37:35 -07005676 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08005677 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005678 if (mActiveTracks.indexOf(recordTrack) >= 0) {
5679 if (recordTrack->mState == TrackBase::PAUSING) {
5680 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005681 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005682 } else {
5683 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08005684 }
5685 return status;
5686 }
5687
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005688 // TODO consider other ways of handling this, such as changing the state to :STARTING and
5689 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
5690 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005691 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08005692 mActiveTracks.add(recordTrack);
5693 mActiveTracksGen++;
Eric Laurent83b88082014-06-20 18:31:16 -07005694 status_t status = NO_ERROR;
5695 if (recordTrack->isExternalTrack()) {
5696 mLock.unlock();
Eric Laurent4dc68062014-07-28 17:26:49 -07005697 status = AudioSystem::startInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07005698 mLock.lock();
5699 // FIXME should verify that recordTrack is still in mActiveTracks
5700 if (status != NO_ERROR) {
5701 mActiveTracks.remove(recordTrack);
5702 mActiveTracksGen++;
5703 recordTrack->clearSyncStartEvent();
5704 ALOGV("RecordThread::start error %d", status);
5705 return status;
5706 }
Eric Laurent81784c32012-11-19 14:55:58 -08005707 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005708 // Catch up with current buffer indices if thread is already running.
5709 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
5710 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
5711 // see previously buffered data before it called start(), but with greater risk of overrun.
5712
5713 recordTrack->mRsmpInFront = mRsmpInRear;
5714 recordTrack->mRsmpInUnrel = 0;
5715 // FIXME why reset?
5716 if (recordTrack->mResampler != NULL) {
5717 recordTrack->mResampler->reset();
Eric Laurent81784c32012-11-19 14:55:58 -08005718 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005719 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08005720 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08005721 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08005722 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005723 ALOGV("Record failed to start");
5724 status = BAD_VALUE;
5725 goto startError;
5726 }
Eric Laurent81784c32012-11-19 14:55:58 -08005727 return status;
5728 }
Glenn Kasten7c027242012-12-26 14:43:16 -08005729
Eric Laurent81784c32012-11-19 14:55:58 -08005730startError:
Eric Laurent83b88082014-06-20 18:31:16 -07005731 if (recordTrack->isExternalTrack()) {
Eric Laurent4dc68062014-07-28 17:26:49 -07005732 AudioSystem::stopInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07005733 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005734 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005735 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08005736 return status;
5737}
5738
Eric Laurent81784c32012-11-19 14:55:58 -08005739void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
5740{
5741 sp<SyncEvent> strongEvent = event.promote();
5742
5743 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08005744 sp<RefBase> ptr = strongEvent->cookie().promote();
5745 if (ptr != 0) {
5746 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
5747 recordTrack->handleSyncStartEvent(strongEvent);
5748 }
Eric Laurent81784c32012-11-19 14:55:58 -08005749 }
5750}
5751
Glenn Kastena8356f62013-07-25 14:37:52 -07005752bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08005753 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07005754 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005755 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08005756 return false;
5757 }
Glenn Kasten47c20702013-08-13 15:37:35 -07005758 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08005759 recordTrack->mState = TrackBase::PAUSING;
5760 // do not wait for mStartStopCond if exiting
5761 if (exitPending()) {
5762 return true;
5763 }
Glenn Kasten47c20702013-08-13 15:37:35 -07005764 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08005765 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005766 // if we have been restarted, recordTrack is in mActiveTracks here
5767 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005768 ALOGV("Record stopped OK");
5769 return true;
5770 }
5771 return false;
5772}
5773
Glenn Kasten0f11b512014-01-31 16:18:54 -08005774bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08005775{
5776 return false;
5777}
5778
Glenn Kasten0f11b512014-01-31 16:18:54 -08005779status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005780{
5781#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
5782 if (!isValidSyncEvent(event)) {
5783 return BAD_VALUE;
5784 }
5785
5786 int eventSession = event->triggerSession();
5787 status_t ret = NAME_NOT_FOUND;
5788
5789 Mutex::Autolock _l(mLock);
5790
5791 for (size_t i = 0; i < mTracks.size(); i++) {
5792 sp<RecordTrack> track = mTracks[i];
5793 if (eventSession == track->sessionId()) {
5794 (void) track->setSyncEvent(event);
5795 ret = NO_ERROR;
5796 }
5797 }
5798 return ret;
5799#else
5800 return BAD_VALUE;
5801#endif
5802}
5803
5804// destroyTrack_l() must be called with ThreadBase::mLock held
5805void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
5806{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005807 track->terminate();
5808 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08005809 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08005810 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005811 removeTrack_l(track);
5812 }
5813}
5814
5815void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
5816{
5817 mTracks.remove(track);
5818 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005819 if (track->isFastTrack()) {
5820 ALOG_ASSERT(!mFastTrackAvail);
5821 mFastTrackAvail = true;
5822 }
Eric Laurent81784c32012-11-19 14:55:58 -08005823}
5824
5825void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
5826{
5827 dumpInternals(fd, args);
5828 dumpTracks(fd, args);
5829 dumpEffectChains(fd, args);
5830}
5831
5832void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
5833{
Elliott Hughes87cebad2014-05-22 10:14:43 -07005834 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08005835
Glenn Kasten2b806402013-11-20 16:37:38 -08005836 if (mActiveTracks.size() > 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07005837 dprintf(fd, " Buffer size: %zu bytes\n", mBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005838 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07005839 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08005840 }
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005841 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005842 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Eric Laurent81784c32012-11-19 14:55:58 -08005843
Eric Laurent81784c32012-11-19 14:55:58 -08005844 dumpBase(fd, args);
5845}
5846
Glenn Kasten0f11b512014-01-31 16:18:54 -08005847void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005848{
5849 const size_t SIZE = 256;
5850 char buffer[SIZE];
5851 String8 result;
5852
Marco Nelissenb2208842014-02-07 14:00:50 -08005853 size_t numtracks = mTracks.size();
5854 size_t numactive = mActiveTracks.size();
5855 size_t numactiveseen = 0;
Elliott Hughes87cebad2014-05-22 10:14:43 -07005856 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08005857 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07005858 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08005859 RecordTrack::appendDumpHeader(result);
5860 for (size_t i = 0; i < numtracks ; ++i) {
5861 sp<RecordTrack> track = mTracks[i];
5862 if (track != 0) {
5863 bool active = mActiveTracks.indexOf(track) >= 0;
5864 if (active) {
5865 numactiveseen++;
5866 }
5867 track->dump(buffer, SIZE, active);
5868 result.append(buffer);
5869 }
Eric Laurent81784c32012-11-19 14:55:58 -08005870 }
Marco Nelissenb2208842014-02-07 14:00:50 -08005871 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07005872 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08005873 }
5874
Marco Nelissenb2208842014-02-07 14:00:50 -08005875 if (numactiveseen != numactive) {
5876 snprintf(buffer, SIZE, " The following tracks are in the active list but"
5877 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08005878 result.append(buffer);
5879 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08005880 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08005881 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08005882 if (mTracks.indexOf(track) < 0) {
5883 track->dump(buffer, SIZE, true);
5884 result.append(buffer);
5885 }
Glenn Kasten2b806402013-11-20 16:37:38 -08005886 }
Eric Laurent81784c32012-11-19 14:55:58 -08005887
5888 }
5889 write(fd, result.string(), result.size());
5890}
5891
5892// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005893status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
5894 AudioBufferProvider::Buffer* buffer, int64_t pts __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005895{
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005896 RecordTrack *activeTrack = mRecordTrack;
5897 sp<ThreadBase> threadBase = activeTrack->mThread.promote();
5898 if (threadBase == 0) {
5899 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005900 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005901 return NOT_ENOUGH_DATA;
5902 }
5903 RecordThread *recordThread = (RecordThread *) threadBase.get();
5904 int32_t rear = recordThread->mRsmpInRear;
5905 int32_t front = activeTrack->mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07005906 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005907 // FIXME should not be P2 (don't want to increase latency)
5908 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005909 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07005910 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005911 front &= recordThread->mRsmpInFramesP2 - 1;
5912 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07005913 if (part1 > (size_t) filled) {
5914 part1 = filled;
5915 }
5916 size_t ask = buffer->frameCount;
5917 ALOG_ASSERT(ask > 0);
5918 if (part1 > ask) {
5919 part1 = ask;
5920 }
5921 if (part1 == 0) {
5922 // Higher-level should keep mRsmpInBuffer full, and not call resampler if empty
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005923 LOG_ALWAYS_FATAL("RecordThread::getNextBuffer() starved");
Glenn Kasten85948432013-08-19 12:09:05 -07005924 buffer->raw = NULL;
5925 buffer->frameCount = 0;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005926 activeTrack->mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07005927 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08005928 }
5929
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005930 buffer->raw = recordThread->mRsmpInBuffer + front * recordThread->mChannelCount;
Glenn Kasten85948432013-08-19 12:09:05 -07005931 buffer->frameCount = part1;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005932 activeTrack->mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08005933 return NO_ERROR;
5934}
5935
5936// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005937void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
5938 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08005939{
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005940 RecordTrack *activeTrack = mRecordTrack;
Glenn Kasten85948432013-08-19 12:09:05 -07005941 size_t stepCount = buffer->frameCount;
5942 if (stepCount == 0) {
5943 return;
5944 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005945 ALOG_ASSERT(stepCount <= activeTrack->mRsmpInUnrel);
5946 activeTrack->mRsmpInUnrel -= stepCount;
5947 activeTrack->mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07005948 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08005949 buffer->frameCount = 0;
5950}
5951
Eric Laurent10351942014-05-08 18:49:52 -07005952bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
5953 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005954{
5955 bool reconfig = false;
5956
Eric Laurent10351942014-05-08 18:49:52 -07005957 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005958
Eric Laurent10351942014-05-08 18:49:52 -07005959 audio_format_t reqFormat = mFormat;
5960 uint32_t samplingRate = mSampleRate;
5961 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
5962
5963 AudioParameter param = AudioParameter(keyValuePair);
5964 int value;
5965 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
5966 // channel count change can be requested. Do we mandate the first client defines the
5967 // HAL sampling rate and channel count or do we allow changes on the fly?
5968 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5969 samplingRate = value;
5970 reconfig = true;
5971 }
5972 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
5973 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
5974 status = BAD_VALUE;
5975 } else {
5976 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08005977 reconfig = true;
5978 }
Eric Laurent10351942014-05-08 18:49:52 -07005979 }
5980 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
5981 audio_channel_mask_t mask = (audio_channel_mask_t) value;
5982 if (mask != AUDIO_CHANNEL_IN_MONO && mask != AUDIO_CHANNEL_IN_STEREO) {
5983 status = BAD_VALUE;
5984 } else {
5985 channelMask = mask;
5986 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005987 }
Eric Laurent10351942014-05-08 18:49:52 -07005988 }
5989 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5990 // do not accept frame count changes if tracks are open as the track buffer
5991 // size depends on frame count and correct behavior would not be guaranteed
5992 // if frame count is changed after track creation
5993 if (mActiveTracks.size() > 0) {
5994 status = INVALID_OPERATION;
5995 } else {
5996 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005997 }
Eric Laurent10351942014-05-08 18:49:52 -07005998 }
5999 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6000 // forward device change to effects that have requested to be
6001 // aware of attached audio device.
6002 for (size_t i = 0; i < mEffectChains.size(); i++) {
6003 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08006004 }
Eric Laurent81784c32012-11-19 14:55:58 -08006005
Eric Laurent10351942014-05-08 18:49:52 -07006006 // store input device and output device but do not forward output device to audio HAL.
6007 // Note that status is ignored by the caller for output device
6008 // (see AudioFlinger::setParameters()
6009 if (audio_is_output_devices(value)) {
6010 mOutDevice = value;
6011 status = BAD_VALUE;
6012 } else {
6013 mInDevice = value;
6014 // disable AEC and NS if the device is a BT SCO headset supporting those
6015 // pre processings
6016 if (mTracks.size() > 0) {
6017 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6018 mAudioFlinger->btNrecIsOff();
6019 for (size_t i = 0; i < mTracks.size(); i++) {
6020 sp<RecordTrack> track = mTracks[i];
6021 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
6022 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08006023 }
6024 }
6025 }
Eric Laurent10351942014-05-08 18:49:52 -07006026 }
6027 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
6028 mAudioSource != (audio_source_t)value) {
6029 // forward device change to effects that have requested to be
6030 // aware of attached audio device.
6031 for (size_t i = 0; i < mEffectChains.size(); i++) {
6032 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08006033 }
Eric Laurent10351942014-05-08 18:49:52 -07006034 mAudioSource = (audio_source_t)value;
6035 }
Glenn Kastene198c362013-08-13 09:13:36 -07006036
Eric Laurent10351942014-05-08 18:49:52 -07006037 if (status == NO_ERROR) {
6038 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6039 keyValuePair.string());
6040 if (status == INVALID_OPERATION) {
6041 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006042 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6043 keyValuePair.string());
Eric Laurent10351942014-05-08 18:49:52 -07006044 }
6045 if (reconfig) {
6046 if (status == BAD_VALUE &&
6047 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
6048 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
6049 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
6050 <= (2 * samplingRate)) &&
Andy Hunge5412692014-05-16 11:25:07 -07006051 audio_channel_count_from_in_mask(
6052 mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
Eric Laurent10351942014-05-08 18:49:52 -07006053 (channelMask == AUDIO_CHANNEL_IN_MONO ||
6054 channelMask == AUDIO_CHANNEL_IN_STEREO)) {
6055 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006056 }
Eric Laurent10351942014-05-08 18:49:52 -07006057 if (status == NO_ERROR) {
6058 readInputParameters_l();
6059 sendIoConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08006060 }
6061 }
Eric Laurent81784c32012-11-19 14:55:58 -08006062 }
Eric Laurent10351942014-05-08 18:49:52 -07006063
Eric Laurent81784c32012-11-19 14:55:58 -08006064 return reconfig;
6065}
6066
6067String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6068{
Eric Laurent81784c32012-11-19 14:55:58 -08006069 Mutex::Autolock _l(mLock);
6070 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07006071 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08006072 }
6073
Glenn Kastend8ea6992013-07-16 14:17:15 -07006074 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
6075 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08006076 free(s);
6077 return out_s8;
6078}
6079
Eric Laurent021cf962014-05-13 10:18:14 -07006080void AudioFlinger::RecordThread::audioConfigChanged(int event, int param __unused) {
Eric Laurent81784c32012-11-19 14:55:58 -08006081 AudioSystem::OutputDescriptor desc;
Glenn Kastenb2737d02013-08-19 12:03:11 -07006082 const void *param2 = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006083
6084 switch (event) {
6085 case AudioSystem::INPUT_OPENED:
6086 case AudioSystem::INPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07006087 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08006088 desc.samplingRate = mSampleRate;
6089 desc.format = mFormat;
6090 desc.frameCount = mFrameCount;
6091 desc.latency = 0;
6092 param2 = &desc;
6093 break;
6094
6095 case AudioSystem::INPUT_CLOSED:
6096 default:
6097 break;
6098 }
Eric Laurent021cf962014-05-13 10:18:14 -07006099 mAudioFlinger->audioConfigChanged(event, mId, param2);
Eric Laurent81784c32012-11-19 14:55:58 -08006100}
6101
Glenn Kastendeca2ae2014-02-07 10:25:56 -08006102void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006103{
Eric Laurent81784c32012-11-19 14:55:58 -08006104 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
6105 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Andy Hunge5412692014-05-16 11:25:07 -07006106 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Andy Hung463be252014-07-10 16:56:07 -07006107 mHALFormat = mInput->stream->common.get_format(&mInput->stream->common);
6108 mFormat = mHALFormat;
Glenn Kasten291bb6d2013-07-16 17:23:39 -07006109 if (mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08006110 ALOGE("HAL format %#x not supported; must be AUDIO_FORMAT_PCM_16_BIT", mFormat);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07006111 }
Eric Laurent665470b2014-07-03 16:37:08 -07006112 mFrameSize = audio_stream_in_frame_size(mInput->stream);
Glenn Kasten548efc92012-11-29 08:48:51 -08006113 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
6114 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006115 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08006116 // 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 -07006117 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08006118 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006119 // A larger value should allow more old data to be read after a track calls start(),
6120 // without increasing latency.
Glenn Kastene8426142014-02-28 16:45:03 -08006121 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07006122 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006123 delete[] mRsmpInBuffer;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006124
6125 // TODO optimize audio capture buffer sizes ...
6126 // Here we calculate the size of the sliding buffer used as a source
6127 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
6128 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
6129 // be better to have it derived from the pipe depth in the long term.
6130 // The current value is higher than necessary. However it should not add to latency.
6131
Glenn Kasten85948432013-08-19 12:09:05 -07006132 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
6133 mRsmpInBuffer = new int16_t[(mRsmpInFramesP2 + mFrameCount - 1) * mChannelCount];
Eric Laurent81784c32012-11-19 14:55:58 -08006134
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006135 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
6136 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08006137}
6138
Glenn Kasten5f972c02014-01-13 09:59:31 -08006139uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08006140{
6141 Mutex::Autolock _l(mLock);
6142 if (initCheck() != NO_ERROR) {
6143 return 0;
6144 }
6145
6146 return mInput->stream->get_input_frames_lost(mInput->stream);
6147}
6148
6149uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
6150{
6151 Mutex::Autolock _l(mLock);
6152 uint32_t result = 0;
6153 if (getEffectChain_l(sessionId) != 0) {
6154 result = EFFECT_SESSION;
6155 }
6156
6157 for (size_t i = 0; i < mTracks.size(); ++i) {
6158 if (sessionId == mTracks[i]->sessionId()) {
6159 result |= TRACK_SESSION;
6160 break;
6161 }
6162 }
6163
6164 return result;
6165}
6166
6167KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
6168{
6169 KeyedVector<int, bool> ids;
6170 Mutex::Autolock _l(mLock);
6171 for (size_t j = 0; j < mTracks.size(); ++j) {
6172 sp<RecordThread::RecordTrack> track = mTracks[j];
6173 int sessionId = track->sessionId();
6174 if (ids.indexOfKey(sessionId) < 0) {
6175 ids.add(sessionId, true);
6176 }
6177 }
6178 return ids;
6179}
6180
6181AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
6182{
6183 Mutex::Autolock _l(mLock);
6184 AudioStreamIn *input = mInput;
6185 mInput = NULL;
6186 return input;
6187}
6188
6189// this method must always be called either with ThreadBase mLock held or inside the thread loop
6190audio_stream_t* AudioFlinger::RecordThread::stream() const
6191{
6192 if (mInput == NULL) {
6193 return NULL;
6194 }
6195 return &mInput->stream->common;
6196}
6197
6198status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6199{
6200 // only one chain per input thread
6201 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07006202 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08006203 return INVALID_OPERATION;
6204 }
6205 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07006206 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08006207 chain->setInBuffer(NULL);
6208 chain->setOutBuffer(NULL);
6209
6210 checkSuspendOnAddEffectChain_l(chain);
6211
Eric Laurent1b928682014-10-02 19:41:47 -07006212 // make sure enabled pre processing effects state is communicated to the HAL as we
6213 // just moved them to a new input stream.
6214 chain->syncHalEffectsState();
6215
Eric Laurent81784c32012-11-19 14:55:58 -08006216 mEffectChains.add(chain);
6217
6218 return NO_ERROR;
6219}
6220
6221size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6222{
6223 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
6224 ALOGW_IF(mEffectChains.size() != 1,
6225 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6226 chain.get(), mEffectChains.size(), this);
6227 if (mEffectChains.size() == 1) {
6228 mEffectChains.removeAt(0);
6229 }
6230 return 0;
6231}
6232
Eric Laurent1c333e22014-05-20 10:48:17 -07006233status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
6234 audio_patch_handle_t *handle)
6235{
6236 status_t status = NO_ERROR;
6237 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
6238 // store new device and send to effects
6239 mInDevice = patch->sources[0].ext.device.type;
6240 for (size_t i = 0; i < mEffectChains.size(); i++) {
6241 mEffectChains[i]->setDevice_l(mInDevice);
6242 }
6243
6244 // disable AEC and NS if the device is a BT SCO headset supporting those
6245 // pre processings
6246 if (mTracks.size() > 0) {
6247 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6248 mAudioFlinger->btNrecIsOff();
6249 for (size_t i = 0; i < mTracks.size(); i++) {
6250 sp<RecordTrack> track = mTracks[i];
6251 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
6252 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
6253 }
6254 }
6255
6256 // store new source and send to effects
6257 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
6258 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
6259 for (size_t i = 0; i < mEffectChains.size(); i++) {
6260 mEffectChains[i]->setAudioSource_l(mAudioSource);
6261 }
6262 }
6263
6264 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
6265 status = hwDevice->create_audio_patch(hwDevice,
6266 patch->num_sources,
6267 patch->sources,
6268 patch->num_sinks,
6269 patch->sinks,
6270 handle);
6271 } else {
6272 ALOG_ASSERT(false, "createAudioPatch_l() called on a pre 3.0 HAL");
6273 }
6274 return status;
6275}
6276
6277status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
6278{
6279 status_t status = NO_ERROR;
6280 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
6281 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
6282 status = hwDevice->release_audio_patch(hwDevice, handle);
6283 } else {
6284 ALOG_ASSERT(false, "releaseAudioPatch_l() called on a pre 3.0 HAL");
6285 }
6286 return status;
6287}
6288
Eric Laurent83b88082014-06-20 18:31:16 -07006289void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
6290{
6291 Mutex::Autolock _l(mLock);
6292 mTracks.add(record);
6293}
6294
6295void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
6296{
6297 Mutex::Autolock _l(mLock);
6298 destroyTrack_l(record);
6299}
6300
6301void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
6302{
6303 ThreadBase::getAudioPortConfig(config);
6304 config->role = AUDIO_PORT_ROLE_SINK;
6305 config->ext.mix.hw_module = mInput->audioHwDev->handle();
6306 config->ext.mix.usecase.source = mAudioSource;
6307}
Eric Laurent1c333e22014-05-20 10:48:17 -07006308
Eric Laurent81784c32012-11-19 14:55:58 -08006309}; // namespace android