blob: dacb12cd6114398e8a137db9e81144d00bfd4c95 [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),
Eric Laurentd1f69b02014-12-15 14:33:13 -08001200 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001201 // mLatchD, mLatchQ,
1202 mLatchDValid(false), mLatchQValid(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001203{
1204 snprintf(mName, kNameLength, "AudioOut_%X", id);
Glenn Kasten9e58b552013-01-18 15:09:48 -08001205 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mName);
Eric Laurent81784c32012-11-19 14:55:58 -08001206
1207 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1208 // it would be safer to explicitly pass initial masterVolume/masterMute as
1209 // parameter.
1210 //
1211 // If the HAL we are using has support for master volume or master mute,
1212 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1213 // and the mute set to false).
1214 mMasterVolume = audioFlinger->masterVolume_l();
1215 mMasterMute = audioFlinger->masterMute_l();
1216 if (mOutput && mOutput->audioHwDev) {
1217 if (mOutput->audioHwDev->canSetMasterVolume()) {
1218 mMasterVolume = 1.0;
1219 }
1220
1221 if (mOutput->audioHwDev->canSetMasterMute()) {
1222 mMasterMute = false;
1223 }
1224 }
1225
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001226 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001227
Eric Laurent223fd5c2014-11-11 13:43:36 -08001228 // ++ operator does not compile
Glenn Kasten66e46352014-01-16 17:44:23 -08001229 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001230 stream = (audio_stream_type_t) (stream + 1)) {
1231 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1232 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1233 }
Eric Laurent81784c32012-11-19 14:55:58 -08001234}
1235
1236AudioFlinger::PlaybackThread::~PlaybackThread()
1237{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001238 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001239 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001240 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001241 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001242}
1243
1244void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1245{
1246 dumpInternals(fd, args);
1247 dumpTracks(fd, args);
1248 dumpEffectChains(fd, args);
1249}
1250
Glenn Kasten0f11b512014-01-31 16:18:54 -08001251void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001252{
1253 const size_t SIZE = 256;
1254 char buffer[SIZE];
1255 String8 result;
1256
Marco Nelissenb2208842014-02-07 14:00:50 -08001257 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001258 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1259 const stream_type_t *st = &mStreamTypes[i];
1260 if (i > 0) {
1261 result.appendFormat(", ");
1262 }
1263 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1264 if (st->mute) {
1265 result.append("M");
1266 }
1267 }
1268 result.append("\n");
1269 write(fd, result.string(), result.length());
1270 result.clear();
1271
Eric Laurent81784c32012-11-19 14:55:58 -08001272 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1273 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001274 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001275 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001276
1277 size_t numtracks = mTracks.size();
1278 size_t numactive = mActiveTracks.size();
Elliott Hughes87cebad2014-05-22 10:14:43 -07001279 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001280 size_t numactiveseen = 0;
1281 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07001282 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08001283 Track::appendDumpHeader(result);
1284 for (size_t i = 0; i < numtracks; ++i) {
1285 sp<Track> track = mTracks[i];
1286 if (track != 0) {
1287 bool active = mActiveTracks.indexOf(track) >= 0;
1288 if (active) {
1289 numactiveseen++;
1290 }
1291 track->dump(buffer, SIZE, active);
1292 result.append(buffer);
1293 }
1294 }
1295 } else {
1296 result.append("\n");
1297 }
1298 if (numactiveseen != numactive) {
1299 // some tracks in the active list were not in the tracks list
1300 snprintf(buffer, SIZE, " The following tracks are in the active list but"
1301 " not in the track list\n");
1302 result.append(buffer);
1303 Track::appendDumpHeader(result);
1304 for (size_t i = 0; i < numactive; ++i) {
1305 sp<Track> track = mActiveTracks[i].promote();
1306 if (track != 0 && mTracks.indexOf(track) < 0) {
1307 track->dump(buffer, SIZE, true);
1308 result.append(buffer);
1309 }
1310 }
1311 }
1312
1313 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001314}
1315
1316void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1317{
Elliott Hughes87cebad2014-05-22 10:14:43 -07001318 dprintf(fd, "\nOutput thread %p:\n", this);
1319 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
1320 dprintf(fd, " Last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1321 dprintf(fd, " Total writes: %d\n", mNumWrites);
1322 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1323 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1324 dprintf(fd, " Suspend count: %d\n", mSuspended);
1325 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1326 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1327 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1328 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent81784c32012-11-19 14:55:58 -08001329
1330 dumpBase(fd, args);
1331}
1332
1333// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001334
1335void AudioFlinger::PlaybackThread::onFirstRef()
1336{
1337 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
1338}
1339
1340// ThreadBase virtuals
1341void AudioFlinger::PlaybackThread::preExit()
1342{
1343 ALOGV(" preExit()");
1344 // FIXME this is using hard-coded strings but in the future, this functionality will be
1345 // converted to use audio HAL extensions required to support tunneling
1346 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1347}
1348
1349// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1350sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1351 const sp<AudioFlinger::Client>& client,
1352 audio_stream_type_t streamType,
1353 uint32_t sampleRate,
1354 audio_format_t format,
1355 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001356 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001357 const sp<IMemory>& sharedBuffer,
1358 int sessionId,
1359 IAudioFlinger::track_flags_t *flags,
1360 pid_t tid,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001361 int uid,
Eric Laurent81784c32012-11-19 14:55:58 -08001362 status_t *status)
1363{
Glenn Kasten74935e42013-12-19 08:56:45 -08001364 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001365 sp<Track> track;
1366 status_t lStatus;
1367
1368 bool isTimed = (*flags & IAudioFlinger::TRACK_TIMED) != 0;
1369
1370 // client expresses a preference for FAST, but we get the final say
1371 if (*flags & IAudioFlinger::TRACK_FAST) {
1372 if (
1373 // not timed
1374 (!isTimed) &&
1375 // either of these use cases:
1376 (
1377 // use case 1: shared buffer with any frame count
1378 (
1379 (sharedBuffer != 0)
1380 ) ||
1381 // use case 2: callback handler and frame count is default or at least as large as HAL
1382 (
1383 (tid != -1) &&
1384 ((frameCount == 0) ||
Glenn Kastenb5fed682013-12-03 09:06:43 -08001385 (frameCount >= mFrameCount))
Eric Laurent81784c32012-11-19 14:55:58 -08001386 )
1387 ) &&
1388 // PCM data
1389 audio_is_linear_pcm(format) &&
Andy Hung9a592762014-07-21 21:56:01 -07001390 // identical channel mask to sink, or mono in and stereo sink
1391 (channelMask == mChannelMask ||
1392 (channelMask == AUDIO_CHANNEL_OUT_MONO &&
1393 mChannelMask == AUDIO_CHANNEL_OUT_STEREO)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001394 // hardware sample rate
1395 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001396 // normal mixer has an associated fast mixer
1397 hasFastMixer() &&
1398 // there are sufficient fast track slots available
1399 (mFastTrackAvailMask != 0)
1400 // FIXME test that MixerThread for this fast track has a capable output HAL
1401 // FIXME add a permission test also?
1402 ) {
1403 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1404 if (frameCount == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001405 // read the fast track multiplier property the first time it is needed
1406 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1407 if (ok != 0) {
1408 ALOGE("%s pthread_once failed: %d", __func__, ok);
1409 }
1410 frameCount = mFrameCount * sFastTrackMultiplier;
Eric Laurent81784c32012-11-19 14:55:58 -08001411 }
1412 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
1413 frameCount, mFrameCount);
1414 } else {
1415 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
Andy Hung6146c082014-03-18 11:56:15 -07001416 "mFrameCount=%d format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
1417 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001418 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Andy Hung6146c082014-03-18 11:56:15 -07001419 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001420 audio_is_linear_pcm(format),
1421 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
1422 *flags &= ~IAudioFlinger::TRACK_FAST;
1423 // For compatibility with AudioTrack calculation, buffer depth is forced
1424 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1425 // This is probably too conservative, but legacy application code may depend on it.
1426 // If you change this calculation, also review the start threshold which is related.
1427 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1428 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1429 if (minBufCount < 2) {
1430 minBufCount = 2;
1431 }
1432 size_t minFrameCount = mNormalFrameCount * minBufCount;
1433 if (frameCount < minFrameCount) {
1434 frameCount = minFrameCount;
1435 }
1436 }
1437 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001438 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001439
Glenn Kastenc3df8382014-03-13 15:05:25 -07001440 switch (mType) {
1441
1442 case DIRECT:
Glenn Kasten993fa062014-05-02 11:14:34 -07001443 if (audio_is_linear_pcm(format)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001444 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001445 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1446 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001447 sampleRate, format, channelMask, mOutput, mFormat);
1448 lStatus = BAD_VALUE;
1449 goto Exit;
1450 }
1451 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001452 break;
1453
1454 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001455 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001456 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1457 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001458 sampleRate, format, channelMask, mOutput, mFormat);
1459 lStatus = BAD_VALUE;
1460 goto Exit;
1461 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001462 break;
1463
1464 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07001465 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001466 ALOGE("createTrack_l() Bad parameter: format %#x \""
1467 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001468 format, mOutput, mFormat);
1469 lStatus = BAD_VALUE;
1470 goto Exit;
1471 }
Andy Hungcd044842014-08-07 11:04:34 -07001472 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08001473 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1474 lStatus = BAD_VALUE;
1475 goto Exit;
1476 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001477 break;
1478
Eric Laurent81784c32012-11-19 14:55:58 -08001479 }
1480
1481 lStatus = initCheck();
1482 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07001483 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08001484 goto Exit;
1485 }
1486
1487 { // scope for mLock
1488 Mutex::Autolock _l(mLock);
1489
1490 // all tracks in same audio session must share the same routing strategy otherwise
1491 // conflicts will happen when tracks are moved from one output to another by audio policy
1492 // manager
1493 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1494 for (size_t i = 0; i < mTracks.size(); ++i) {
1495 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07001496 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001497 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1498 if (sessionId == t->sessionId() && strategy != actual) {
1499 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1500 strategy, actual);
1501 lStatus = BAD_VALUE;
1502 goto Exit;
1503 }
1504 }
1505 }
1506
1507 if (!isTimed) {
1508 track = new Track(this, client, streamType, sampleRate, format,
Eric Laurent83b88082014-06-20 18:31:16 -07001509 channelMask, frameCount, NULL, sharedBuffer,
1510 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08001511 } else {
1512 track = TimedTrack::create(this, client, streamType, sampleRate, format,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001513 channelMask, frameCount, sharedBuffer, sessionId, uid);
Eric Laurent81784c32012-11-19 14:55:58 -08001514 }
Glenn Kasten03003332013-08-06 15:40:54 -07001515
1516 // new Track always returns non-NULL,
1517 // but TimedTrack::create() is a factory that could fail by returning NULL
1518 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
1519 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08001520 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001521 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08001522 goto Exit;
1523 }
1524 mTracks.add(track);
1525
1526 sp<EffectChain> chain = getEffectChain_l(sessionId);
1527 if (chain != 0) {
1528 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1529 track->setMainBuffer(chain->inBuffer());
1530 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1531 chain->incTrackCnt();
1532 }
1533
1534 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1535 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1536 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1537 // so ask activity manager to do this on our behalf
1538 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1539 }
1540 }
1541
1542 lStatus = NO_ERROR;
1543
1544Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001545 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001546 return track;
1547}
1548
1549uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1550{
1551 return latency;
1552}
1553
1554uint32_t AudioFlinger::PlaybackThread::latency() const
1555{
1556 Mutex::Autolock _l(mLock);
1557 return latency_l();
1558}
1559uint32_t AudioFlinger::PlaybackThread::latency_l() const
1560{
1561 if (initCheck() == NO_ERROR) {
1562 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
1563 } else {
1564 return 0;
1565 }
1566}
1567
1568void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1569{
1570 Mutex::Autolock _l(mLock);
1571 // Don't apply master volume in SW if our HAL can do it for us.
1572 if (mOutput && mOutput->audioHwDev &&
1573 mOutput->audioHwDev->canSetMasterVolume()) {
1574 mMasterVolume = 1.0;
1575 } else {
1576 mMasterVolume = value;
1577 }
1578}
1579
1580void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1581{
1582 Mutex::Autolock _l(mLock);
1583 // Don't apply master mute in SW if our HAL can do it for us.
1584 if (mOutput && mOutput->audioHwDev &&
1585 mOutput->audioHwDev->canSetMasterMute()) {
1586 mMasterMute = false;
1587 } else {
1588 mMasterMute = muted;
1589 }
1590}
1591
1592void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
1593{
1594 Mutex::Autolock _l(mLock);
1595 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001596 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001597}
1598
1599void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
1600{
1601 Mutex::Autolock _l(mLock);
1602 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001603 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001604}
1605
1606float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
1607{
1608 Mutex::Autolock _l(mLock);
1609 return mStreamTypes[stream].volume;
1610}
1611
1612// addTrack_l() must be called with ThreadBase::mLock held
1613status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1614{
1615 status_t status = ALREADY_EXISTS;
1616
1617 // set retry count for buffer fill
1618 track->mRetryCount = kMaxTrackStartupRetries;
1619 if (mActiveTracks.indexOf(track) < 0) {
1620 // the track is newly added, make sure it fills up all its
1621 // buffers before playing. This is to ensure the client will
1622 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07001623 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001624 TrackBase::track_state state = track->mState;
1625 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08001626 status = AudioSystem::startOutput(mId, track->streamType(),
1627 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001628 mLock.lock();
1629 // abort track was stopped/paused while we released the lock
1630 if (state != track->mState) {
1631 if (status == NO_ERROR) {
1632 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08001633 AudioSystem::stopOutput(mId, track->streamType(),
1634 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001635 mLock.lock();
1636 }
1637 return INVALID_OPERATION;
1638 }
1639 // abort if start is rejected by audio policy manager
1640 if (status != NO_ERROR) {
1641 return PERMISSION_DENIED;
1642 }
1643#ifdef ADD_BATTERY_DATA
1644 // to track the speaker usage
1645 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
1646#endif
1647 }
1648
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001649 track->mFillingUpStatus = track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent81784c32012-11-19 14:55:58 -08001650 track->mResetDone = false;
1651 track->mPresentationCompleteFrames = 0;
1652 mActiveTracks.add(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001653 mWakeLockUids.add(track->uid());
1654 mActiveTracksGeneration++;
Eric Laurentfd477972013-10-25 18:10:40 -07001655 mLatestActiveTrack = track;
Eric Laurentd0107bc2013-06-11 14:38:48 -07001656 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1657 if (chain != 0) {
1658 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
1659 track->sessionId());
1660 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08001661 }
1662
1663 status = NO_ERROR;
1664 }
1665
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08001666 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001667 return status;
1668}
1669
Eric Laurentbfb1b832013-01-07 09:53:42 -08001670bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08001671{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001672 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08001673 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001674 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
1675 track->mState = TrackBase::STOPPED;
1676 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08001677 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07001678 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001679 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08001680 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001681
1682 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08001683}
1684
1685void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1686{
1687 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
1688 mTracks.remove(track);
1689 deleteTrackName_l(track->name());
1690 // redundant as track is about to be destroyed, for dumpsys only
1691 track->mName = -1;
1692 if (track->isFastTrack()) {
1693 int index = track->mFastIndex;
1694 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
1695 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1696 mFastTrackAvailMask |= 1 << index;
1697 // redundant as track is about to be destroyed, for dumpsys only
1698 track->mFastIndex = -1;
1699 }
1700 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1701 if (chain != 0) {
1702 chain->decTrackCnt();
1703 }
1704}
1705
Eric Laurentede6c3b2013-09-19 14:37:46 -07001706void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001707{
1708 // Thread could be blocked waiting for async
1709 // so signal it to handle state changes immediately
1710 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1711 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1712 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001713 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001714}
1715
Eric Laurent81784c32012-11-19 14:55:58 -08001716String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1717{
Eric Laurent81784c32012-11-19 14:55:58 -08001718 Mutex::Autolock _l(mLock);
1719 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07001720 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08001721 }
1722
Glenn Kastend8ea6992013-07-16 14:17:15 -07001723 char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
1724 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08001725 free(s);
1726 return out_s8;
1727}
1728
Eric Laurent021cf962014-05-13 10:18:14 -07001729void AudioFlinger::PlaybackThread::audioConfigChanged(int event, int param) {
Eric Laurent81784c32012-11-19 14:55:58 -08001730 AudioSystem::OutputDescriptor desc;
1731 void *param2 = NULL;
1732
Eric Laurent021cf962014-05-13 10:18:14 -07001733 ALOGV("PlaybackThread::audioConfigChanged, thread %p, event %d, param %d", this, event,
Eric Laurent81784c32012-11-19 14:55:58 -08001734 param);
1735
1736 switch (event) {
1737 case AudioSystem::OUTPUT_OPENED:
1738 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07001739 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08001740 desc.samplingRate = mSampleRate;
1741 desc.format = mFormat;
1742 desc.frameCount = mNormalFrameCount; // FIXME see
1743 // AudioFlinger::frameCount(audio_io_handle_t)
Eric Laurent10351942014-05-08 18:49:52 -07001744 desc.latency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001745 param2 = &desc;
1746 break;
1747
1748 case AudioSystem::STREAM_CONFIG_CHANGED:
1749 param2 = &param;
1750 case AudioSystem::OUTPUT_CLOSED:
1751 default:
1752 break;
1753 }
Eric Laurent021cf962014-05-13 10:18:14 -07001754 mAudioFlinger->audioConfigChanged(event, mId, param2);
Eric Laurent81784c32012-11-19 14:55:58 -08001755}
1756
Eric Laurentbfb1b832013-01-07 09:53:42 -08001757void AudioFlinger::PlaybackThread::writeCallback()
1758{
1759 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001760 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001761}
1762
1763void AudioFlinger::PlaybackThread::drainCallback()
1764{
1765 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001766 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001767}
1768
Eric Laurent3b4529e2013-09-05 18:09:19 -07001769void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001770{
1771 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001772 // reject out of sequence requests
1773 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
1774 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001775 mWaitWorkCV.signal();
1776 }
1777}
1778
Eric Laurent3b4529e2013-09-05 18:09:19 -07001779void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001780{
1781 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001782 // reject out of sequence requests
1783 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
1784 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001785 mWaitWorkCV.signal();
1786 }
1787}
1788
1789// static
1790int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
Glenn Kasten0f11b512014-01-31 16:18:54 -08001791 void *param __unused,
Eric Laurentbfb1b832013-01-07 09:53:42 -08001792 void *cookie)
1793{
1794 AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
1795 ALOGV("asyncCallback() event %d", event);
1796 switch (event) {
1797 case STREAM_CBK_EVENT_WRITE_READY:
1798 me->writeCallback();
1799 break;
1800 case STREAM_CBK_EVENT_DRAIN_READY:
1801 me->drainCallback();
1802 break;
1803 default:
1804 ALOGW("asyncCallback() unknown event %d", event);
1805 break;
1806 }
1807 return 0;
1808}
1809
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001810void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001811{
Glenn Kastenadad3d72014-02-21 14:51:43 -08001812 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Eric Laurent81784c32012-11-19 14:55:58 -08001813 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
1814 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001815 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08001816 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001817 }
Andy Hung9a592762014-07-21 21:56:01 -07001818 if ((mType == MIXER || mType == DUPLICATING)
1819 && !isValidPcmSinkChannelMask(mChannelMask)) {
1820 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
1821 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001822 }
Andy Hunge5412692014-05-16 11:25:07 -07001823 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Andy Hung463be252014-07-10 16:56:07 -07001824 mHALFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
1825 mFormat = mHALFormat;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001826 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08001827 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001828 }
Andy Hung6146c082014-03-18 11:56:15 -07001829 if ((mType == MIXER || mType == DUPLICATING)
1830 && !isValidPcmSinkFormat(mFormat)) {
1831 LOG_FATAL("HAL format %#x not supported for mixed output",
1832 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001833 }
Eric Laurent665470b2014-07-03 16:37:08 -07001834 mFrameSize = audio_stream_out_frame_size(mOutput->stream);
Glenn Kasten70949c42013-08-06 07:40:12 -07001835 mBufferSize = mOutput->stream->common.get_buffer_size(&mOutput->stream->common);
1836 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08001837 if (mFrameCount & 15) {
1838 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
1839 mFrameCount);
1840 }
1841
Eric Laurentbfb1b832013-01-07 09:53:42 -08001842 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
1843 (mOutput->stream->set_callback != NULL)) {
1844 if (mOutput->stream->set_callback(mOutput->stream,
1845 AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
1846 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07001847 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001848 }
1849 }
1850
Eric Laurentd1f69b02014-12-15 14:33:13 -08001851 mHwSupportsPause = false;
1852 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
1853 if (mOutput->stream->pause != NULL) {
1854 if (mOutput->stream->resume != NULL) {
1855 mHwSupportsPause = true;
1856 } else {
1857 ALOGW("direct output implements pause but not resume");
1858 }
1859 } else if (mOutput->stream->resume != NULL) {
1860 ALOGW("direct output implements resume but not pause");
1861 }
1862 }
1863
Andy Hung09a50072014-02-27 14:30:47 -08001864 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08001865 double multiplier = 1.0;
1866 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
1867 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08001868 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
1869 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Eric Laurent81784c32012-11-19 14:55:58 -08001870 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
1871 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
1872 maxNormalFrameCount = maxNormalFrameCount & ~15;
1873 if (maxNormalFrameCount < minNormalFrameCount) {
1874 maxNormalFrameCount = minNormalFrameCount;
1875 }
1876 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
1877 if (multiplier <= 1.0) {
1878 multiplier = 1.0;
1879 } else if (multiplier <= 2.0) {
1880 if (2 * mFrameCount <= maxNormalFrameCount) {
1881 multiplier = 2.0;
1882 } else {
1883 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
1884 }
1885 } else {
1886 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
Andy Hung09a50072014-02-27 14:30:47 -08001887 // 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 -08001888 // track, but we sometimes have to do this to satisfy the maximum frame count
1889 // constraint)
1890 // FIXME this rounding up should not be done if no HAL SRC
1891 uint32_t truncMult = (uint32_t) multiplier;
1892 if ((truncMult & 1)) {
1893 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
1894 ++truncMult;
1895 }
1896 }
1897 multiplier = (double) truncMult;
1898 }
1899 }
1900 mNormalFrameCount = multiplier * mFrameCount;
1901 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07001902 if (mType == MIXER || mType == DUPLICATING) {
1903 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
1904 }
Andy Hung09a50072014-02-27 14:30:47 -08001905 ALOGI("HAL output buffer size %u frames, normal sink buffer size %u frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001906 mNormalFrameCount);
1907
Andy Hung010a1a12014-03-13 13:57:33 -07001908 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
1909 // Originally this was int16_t[] array, need to remove legacy implications.
1910 free(mSinkBuffer);
1911 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07001912 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
1913 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
1914 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07001915 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08001916
Andy Hung69aed5f2014-02-25 17:24:40 -08001917 // We resize the mMixerBuffer according to the requirements of the sink buffer which
1918 // drives the output.
1919 free(mMixerBuffer);
1920 mMixerBuffer = NULL;
1921 if (mMixerBufferEnabled) {
1922 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
1923 mMixerBufferSize = mNormalFrameCount * mChannelCount
1924 * audio_bytes_per_sample(mMixerBufferFormat);
1925 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
1926 }
Andy Hung98ef9782014-03-04 14:46:50 -08001927 free(mEffectBuffer);
1928 mEffectBuffer = NULL;
1929 if (mEffectBufferEnabled) {
1930 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
1931 mEffectBufferSize = mNormalFrameCount * mChannelCount
1932 * audio_bytes_per_sample(mEffectBufferFormat);
1933 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
1934 }
Andy Hung69aed5f2014-02-25 17:24:40 -08001935
Eric Laurent81784c32012-11-19 14:55:58 -08001936 // force reconfiguration of effect chains and engines to take new buffer size and audio
1937 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001938 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08001939 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1940 // matter.
1941 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1942 Vector< sp<EffectChain> > effectChains = mEffectChains;
1943 for (size_t i = 0; i < effectChains.size(); i ++) {
1944 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
1945 }
1946}
1947
1948
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001949status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08001950{
1951 if (halFrames == NULL || dspFrames == NULL) {
1952 return BAD_VALUE;
1953 }
1954 Mutex::Autolock _l(mLock);
1955 if (initCheck() != NO_ERROR) {
1956 return INVALID_OPERATION;
1957 }
1958 size_t framesWritten = mBytesWritten / mFrameSize;
1959 *halFrames = framesWritten;
1960
1961 if (isSuspended()) {
1962 // return an estimation of rendered frames when the output is suspended
1963 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
1964 *dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0;
1965 return NO_ERROR;
1966 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001967 status_t status;
1968 uint32_t frames;
1969 status = mOutput->stream->get_render_position(mOutput->stream, &frames);
1970 *dspFrames = (size_t)frames;
1971 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08001972 }
1973}
1974
1975uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
1976{
1977 Mutex::Autolock _l(mLock);
1978 uint32_t result = 0;
1979 if (getEffectChain_l(sessionId) != 0) {
1980 result = EFFECT_SESSION;
1981 }
1982
1983 for (size_t i = 0; i < mTracks.size(); ++i) {
1984 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08001985 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001986 result |= TRACK_SESSION;
1987 break;
1988 }
1989 }
1990
1991 return result;
1992}
1993
1994uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1995{
1996 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
1997 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
1998 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1999 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2000 }
2001 for (size_t i = 0; i < mTracks.size(); i++) {
2002 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002003 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002004 return AudioSystem::getStrategyForStream(track->streamType());
2005 }
2006 }
2007 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2008}
2009
2010
2011AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
2012{
2013 Mutex::Autolock _l(mLock);
2014 return mOutput;
2015}
2016
2017AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
2018{
2019 Mutex::Autolock _l(mLock);
2020 AudioStreamOut *output = mOutput;
2021 mOutput = NULL;
2022 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2023 // must push a NULL and wait for ack
2024 mOutputSink.clear();
2025 mPipeSink.clear();
2026 mNormalSink.clear();
2027 return output;
2028}
2029
2030// this method must always be called either with ThreadBase mLock held or inside the thread loop
2031audio_stream_t* AudioFlinger::PlaybackThread::stream() const
2032{
2033 if (mOutput == NULL) {
2034 return NULL;
2035 }
2036 return &mOutput->stream->common;
2037}
2038
2039uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2040{
2041 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2042}
2043
2044status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2045{
2046 if (!isValidSyncEvent(event)) {
2047 return BAD_VALUE;
2048 }
2049
2050 Mutex::Autolock _l(mLock);
2051
2052 for (size_t i = 0; i < mTracks.size(); ++i) {
2053 sp<Track> track = mTracks[i];
2054 if (event->triggerSession() == track->sessionId()) {
2055 (void) track->setSyncEvent(event);
2056 return NO_ERROR;
2057 }
2058 }
2059
2060 return NAME_NOT_FOUND;
2061}
2062
2063bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2064{
2065 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2066}
2067
2068void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2069 const Vector< sp<Track> >& tracksToRemove)
2070{
2071 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002072 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002073 for (size_t i = 0 ; i < count ; i++) {
2074 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002075 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002076 AudioSystem::stopOutput(mId, track->streamType(),
2077 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002078#ifdef ADD_BATTERY_DATA
2079 // to track the speaker usage
2080 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2081#endif
2082 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002083 AudioSystem::releaseOutput(mId, track->streamType(),
2084 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002085 }
Eric Laurent81784c32012-11-19 14:55:58 -08002086 }
2087 }
2088 }
Eric Laurent81784c32012-11-19 14:55:58 -08002089}
2090
2091void AudioFlinger::PlaybackThread::checkSilentMode_l()
2092{
2093 if (!mMasterMute) {
2094 char value[PROPERTY_VALUE_MAX];
2095 if (property_get("ro.audio.silent", value, "0") > 0) {
2096 char *endptr;
2097 unsigned long ul = strtoul(value, &endptr, 0);
2098 if (*endptr == '\0' && ul != 0) {
2099 ALOGD("Silence is golden");
2100 // The setprop command will not allow a property to be changed after
2101 // the first time it is set, so we don't have to worry about un-muting.
2102 setMasterMute_l(true);
2103 }
2104 }
2105 }
2106}
2107
2108// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002109ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002110{
2111 // FIXME rewrite to reduce number of system calls
2112 mLastWriteTime = systemTime();
2113 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002114 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002115 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002116
2117 // If an NBAIO sink is present, use it to write the normal mixer's submix
2118 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002119
Andy Hung010a1a12014-03-13 13:57:33 -07002120 const size_t count = mBytesRemaining / mFrameSize;
2121
Simon Wilson2d590962012-11-29 15:18:50 -08002122 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002123 // update the setpoint when AudioFlinger::mScreenState changes
2124 uint32_t screenState = AudioFlinger::mScreenState;
2125 if (screenState != mScreenState) {
2126 mScreenState = screenState;
2127 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2128 if (pipe != NULL) {
2129 pipe->setAvgFrames((mScreenState & 1) ?
2130 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2131 }
2132 }
Andy Hung010a1a12014-03-13 13:57:33 -07002133 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002134 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002135 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002136 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002137 } else {
2138 bytesWritten = framesWritten;
2139 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002140 status_t status = mNormalSink->getTimestamp(mLatchD.mTimestamp);
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002141 if (status == NO_ERROR) {
2142 size_t totalFramesWritten = mNormalSink->framesWritten();
2143 if (totalFramesWritten >= mLatchD.mTimestamp.mPosition) {
2144 mLatchD.mUnpresentedFrames = totalFramesWritten - mLatchD.mTimestamp.mPosition;
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002145 // mLatchD.mFramesReleased is set immediately before D is clocked into Q
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002146 mLatchDValid = true;
2147 }
2148 }
Eric Laurent81784c32012-11-19 14:55:58 -08002149 // otherwise use the HAL / AudioStreamOut directly
2150 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002151 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002152
Eric Laurentbfb1b832013-01-07 09:53:42 -08002153 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002154 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2155 mWriteAckSequence += 2;
2156 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002157 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002158 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002159 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002160 // FIXME We should have an implementation of timestamps for direct output threads.
2161 // They are used e.g for multichannel PCM playback over HDMI.
Eric Laurentbfb1b832013-01-07 09:53:42 -08002162 bytesWritten = mOutput->stream->write(mOutput->stream,
Andy Hung2098f272014-02-27 14:00:06 -08002163 (char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002164 if (mUseAsyncWrite &&
2165 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2166 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002167 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002168 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002169 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002170 }
Eric Laurent81784c32012-11-19 14:55:58 -08002171 }
2172
Eric Laurent81784c32012-11-19 14:55:58 -08002173 mNumWrites++;
2174 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002175 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002176 return bytesWritten;
2177}
2178
2179void AudioFlinger::PlaybackThread::threadLoop_drain()
2180{
2181 if (mOutput->stream->drain) {
2182 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2183 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002184 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2185 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002186 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002187 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002188 }
2189 mOutput->stream->drain(mOutput->stream,
2190 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
2191 : AUDIO_DRAIN_ALL);
2192 }
2193}
2194
2195void AudioFlinger::PlaybackThread::threadLoop_exit()
2196{
Eric Laurent275e8e92014-11-30 15:14:47 -08002197 {
2198 Mutex::Autolock _l(mLock);
2199 for (size_t i = 0; i < mTracks.size(); i++) {
2200 sp<Track> track = mTracks[i];
2201 track->invalidate();
2202 }
2203 }
Eric Laurent81784c32012-11-19 14:55:58 -08002204}
2205
2206/*
2207The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002208 - mSinkBufferSize from frame count * frame size
Eric Laurent81784c32012-11-19 14:55:58 -08002209 - activeSleepTime from activeSleepTimeUs()
2210 - idleSleepTime from idleSleepTimeUs()
2211 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
2212 - maxPeriod from frame count and sample rate (MIXER only)
2213
2214The parameters that affect these derived values are:
2215 - frame count
2216 - frame size
2217 - sample rate
2218 - device type: A2DP or not
2219 - device latency
2220 - format: PCM or not
2221 - active sleep time
2222 - idle sleep time
2223*/
2224
2225void AudioFlinger::PlaybackThread::cacheParameters_l()
2226{
Andy Hung25c2dac2014-02-27 14:56:00 -08002227 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002228 activeSleepTime = activeSleepTimeUs();
2229 idleSleepTime = idleSleepTimeUs();
2230}
2231
2232void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2233{
Glenn Kasten7c027242012-12-26 14:43:16 -08002234 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurent81784c32012-11-19 14:55:58 -08002235 this, streamType, mTracks.size());
2236 Mutex::Autolock _l(mLock);
2237
2238 size_t size = mTracks.size();
2239 for (size_t i = 0; i < size; i++) {
2240 sp<Track> t = mTracks[i];
2241 if (t->streamType() == streamType) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002242 t->invalidate();
Eric Laurent81784c32012-11-19 14:55:58 -08002243 }
2244 }
2245}
2246
2247status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2248{
2249 int session = chain->sessionId();
Andy Hung010a1a12014-03-13 13:57:33 -07002250 int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled
2251 ? mEffectBuffer : mSinkBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002252 bool ownsBuffer = false;
2253
2254 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
2255 if (session > 0) {
2256 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002257 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002258 if (mType != DIRECT) {
2259 size_t numSamples = mNormalFrameCount * mChannelCount;
2260 buffer = new int16_t[numSamples];
2261 memset(buffer, 0, numSamples * sizeof(int16_t));
2262 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2263 ownsBuffer = true;
2264 }
2265
2266 // Attach all tracks with same session ID to this chain.
2267 for (size_t i = 0; i < mTracks.size(); ++i) {
2268 sp<Track> track = mTracks[i];
2269 if (session == track->sessionId()) {
2270 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2271 buffer);
2272 track->setMainBuffer(buffer);
2273 chain->incTrackCnt();
2274 }
2275 }
2276
2277 // indicate all active tracks in the chain
2278 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2279 sp<Track> track = mActiveTracks[i].promote();
2280 if (track == 0) {
2281 continue;
2282 }
2283 if (session == track->sessionId()) {
2284 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2285 chain->incActiveTrackCnt();
2286 }
2287 }
2288 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002289 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08002290 chain->setInBuffer(buffer, ownsBuffer);
Andy Hung010a1a12014-03-13 13:57:33 -07002291 chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled
2292 ? mEffectBuffer : mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002293 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
2294 // chains list in order to be processed last as it contains output stage effects
2295 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2296 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
2297 // after track specific effects and before output stage
2298 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
2299 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
2300 // Effect chain for other sessions are inserted at beginning of effect
2301 // chains list to be processed before output mix effects. Relative order between other
2302 // sessions is not important
2303 size_t size = mEffectChains.size();
2304 size_t i = 0;
2305 for (i = 0; i < size; i++) {
2306 if (mEffectChains[i]->sessionId() < session) {
2307 break;
2308 }
2309 }
2310 mEffectChains.insertAt(chain, i);
2311 checkSuspendOnAddEffectChain_l(chain);
2312
2313 return NO_ERROR;
2314}
2315
2316size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2317{
2318 int session = chain->sessionId();
2319
2320 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2321
2322 for (size_t i = 0; i < mEffectChains.size(); i++) {
2323 if (chain == mEffectChains[i]) {
2324 mEffectChains.removeAt(i);
2325 // detach all active tracks from the chain
2326 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2327 sp<Track> track = mActiveTracks[i].promote();
2328 if (track == 0) {
2329 continue;
2330 }
2331 if (session == track->sessionId()) {
2332 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2333 chain.get(), session);
2334 chain->decActiveTrackCnt();
2335 }
2336 }
2337
2338 // detach all tracks with same session ID from this chain
2339 for (size_t i = 0; i < mTracks.size(); ++i) {
2340 sp<Track> track = mTracks[i];
2341 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002342 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002343 chain->decTrackCnt();
2344 }
2345 }
2346 break;
2347 }
2348 }
2349 return mEffectChains.size();
2350}
2351
2352status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2353 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2354{
2355 Mutex::Autolock _l(mLock);
2356 return attachAuxEffect_l(track, EffectId);
2357}
2358
2359status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2360 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2361{
2362 status_t status = NO_ERROR;
2363
2364 if (EffectId == 0) {
2365 track->setAuxBuffer(0, NULL);
2366 } else {
2367 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2368 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2369 if (effect != 0) {
2370 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2371 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2372 } else {
2373 status = INVALID_OPERATION;
2374 }
2375 } else {
2376 status = BAD_VALUE;
2377 }
2378 }
2379 return status;
2380}
2381
2382void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2383{
2384 for (size_t i = 0; i < mTracks.size(); ++i) {
2385 sp<Track> track = mTracks[i];
2386 if (track->auxEffectId() == effectId) {
2387 attachAuxEffect_l(track, 0);
2388 }
2389 }
2390}
2391
2392bool AudioFlinger::PlaybackThread::threadLoop()
2393{
2394 Vector< sp<Track> > tracksToRemove;
2395
2396 standbyTime = systemTime();
2397
2398 // MIXER
2399 nsecs_t lastWarning = 0;
2400
2401 // DUPLICATING
2402 // FIXME could this be made local to while loop?
2403 writeFrames = 0;
2404
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002405 int lastGeneration = 0;
2406
Eric Laurent81784c32012-11-19 14:55:58 -08002407 cacheParameters_l();
2408 sleepTime = idleSleepTime;
2409
2410 if (mType == MIXER) {
2411 sleepTimeShift = 0;
2412 }
2413
2414 CpuStats cpuStats;
2415 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2416
2417 acquireWakeLock();
2418
Glenn Kasten9e58b552013-01-18 15:09:48 -08002419 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2420 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2421 // and then that string will be logged at the next convenient opportunity.
2422 const char *logString = NULL;
2423
Eric Laurent664539d2013-09-23 18:24:31 -07002424 checkSilentMode_l();
2425
Eric Laurent81784c32012-11-19 14:55:58 -08002426 while (!exitPending())
2427 {
2428 cpuStats.sample(myName);
2429
2430 Vector< sp<EffectChain> > effectChains;
2431
Eric Laurent81784c32012-11-19 14:55:58 -08002432 { // scope for mLock
2433
2434 Mutex::Autolock _l(mLock);
2435
Eric Laurent021cf962014-05-13 10:18:14 -07002436 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07002437
Glenn Kasten9e58b552013-01-18 15:09:48 -08002438 if (logString != NULL) {
2439 mNBLogWriter->logTimestamp();
2440 mNBLogWriter->log(logString);
2441 logString = NULL;
2442 }
2443
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002444 // Gather the framesReleased counters for all active tracks,
2445 // and latch them atomically with the timestamp.
2446 // FIXME We're using raw pointers as indices. A unique track ID would be a better index.
2447 mLatchD.mFramesReleased.clear();
2448 size_t size = mActiveTracks.size();
2449 for (size_t i = 0; i < size; i++) {
2450 sp<Track> t = mActiveTracks[i].promote();
2451 if (t != 0) {
2452 mLatchD.mFramesReleased.add(t.get(),
2453 t->mAudioTrackServerProxy->framesReleased());
2454 }
2455 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002456 if (mLatchDValid) {
2457 mLatchQ = mLatchD;
2458 mLatchDValid = false;
2459 mLatchQValid = true;
2460 }
2461
Eric Laurent81784c32012-11-19 14:55:58 -08002462 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002463 if (mSignalPending) {
2464 // A signal was raised while we were unlocked
2465 mSignalPending = false;
2466 } else if (waitingAsyncCallback_l()) {
2467 if (exitPending()) {
2468 break;
2469 }
2470 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002471 mWakeLockUids.clear();
2472 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002473 ALOGV("wait async completion");
2474 mWaitWorkCV.wait(mLock);
2475 ALOGV("async completion/wake");
2476 acquireWakeLock_l();
Eric Laurent972a1732013-09-04 09:42:59 -07002477 standbyTime = systemTime() + standbyDelay;
2478 sleepTime = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002479
2480 continue;
2481 }
2482 if ((!mActiveTracks.size() && systemTime() > standbyTime) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08002483 isSuspended()) {
2484 // put audio hardware into standby after short delay
2485 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002486
2487 threadLoop_standby();
2488
2489 mStandby = true;
2490 }
2491
2492 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2493 // we're about to wait, flush the binder command buffer
2494 IPCThreadState::self()->flushCommands();
2495
2496 clearOutputTracks();
2497
2498 if (exitPending()) {
2499 break;
2500 }
2501
2502 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002503 mWakeLockUids.clear();
2504 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002505 // wait until we have something to do...
2506 ALOGV("%s going to sleep", myName.string());
2507 mWaitWorkCV.wait(mLock);
2508 ALOGV("%s waking up", myName.string());
2509 acquireWakeLock_l();
2510
2511 mMixerStatus = MIXER_IDLE;
2512 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2513 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002514 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002515 checkSilentMode_l();
2516
2517 standbyTime = systemTime() + standbyDelay;
2518 sleepTime = idleSleepTime;
2519 if (mType == MIXER) {
2520 sleepTimeShift = 0;
2521 }
2522
2523 continue;
2524 }
2525 }
Eric Laurent81784c32012-11-19 14:55:58 -08002526 // mMixerStatusIgnoringFastTracks is also updated internally
2527 mMixerStatus = prepareTracks_l(&tracksToRemove);
2528
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002529 // compare with previously applied list
2530 if (lastGeneration != mActiveTracksGeneration) {
2531 // update wakelock
2532 updateWakeLockUids_l(mWakeLockUids);
2533 lastGeneration = mActiveTracksGeneration;
2534 }
2535
Eric Laurent81784c32012-11-19 14:55:58 -08002536 // prevent any changes in effect chain list and in each effect chain
2537 // during mixing and effect process as the audio buffers could be deleted
2538 // or modified if an effect is created or deleted
2539 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002540 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08002541
Eric Laurentbfb1b832013-01-07 09:53:42 -08002542 if (mBytesRemaining == 0) {
2543 mCurrentWriteLength = 0;
2544 if (mMixerStatus == MIXER_TRACKS_READY) {
2545 // threadLoop_mix() sets mCurrentWriteLength
2546 threadLoop_mix();
2547 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
2548 && (mMixerStatus != MIXER_DRAIN_ALL)) {
2549 // threadLoop_sleepTime sets sleepTime to 0 if data
2550 // must be written to HAL
2551 threadLoop_sleepTime();
2552 if (sleepTime == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08002553 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002554 }
2555 }
Andy Hung98ef9782014-03-04 14:46:50 -08002556 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
2557 // mMixerBuffer with data if mMixerBufferValid is true and sleepTime == 0.
2558 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
2559 // or mSinkBuffer (if there are no effects).
2560 //
2561 // This is done pre-effects computation; if effects change to
2562 // support higher precision, this needs to move.
2563 //
2564 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
2565 // TODO use sleepTime == 0 as an additional condition.
2566 if (mMixerBufferValid) {
2567 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
2568 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
2569
2570 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
2571 mNormalFrameCount * mChannelCount);
2572 }
2573
Eric Laurentbfb1b832013-01-07 09:53:42 -08002574 mBytesRemaining = mCurrentWriteLength;
2575 if (isSuspended()) {
2576 sleepTime = suspendSleepTimeUs();
2577 // simulate write to HAL when suspended
Andy Hung25c2dac2014-02-27 14:56:00 -08002578 mBytesWritten += mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002579 mBytesRemaining = 0;
2580 }
Eric Laurent81784c32012-11-19 14:55:58 -08002581
Eric Laurentbfb1b832013-01-07 09:53:42 -08002582 // only process effects if we're going to write
Eric Laurent59fe0102013-09-27 18:48:26 -07002583 if (sleepTime == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002584 for (size_t i = 0; i < effectChains.size(); i ++) {
2585 effectChains[i]->process_l();
2586 }
Eric Laurent81784c32012-11-19 14:55:58 -08002587 }
2588 }
Eric Laurent59fe0102013-09-27 18:48:26 -07002589 // Process effect chains for offloaded thread even if no audio
2590 // was read from audio track: process only updates effect state
2591 // and thus does have to be synchronized with audio writes but may have
2592 // to be called while waiting for async write callback
2593 if (mType == OFFLOAD) {
2594 for (size_t i = 0; i < effectChains.size(); i ++) {
2595 effectChains[i]->process_l();
2596 }
2597 }
Eric Laurent81784c32012-11-19 14:55:58 -08002598
Andy Hung98ef9782014-03-04 14:46:50 -08002599 // Only if the Effects buffer is enabled and there is data in the
2600 // Effects buffer (buffer valid), we need to
2601 // copy into the sink buffer.
2602 // TODO use sleepTime == 0 as an additional condition.
2603 if (mEffectBufferValid) {
2604 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
2605 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
2606 mNormalFrameCount * mChannelCount);
2607 }
2608
Eric Laurent81784c32012-11-19 14:55:58 -08002609 // enable changes in effect chain
2610 unlockEffectChains(effectChains);
2611
Eric Laurentbfb1b832013-01-07 09:53:42 -08002612 if (!waitingAsyncCallback()) {
2613 // sleepTime == 0 means we must write to audio hardware
2614 if (sleepTime == 0) {
2615 if (mBytesRemaining) {
2616 ssize_t ret = threadLoop_write();
2617 if (ret < 0) {
2618 mBytesRemaining = 0;
2619 } else {
2620 mBytesWritten += ret;
2621 mBytesRemaining -= ret;
2622 }
2623 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
2624 (mMixerStatus == MIXER_DRAIN_ALL)) {
2625 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08002626 }
Glenn Kasten4944acb2013-08-19 08:39:20 -07002627 if (mType == MIXER) {
2628 // write blocked detection
2629 nsecs_t now = systemTime();
2630 nsecs_t delta = now - mLastWriteTime;
2631 if (!mStandby && delta > maxPeriod) {
2632 mNumDelayedWrites++;
2633 if ((now - lastWarning) > kWarningThrottleNs) {
2634 ATRACE_NAME("underrun");
2635 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2636 ns2ms(delta), mNumDelayedWrites, this);
2637 lastWarning = now;
2638 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002639 }
2640 }
Eric Laurent81784c32012-11-19 14:55:58 -08002641
Eric Laurentbfb1b832013-01-07 09:53:42 -08002642 } else {
2643 usleep(sleepTime);
2644 }
Eric Laurent81784c32012-11-19 14:55:58 -08002645 }
2646
2647 // Finally let go of removed track(s), without the lock held
2648 // since we can't guarantee the destructors won't acquire that
2649 // same lock. This will also mutate and push a new fast mixer state.
2650 threadLoop_removeTracks(tracksToRemove);
2651 tracksToRemove.clear();
2652
2653 // FIXME I don't understand the need for this here;
2654 // it was in the original code but maybe the
2655 // assignment in saveOutputTracks() makes this unnecessary?
2656 clearOutputTracks();
2657
2658 // Effect chains will be actually deleted here if they were removed from
2659 // mEffectChains list during mixing or effects processing
2660 effectChains.clear();
2661
2662 // FIXME Note that the above .clear() is no longer necessary since effectChains
2663 // is now local to this block, but will keep it for now (at least until merge done).
2664 }
2665
Eric Laurentbfb1b832013-01-07 09:53:42 -08002666 threadLoop_exit();
2667
Eric Laurentcf817a22014-08-04 20:36:31 -07002668 if (!mStandby) {
2669 threadLoop_standby();
2670 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08002671 }
2672
2673 releaseWakeLock();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002674 mWakeLockUids.clear();
2675 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002676
2677 ALOGV("Thread %p type %d exiting", this, mType);
2678 return false;
2679}
2680
Eric Laurentbfb1b832013-01-07 09:53:42 -08002681// removeTracks_l() must be called with ThreadBase::mLock held
2682void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
2683{
2684 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002685 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002686 for (size_t i=0 ; i<count ; i++) {
2687 const sp<Track>& track = tracksToRemove.itemAt(i);
2688 mActiveTracks.remove(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002689 mWakeLockUids.remove(track->uid());
2690 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002691 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
2692 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2693 if (chain != 0) {
2694 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
2695 track->sessionId());
2696 chain->decActiveTrackCnt();
2697 }
2698 if (track->isTerminated()) {
2699 removeTrack_l(track);
2700 }
2701 }
2702 }
2703
2704}
Eric Laurent81784c32012-11-19 14:55:58 -08002705
Eric Laurentaccc1472013-09-20 09:36:34 -07002706status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
2707{
2708 if (mNormalSink != 0) {
2709 return mNormalSink->getTimestamp(timestamp);
2710 }
Andy Hung9a1c8892014-12-03 11:37:42 -08002711 if ((mType == OFFLOAD || mType == DIRECT)
2712 && mOutput != NULL && mOutput->stream->get_presentation_position) {
Eric Laurentaccc1472013-09-20 09:36:34 -07002713 uint64_t position64;
2714 int ret = mOutput->stream->get_presentation_position(
2715 mOutput->stream, &position64, &timestamp.mTime);
2716 if (ret == 0) {
2717 timestamp.mPosition = (uint32_t)position64;
2718 return NO_ERROR;
2719 }
2720 }
2721 return INVALID_OPERATION;
2722}
Eric Laurent1c333e22014-05-20 10:48:17 -07002723
2724status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
2725 audio_patch_handle_t *handle)
2726{
2727 status_t status = NO_ERROR;
2728 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
2729 // store new device and send to effects
2730 audio_devices_t type = AUDIO_DEVICE_NONE;
2731 for (unsigned int i = 0; i < patch->num_sinks; i++) {
2732 type |= patch->sinks[i].ext.device.type;
2733 }
2734 mOutDevice = type;
2735 for (size_t i = 0; i < mEffectChains.size(); i++) {
2736 mEffectChains[i]->setDevice_l(mOutDevice);
2737 }
2738
2739 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
2740 status = hwDevice->create_audio_patch(hwDevice,
2741 patch->num_sources,
2742 patch->sources,
2743 patch->num_sinks,
2744 patch->sinks,
2745 handle);
2746 } else {
2747 ALOG_ASSERT(false, "createAudioPatch_l() called on a pre 3.0 HAL");
2748 }
2749 return status;
2750}
2751
2752status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
2753{
2754 status_t status = NO_ERROR;
2755 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
2756 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
2757 status = hwDevice->release_audio_patch(hwDevice, handle);
2758 } else {
2759 ALOG_ASSERT(false, "releaseAudioPatch_l() called on a pre 3.0 HAL");
2760 }
2761 return status;
2762}
2763
Eric Laurent83b88082014-06-20 18:31:16 -07002764void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
2765{
2766 Mutex::Autolock _l(mLock);
2767 mTracks.add(track);
2768}
2769
2770void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
2771{
2772 Mutex::Autolock _l(mLock);
2773 destroyTrack_l(track);
2774}
2775
2776void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
2777{
2778 ThreadBase::getAudioPortConfig(config);
2779 config->role = AUDIO_PORT_ROLE_SOURCE;
2780 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
2781 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
2782}
2783
Eric Laurent81784c32012-11-19 14:55:58 -08002784// ----------------------------------------------------------------------------
2785
2786AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
2787 audio_io_handle_t id, audio_devices_t device, type_t type)
2788 : PlaybackThread(audioFlinger, output, id, device, type),
2789 // mAudioMixer below
2790 // mFastMixer below
2791 mFastMixerFutex(0)
2792 // mOutputSink below
2793 // mPipeSink below
2794 // mNormalSink below
2795{
2796 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07002797 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, "
Eric Laurent81784c32012-11-19 14:55:58 -08002798 "mFrameCount=%d, mNormalFrameCount=%d",
2799 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2800 mNormalFrameCount);
2801 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2802
Eric Laurent81784c32012-11-19 14:55:58 -08002803 // create an NBAIO sink for the HAL output stream, and negotiate
2804 mOutputSink = new AudioStreamOutSink(output->stream);
2805 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08002806 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Eric Laurent81784c32012-11-19 14:55:58 -08002807 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2808 ALOG_ASSERT(index == 0);
2809
2810 // initialize fast mixer depending on configuration
2811 bool initFastMixer;
2812 switch (kUseFastMixer) {
2813 case FastMixer_Never:
2814 initFastMixer = false;
2815 break;
2816 case FastMixer_Always:
2817 initFastMixer = true;
2818 break;
2819 case FastMixer_Static:
2820 case FastMixer_Dynamic:
2821 initFastMixer = mFrameCount < mNormalFrameCount;
2822 break;
2823 }
2824 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07002825 audio_format_t fastMixerFormat;
2826 if (mMixerBufferEnabled && mEffectBufferEnabled) {
2827 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
2828 } else {
2829 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
2830 }
2831 if (mFormat != fastMixerFormat) {
2832 // change our Sink format to accept our intermediate precision
2833 mFormat = fastMixerFormat;
2834 free(mSinkBuffer);
2835 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2836 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
2837 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
2838 }
Eric Laurent81784c32012-11-19 14:55:58 -08002839
2840 // create a MonoPipe to connect our submix to FastMixer
2841 NBAIO_Format format = mOutputSink->format();
Glenn Kastenba0b34c2014-09-28 13:06:06 -07002842 NBAIO_Format origformat = format;
Andy Hung1258c1a2014-05-23 21:22:17 -07002843 // adjust format to match that of the Fast Mixer
2844 format.mFormat = fastMixerFormat;
2845 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
2846
Eric Laurent81784c32012-11-19 14:55:58 -08002847 // This pipe depth compensates for scheduling latency of the normal mixer thread.
2848 // When it wakes up after a maximum latency, it runs a few cycles quickly before
2849 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
2850 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
2851 const NBAIO_Format offers[1] = {format};
2852 size_t numCounterOffers = 0;
2853 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2854 ALOG_ASSERT(index == 0);
2855 monoPipe->setAvgFrames((mScreenState & 1) ?
2856 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2857 mPipeSink = monoPipe;
2858
Glenn Kasten46909e72013-02-26 09:20:22 -08002859#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08002860 if (mTeeSinkOutputEnabled) {
2861 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07002862 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
2863 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08002864 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07002865 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08002866 ALOG_ASSERT(index == 0);
2867 mTeeSink = teeSink;
2868 PipeReader *teeSource = new PipeReader(*teeSink);
2869 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07002870 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08002871 ALOG_ASSERT(index == 0);
2872 mTeeSource = teeSource;
2873 }
Glenn Kasten46909e72013-02-26 09:20:22 -08002874#endif
Eric Laurent81784c32012-11-19 14:55:58 -08002875
2876 // create fast mixer and configure it initially with just one fast track for our submix
2877 mFastMixer = new FastMixer();
2878 FastMixerStateQueue *sq = mFastMixer->sq();
2879#ifdef STATE_QUEUE_DUMP
2880 sq->setObserverDump(&mStateQueueObserverDump);
2881 sq->setMutatorDump(&mStateQueueMutatorDump);
2882#endif
2883 FastMixerState *state = sq->begin();
2884 FastTrack *fastTrack = &state->mFastTracks[0];
2885 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2886 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2887 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07002888 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
2889 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08002890 fastTrack->mGeneration++;
2891 state->mFastTracksGen++;
2892 state->mTrackMask = 1;
2893 // fast mixer will use the HAL output sink
2894 state->mOutputSink = mOutputSink.get();
2895 state->mOutputSinkGen++;
2896 state->mFrameCount = mFrameCount;
2897 state->mCommand = FastMixerState::COLD_IDLE;
2898 // already done in constructor initialization list
2899 //mFastMixerFutex = 0;
2900 state->mColdFutexAddr = &mFastMixerFutex;
2901 state->mColdGen++;
2902 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08002903#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08002904 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08002905#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08002906 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
2907 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08002908 sq->end();
2909 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2910
2911 // start the fast mixer
2912 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
2913 pid_t tid = mFastMixer->getTid();
2914 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2915 if (err != 0) {
2916 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2917 kPriorityFastMixer, getpid_cached, tid, err);
2918 }
2919
2920#ifdef AUDIO_WATCHDOG
2921 // create and start the watchdog
2922 mAudioWatchdog = new AudioWatchdog();
2923 mAudioWatchdog->setDump(&mAudioWatchdogDump);
2924 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
2925 tid = mAudioWatchdog->getTid();
2926 err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2927 if (err != 0) {
2928 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2929 kPriorityFastMixer, getpid_cached, tid, err);
2930 }
2931#endif
2932
Eric Laurent81784c32012-11-19 14:55:58 -08002933 }
2934
2935 switch (kUseFastMixer) {
2936 case FastMixer_Never:
2937 case FastMixer_Dynamic:
2938 mNormalSink = mOutputSink;
2939 break;
2940 case FastMixer_Always:
2941 mNormalSink = mPipeSink;
2942 break;
2943 case FastMixer_Static:
2944 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2945 break;
2946 }
2947}
2948
2949AudioFlinger::MixerThread::~MixerThread()
2950{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07002951 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002952 FastMixerStateQueue *sq = mFastMixer->sq();
2953 FastMixerState *state = sq->begin();
2954 if (state->mCommand == FastMixerState::COLD_IDLE) {
2955 int32_t old = android_atomic_inc(&mFastMixerFutex);
2956 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07002957 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08002958 }
2959 }
2960 state->mCommand = FastMixerState::EXIT;
2961 sq->end();
2962 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2963 mFastMixer->join();
2964 // Though the fast mixer thread has exited, it's state queue is still valid.
2965 // We'll use that extract the final state which contains one remaining fast track
2966 // corresponding to our sub-mix.
2967 state = sq->begin();
2968 ALOG_ASSERT(state->mTrackMask == 1);
2969 FastTrack *fastTrack = &state->mFastTracks[0];
2970 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2971 delete fastTrack->mBufferProvider;
2972 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07002973 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08002974#ifdef AUDIO_WATCHDOG
2975 if (mAudioWatchdog != 0) {
2976 mAudioWatchdog->requestExit();
2977 mAudioWatchdog->requestExitAndWait();
2978 mAudioWatchdog.clear();
2979 }
2980#endif
2981 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08002982 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08002983 delete mAudioMixer;
2984}
2985
2986
2987uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
2988{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07002989 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002990 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2991 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
2992 }
2993 return latency;
2994}
2995
2996
2997void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2998{
2999 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3000}
3001
Eric Laurentbfb1b832013-01-07 09:53:42 -08003002ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003003{
3004 // FIXME we should only do one push per cycle; confirm this is true
3005 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003006 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003007 FastMixerStateQueue *sq = mFastMixer->sq();
3008 FastMixerState *state = sq->begin();
3009 if (state->mCommand != FastMixerState::MIX_WRITE &&
3010 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3011 if (state->mCommand == FastMixerState::COLD_IDLE) {
3012 int32_t old = android_atomic_inc(&mFastMixerFutex);
3013 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003014 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003015 }
3016#ifdef AUDIO_WATCHDOG
3017 if (mAudioWatchdog != 0) {
3018 mAudioWatchdog->resume();
3019 }
3020#endif
3021 }
3022 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003023 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
3024 FastMixerDumpState::kSamplingNforLowRamDevice : FastMixerDumpState::kSamplingN);
Eric Laurent81784c32012-11-19 14:55:58 -08003025 sq->end();
3026 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3027 if (kUseFastMixer == FastMixer_Dynamic) {
3028 mNormalSink = mPipeSink;
3029 }
3030 } else {
3031 sq->end(false /*didModify*/);
3032 }
3033 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003034 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003035}
3036
3037void AudioFlinger::MixerThread::threadLoop_standby()
3038{
3039 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003040 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003041 FastMixerStateQueue *sq = mFastMixer->sq();
3042 FastMixerState *state = sq->begin();
3043 if (!(state->mCommand & FastMixerState::IDLE)) {
3044 state->mCommand = FastMixerState::COLD_IDLE;
3045 state->mColdFutexAddr = &mFastMixerFutex;
3046 state->mColdGen++;
3047 mFastMixerFutex = 0;
3048 sq->end();
3049 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3050 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3051 if (kUseFastMixer == FastMixer_Dynamic) {
3052 mNormalSink = mOutputSink;
3053 }
3054#ifdef AUDIO_WATCHDOG
3055 if (mAudioWatchdog != 0) {
3056 mAudioWatchdog->pause();
3057 }
3058#endif
3059 } else {
3060 sq->end(false /*didModify*/);
3061 }
3062 }
3063 PlaybackThread::threadLoop_standby();
3064}
3065
Eric Laurentbfb1b832013-01-07 09:53:42 -08003066bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3067{
3068 return false;
3069}
3070
3071bool AudioFlinger::PlaybackThread::shouldStandby_l()
3072{
3073 return !mStandby;
3074}
3075
3076bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3077{
3078 Mutex::Autolock _l(mLock);
3079 return waitingAsyncCallback_l();
3080}
3081
Eric Laurent81784c32012-11-19 14:55:58 -08003082// shared by MIXER and DIRECT, overridden by DUPLICATING
3083void AudioFlinger::PlaybackThread::threadLoop_standby()
3084{
3085 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
3086 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003087 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003088 // discard any pending drain or write ack by incrementing sequence
3089 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3090 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003091 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003092 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3093 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003094 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003095 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003096}
3097
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003098void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3099{
3100 ALOGV("signal playback thread");
3101 broadcast_l();
3102}
3103
Eric Laurent81784c32012-11-19 14:55:58 -08003104void AudioFlinger::MixerThread::threadLoop_mix()
3105{
3106 // obtain the presentation timestamp of the next output buffer
3107 int64_t pts;
3108 status_t status = INVALID_OPERATION;
3109
3110 if (mNormalSink != 0) {
3111 status = mNormalSink->getNextWriteTimestamp(&pts);
3112 } else {
3113 status = mOutputSink->getNextWriteTimestamp(&pts);
3114 }
3115
3116 if (status != NO_ERROR) {
3117 pts = AudioBufferProvider::kInvalidPTS;
3118 }
3119
3120 // mix buffers...
3121 mAudioMixer->process(pts);
Andy Hung25c2dac2014-02-27 14:56:00 -08003122 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003123 // increase sleep time progressively when application underrun condition clears.
3124 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3125 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3126 // such that we would underrun the audio HAL.
3127 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
3128 sleepTimeShift--;
3129 }
3130 sleepTime = 0;
3131 standbyTime = systemTime() + standbyDelay;
3132 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003133
Eric Laurent81784c32012-11-19 14:55:58 -08003134}
3135
3136void AudioFlinger::MixerThread::threadLoop_sleepTime()
3137{
3138 // If no tracks are ready, sleep once for the duration of an output
3139 // buffer size, then write 0s to the output
3140 if (sleepTime == 0) {
3141 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3142 sleepTime = activeSleepTime >> sleepTimeShift;
3143 if (sleepTime < kMinThreadSleepTimeUs) {
3144 sleepTime = kMinThreadSleepTimeUs;
3145 }
3146 // reduce sleep time in case of consecutive application underruns to avoid
3147 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3148 // duration we would end up writing less data than needed by the audio HAL if
3149 // the condition persists.
3150 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3151 sleepTimeShift++;
3152 }
3153 } else {
3154 sleepTime = idleSleepTime;
3155 }
3156 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003157 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3158 // before effects processing or output.
3159 if (mMixerBufferValid) {
3160 memset(mMixerBuffer, 0, mMixerBufferSize);
3161 } else {
3162 memset(mSinkBuffer, 0, mSinkBufferSize);
3163 }
Eric Laurent81784c32012-11-19 14:55:58 -08003164 sleepTime = 0;
3165 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3166 "anticipated start");
3167 }
3168 // TODO add standby time extension fct of effect tail
3169}
3170
3171// prepareTracks_l() must be called with ThreadBase::mLock held
3172AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3173 Vector< sp<Track> > *tracksToRemove)
3174{
3175
3176 mixer_state mixerStatus = MIXER_IDLE;
3177 // find out which tracks need to be processed
3178 size_t count = mActiveTracks.size();
3179 size_t mixedTracks = 0;
3180 size_t tracksWithEffect = 0;
3181 // counts only _active_ fast tracks
3182 size_t fastTracks = 0;
3183 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
3184
3185 float masterVolume = mMasterVolume;
3186 bool masterMute = mMasterMute;
3187
3188 if (masterMute) {
3189 masterVolume = 0;
3190 }
3191 // Delegate master volume control to effect in output mix effect chain if needed
3192 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3193 if (chain != 0) {
3194 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
3195 chain->setVolume_l(&v, &v);
3196 masterVolume = (float)((v + (1 << 23)) >> 24);
3197 chain.clear();
3198 }
3199
3200 // prepare a new state to push
3201 FastMixerStateQueue *sq = NULL;
3202 FastMixerState *state = NULL;
3203 bool didModify = false;
3204 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003205 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003206 sq = mFastMixer->sq();
3207 state = sq->begin();
3208 }
3209
Andy Hung69aed5f2014-02-25 17:24:40 -08003210 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08003211 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08003212
Eric Laurent81784c32012-11-19 14:55:58 -08003213 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003214 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003215 if (t == 0) {
3216 continue;
3217 }
3218
3219 // this const just means the local variable doesn't change
3220 Track* const track = t.get();
3221
3222 // process fast tracks
3223 if (track->isFastTrack()) {
3224
3225 // It's theoretically possible (though unlikely) for a fast track to be created
3226 // and then removed within the same normal mix cycle. This is not a problem, as
3227 // the track never becomes active so it's fast mixer slot is never touched.
3228 // The converse, of removing an (active) track and then creating a new track
3229 // at the identical fast mixer slot within the same normal mix cycle,
3230 // is impossible because the slot isn't marked available until the end of each cycle.
3231 int j = track->mFastIndex;
3232 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
3233 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
3234 FastTrack *fastTrack = &state->mFastTracks[j];
3235
3236 // Determine whether the track is currently in underrun condition,
3237 // and whether it had a recent underrun.
3238 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
3239 FastTrackUnderruns underruns = ftDump->mUnderruns;
3240 uint32_t recentFull = (underruns.mBitFields.mFull -
3241 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
3242 uint32_t recentPartial = (underruns.mBitFields.mPartial -
3243 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
3244 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
3245 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
3246 uint32_t recentUnderruns = recentPartial + recentEmpty;
3247 track->mObservedUnderruns = underruns;
3248 // don't count underruns that occur while stopping or pausing
3249 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07003250 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
3251 recentUnderruns > 0) {
3252 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
3253 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003254 }
3255
3256 // This is similar to the state machine for normal tracks,
3257 // with a few modifications for fast tracks.
3258 bool isActive = true;
3259 switch (track->mState) {
3260 case TrackBase::STOPPING_1:
3261 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08003262 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003263 track->mState = TrackBase::STOPPING_2;
3264 }
3265 break;
3266 case TrackBase::PAUSING:
3267 // ramp down is not yet implemented
3268 track->setPaused();
3269 break;
3270 case TrackBase::RESUMING:
3271 // ramp up is not yet implemented
3272 track->mState = TrackBase::ACTIVE;
3273 break;
3274 case TrackBase::ACTIVE:
3275 if (recentFull > 0 || recentPartial > 0) {
3276 // track has provided at least some frames recently: reset retry count
3277 track->mRetryCount = kMaxTrackRetries;
3278 }
3279 if (recentUnderruns == 0) {
3280 // no recent underruns: stay active
3281 break;
3282 }
3283 // there has recently been an underrun of some kind
3284 if (track->sharedBuffer() == 0) {
3285 // were any of the recent underruns "empty" (no frames available)?
3286 if (recentEmpty == 0) {
3287 // no, then ignore the partial underruns as they are allowed indefinitely
3288 break;
3289 }
3290 // there has recently been an "empty" underrun: decrement the retry counter
3291 if (--(track->mRetryCount) > 0) {
3292 break;
3293 }
3294 // indicate to client process that the track was disabled because of underrun;
3295 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003296 android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003297 // remove from active list, but state remains ACTIVE [confusing but true]
3298 isActive = false;
3299 break;
3300 }
3301 // fall through
3302 case TrackBase::STOPPING_2:
3303 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003304 case TrackBase::STOPPED:
3305 case TrackBase::FLUSHED: // flush() while active
3306 // Check for presentation complete if track is inactive
3307 // We have consumed all the buffers of this track.
3308 // This would be incomplete if we auto-paused on underrun
3309 {
3310 size_t audioHALFrames =
3311 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3312 size_t framesWritten = mBytesWritten / mFrameSize;
3313 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
3314 // track stays in active list until presentation is complete
3315 break;
3316 }
3317 }
3318 if (track->isStopping_2()) {
3319 track->mState = TrackBase::STOPPED;
3320 }
3321 if (track->isStopped()) {
3322 // Can't reset directly, as fast mixer is still polling this track
3323 // track->reset();
3324 // So instead mark this track as needing to be reset after push with ack
3325 resetMask |= 1 << i;
3326 }
3327 isActive = false;
3328 break;
3329 case TrackBase::IDLE:
3330 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08003331 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08003332 }
3333
3334 if (isActive) {
3335 // was it previously inactive?
3336 if (!(state->mTrackMask & (1 << j))) {
3337 ExtendedAudioBufferProvider *eabp = track;
3338 VolumeProvider *vp = track;
3339 fastTrack->mBufferProvider = eabp;
3340 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08003341 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003342 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08003343 fastTrack->mGeneration++;
3344 state->mTrackMask |= 1 << j;
3345 didModify = true;
3346 // no acknowledgement required for newly active tracks
3347 }
3348 // cache the combined master volume and stream type volume for fast mixer; this
3349 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08003350 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08003351 ++fastTracks;
3352 } else {
3353 // was it previously active?
3354 if (state->mTrackMask & (1 << j)) {
3355 fastTrack->mBufferProvider = NULL;
3356 fastTrack->mGeneration++;
3357 state->mTrackMask &= ~(1 << j);
3358 didModify = true;
3359 // If any fast tracks were removed, we must wait for acknowledgement
3360 // because we're about to decrement the last sp<> on those tracks.
3361 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3362 } else {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003363 LOG_ALWAYS_FATAL("fast track %d should have been active", j);
Eric Laurent81784c32012-11-19 14:55:58 -08003364 }
3365 tracksToRemove->add(track);
3366 // Avoids a misleading display in dumpsys
3367 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
3368 }
3369 continue;
3370 }
3371
3372 { // local variable scope to avoid goto warning
3373
3374 audio_track_cblk_t* cblk = track->cblk();
3375
3376 // The first time a track is added we wait
3377 // for all its buffers to be filled before processing it
3378 int name = track->name();
3379 // make sure that we have enough frames to mix one full buffer.
3380 // enforce this condition only once to enable draining the buffer in case the client
3381 // app does not call stop() and relies on underrun to stop:
3382 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
3383 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003384 size_t desiredFrames;
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003385 uint32_t sr = track->sampleRate();
3386 if (sr == mSampleRate) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003387 desiredFrames = mNormalFrameCount;
3388 } else {
3389 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003390 desiredFrames = (mNormalFrameCount * sr) / mSampleRate + 1 + 1;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003391 // add frames already consumed but not yet released by the resampler
Glenn Kasten2fc14732013-08-05 14:58:14 -07003392 // because mAudioTrackServerProxy->framesReady() will include these frames
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003393 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
Glenn Kasten74935e42013-12-19 08:56:45 -08003394#if 0
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003395 // the minimum track buffer size is normally twice the number of frames necessary
3396 // to fill one buffer and the resampler should not leave more than one buffer worth
3397 // of unreleased frames after each pass, but just in case...
3398 ALOG_ASSERT(desiredFrames <= cblk->frameCount_);
Glenn Kasten74935e42013-12-19 08:56:45 -08003399#endif
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003400 }
Eric Laurent81784c32012-11-19 14:55:58 -08003401 uint32_t minFrames = 1;
3402 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
3403 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003404 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08003405 }
Eric Laurent13e4c962013-12-20 17:36:01 -08003406
3407 size_t framesReady = track->framesReady();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003408 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08003409 !track->isPaused() && !track->isTerminated())
3410 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003411 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003412
3413 mixedTracks++;
3414
Andy Hung69aed5f2014-02-25 17:24:40 -08003415 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
3416 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08003417 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08003418 if (track->mainBuffer() != mSinkBuffer &&
3419 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08003420 if (mEffectBufferEnabled) {
3421 mEffectBufferValid = true; // Later can set directly.
3422 }
Eric Laurent81784c32012-11-19 14:55:58 -08003423 chain = getEffectChain_l(track->sessionId());
3424 // Delegate volume control to effect in track effect chain if needed
3425 if (chain != 0) {
3426 tracksWithEffect++;
3427 } else {
3428 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
3429 "session %d",
3430 name, track->sessionId());
3431 }
3432 }
3433
3434
3435 int param = AudioMixer::VOLUME;
3436 if (track->mFillingUpStatus == Track::FS_FILLED) {
3437 // no ramp for the first volume setting
3438 track->mFillingUpStatus = Track::FS_ACTIVE;
3439 if (track->mState == TrackBase::RESUMING) {
3440 track->mState = TrackBase::ACTIVE;
3441 param = AudioMixer::RAMP_VOLUME;
3442 }
3443 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003444 // FIXME should not make a decision based on mServer
3445 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003446 // If the track is stopped before the first frame was mixed,
3447 // do not apply ramp
3448 param = AudioMixer::RAMP_VOLUME;
3449 }
3450
3451 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07003452 uint32_t vl, vr; // in U8.24 integer format
3453 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08003454 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07003455 vl = vr = 0;
3456 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08003457 if (track->isPausing()) {
3458 track->setPaused();
3459 }
3460 } else {
3461
3462 // read original volumes with volume control
3463 float typeVolume = mStreamTypes[track->streamType()].volume;
3464 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003465 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07003466 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07003467 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
3468 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08003469 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07003470 if (vlf > GAIN_FLOAT_UNITY) {
3471 ALOGV("Track left volume out of range: %.3g", vlf);
3472 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003473 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07003474 if (vrf > GAIN_FLOAT_UNITY) {
3475 ALOGV("Track right volume out of range: %.3g", vrf);
3476 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003477 }
3478 // now apply the master volume and stream type volume
Andy Hung6be49402014-05-30 10:42:03 -07003479 vlf *= v;
3480 vrf *= v;
Eric Laurent81784c32012-11-19 14:55:58 -08003481 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07003482 // then derive vl and vr as U8.24 versions for the effect chain
3483 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
3484 vl = (uint32_t) (scaleto8_24 * vlf);
3485 vr = (uint32_t) (scaleto8_24 * vrf);
3486 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08003487 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08003488 // send level comes from shared memory and so may be corrupt
3489 if (sendLevel > MAX_GAIN_INT) {
3490 ALOGV("Track send level out of range: %04X", sendLevel);
3491 sendLevel = MAX_GAIN_INT;
3492 }
Andy Hung6be49402014-05-30 10:42:03 -07003493 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
3494 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08003495 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003496
Eric Laurent81784c32012-11-19 14:55:58 -08003497 // Delegate volume control to effect in track effect chain if needed
3498 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3499 // Do not ramp volume if volume is controlled by effect
3500 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08003501 // Update remaining floating point volume levels
3502 vlf = (float)vl / (1 << 24);
3503 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08003504 track->mHasVolumeController = true;
3505 } else {
3506 // force no volume ramp when volume controller was just disabled or removed
3507 // from effect chain to avoid volume spike
3508 if (track->mHasVolumeController) {
3509 param = AudioMixer::VOLUME;
3510 }
3511 track->mHasVolumeController = false;
3512 }
3513
Eric Laurent81784c32012-11-19 14:55:58 -08003514 // XXX: these things DON'T need to be done each time
3515 mAudioMixer->setBufferProvider(name, track);
3516 mAudioMixer->enable(name);
3517
Andy Hung6be49402014-05-30 10:42:03 -07003518 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
3519 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
3520 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08003521 mAudioMixer->setParameter(
3522 name,
3523 AudioMixer::TRACK,
3524 AudioMixer::FORMAT, (void *)track->format());
3525 mAudioMixer->setParameter(
3526 name,
3527 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003528 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07003529 mAudioMixer->setParameter(
3530 name,
3531 AudioMixer::TRACK,
3532 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08003533 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07003534 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003535 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08003536 if (reqSampleRate == 0) {
3537 reqSampleRate = mSampleRate;
3538 } else if (reqSampleRate > maxSampleRate) {
3539 reqSampleRate = maxSampleRate;
3540 }
Eric Laurent81784c32012-11-19 14:55:58 -08003541 mAudioMixer->setParameter(
3542 name,
3543 AudioMixer::RESAMPLE,
3544 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003545 (void *)(uintptr_t)reqSampleRate);
Andy Hung69aed5f2014-02-25 17:24:40 -08003546 /*
3547 * Select the appropriate output buffer for the track.
3548 *
Andy Hung98ef9782014-03-04 14:46:50 -08003549 * Tracks with effects go into their own effects chain buffer
3550 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08003551 *
3552 * Other tracks can use mMixerBuffer for higher precision
3553 * channel accumulation. If this buffer is enabled
3554 * (mMixerBufferEnabled true), then selected tracks will accumulate
3555 * into it.
3556 *
3557 */
3558 if (mMixerBufferEnabled
3559 && (track->mainBuffer() == mSinkBuffer
3560 || track->mainBuffer() == mMixerBuffer)) {
3561 mAudioMixer->setParameter(
3562 name,
3563 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08003564 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08003565 mAudioMixer->setParameter(
3566 name,
3567 AudioMixer::TRACK,
3568 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
3569 // TODO: override track->mainBuffer()?
3570 mMixerBufferValid = true;
3571 } else {
3572 mAudioMixer->setParameter(
3573 name,
3574 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08003575 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08003576 mAudioMixer->setParameter(
3577 name,
3578 AudioMixer::TRACK,
3579 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3580 }
Eric Laurent81784c32012-11-19 14:55:58 -08003581 mAudioMixer->setParameter(
3582 name,
3583 AudioMixer::TRACK,
3584 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3585
3586 // reset retry count
3587 track->mRetryCount = kMaxTrackRetries;
3588
3589 // If one track is ready, set the mixer ready if:
3590 // - the mixer was not ready during previous round OR
3591 // - no other track is not ready
3592 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
3593 mixerStatus != MIXER_TRACKS_ENABLED) {
3594 mixerStatus = MIXER_TRACKS_READY;
3595 }
3596 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003597 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Glenn Kasten82aaf942013-07-17 16:05:07 -07003598 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003599 }
Eric Laurent81784c32012-11-19 14:55:58 -08003600 // clear effect chain input buffer if an active track underruns to avoid sending
3601 // previous audio buffer again to effects
3602 chain = getEffectChain_l(track->sessionId());
3603 if (chain != 0) {
3604 chain->clearInputBuffer();
3605 }
3606
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003607 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003608 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3609 track->isStopped() || track->isPaused()) {
3610 // We have consumed all the buffers of this track.
3611 // Remove it from the list of active tracks.
3612 // TODO: use actual buffer filling status instead of latency when available from
3613 // audio HAL
3614 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3615 size_t framesWritten = mBytesWritten / mFrameSize;
3616 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
3617 if (track->isStopped()) {
3618 track->reset();
3619 }
3620 tracksToRemove->add(track);
3621 }
3622 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08003623 // No buffers for this track. Give it a few chances to
3624 // fill a buffer, then remove it from active list.
3625 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08003626 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003627 tracksToRemove->add(track);
3628 // indicate to client process that the track was disabled because of underrun;
3629 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003630 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003631 // If one track is not ready, mark the mixer also not ready if:
3632 // - the mixer was ready during previous round OR
3633 // - no other track is ready
3634 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
3635 mixerStatus != MIXER_TRACKS_READY) {
3636 mixerStatus = MIXER_TRACKS_ENABLED;
3637 }
3638 }
3639 mAudioMixer->disable(name);
3640 }
3641
3642 } // local variable scope to avoid goto warning
3643track_is_ready: ;
3644
3645 }
3646
3647 // Push the new FastMixer state if necessary
3648 bool pauseAudioWatchdog = false;
3649 if (didModify) {
3650 state->mFastTracksGen++;
3651 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3652 if (kUseFastMixer == FastMixer_Dynamic &&
3653 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3654 state->mCommand = FastMixerState::COLD_IDLE;
3655 state->mColdFutexAddr = &mFastMixerFutex;
3656 state->mColdGen++;
3657 mFastMixerFutex = 0;
3658 if (kUseFastMixer == FastMixer_Dynamic) {
3659 mNormalSink = mOutputSink;
3660 }
3661 // If we go into cold idle, need to wait for acknowledgement
3662 // so that fast mixer stops doing I/O.
3663 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3664 pauseAudioWatchdog = true;
3665 }
Eric Laurent81784c32012-11-19 14:55:58 -08003666 }
3667 if (sq != NULL) {
3668 sq->end(didModify);
3669 sq->push(block);
3670 }
3671#ifdef AUDIO_WATCHDOG
3672 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3673 mAudioWatchdog->pause();
3674 }
3675#endif
3676
3677 // Now perform the deferred reset on fast tracks that have stopped
3678 while (resetMask != 0) {
3679 size_t i = __builtin_ctz(resetMask);
3680 ALOG_ASSERT(i < count);
3681 resetMask &= ~(1 << i);
3682 sp<Track> t = mActiveTracks[i].promote();
3683 if (t == 0) {
3684 continue;
3685 }
3686 Track* track = t.get();
3687 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3688 track->reset();
3689 }
3690
3691 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08003692 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08003693
Eric Laurent97d547d2014-09-02 14:45:53 -07003694 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
3695 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07003696 }
3697
3698 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07003699 // as long as there are effects we should clear the effects buffer, to avoid
3700 // passing a non-clean buffer to the effect chain
3701 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07003702 }
Andy Hung69aed5f2014-02-25 17:24:40 -08003703 // sink or mix buffer must be cleared if all tracks are connected to an
3704 // effect chain as in this case the mixer will not write to the sink or mix buffer
3705 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08003706 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3707 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08003708 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08003709 if (mMixerBufferValid) {
3710 memset(mMixerBuffer, 0, mMixerBufferSize);
3711 // TODO: In testing, mSinkBuffer below need not be cleared because
3712 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
3713 // after mixing.
3714 //
3715 // To enforce this guarantee:
3716 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3717 // (mixedTracks == 0 && fastTracks > 0))
3718 // must imply MIXER_TRACKS_READY.
3719 // Later, we may clear buffers regardless, and skip much of this logic.
3720 }
Andy Hung98ef9782014-03-04 14:46:50 -08003721 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07003722 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003723 }
3724
3725 // if any fast tracks, then status is ready
3726 mMixerStatusIgnoringFastTracks = mixerStatus;
3727 if (fastTracks > 0) {
3728 mixerStatus = MIXER_TRACKS_READY;
3729 }
3730 return mixerStatus;
3731}
3732
3733// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07003734int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
3735 audio_format_t format, int sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08003736{
Andy Hunge8a1ced2014-05-09 15:02:21 -07003737 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08003738}
3739
3740// deleteTrackName_l() must be called with ThreadBase::mLock held
3741void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3742{
3743 ALOGV("remove track (%d) and delete from mixer", name);
3744 mAudioMixer->deleteTrackName(name);
3745}
3746
Eric Laurent10351942014-05-08 18:49:52 -07003747// checkForNewParameter_l() must be called with ThreadBase::mLock held
3748bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
3749 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08003750{
Eric Laurent81784c32012-11-19 14:55:58 -08003751 bool reconfig = false;
3752
Eric Laurent10351942014-05-08 18:49:52 -07003753 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08003754
Eric Laurent10351942014-05-08 18:49:52 -07003755 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3756 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003757 if (mFastMixer != 0) {
Eric Laurent10351942014-05-08 18:49:52 -07003758 FastMixerStateQueue *sq = mFastMixer->sq();
3759 FastMixerState *state = sq->begin();
3760 if (!(state->mCommand & FastMixerState::IDLE)) {
3761 previousCommand = state->mCommand;
3762 state->mCommand = FastMixerState::HOT_IDLE;
3763 sq->end();
3764 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3765 } else {
3766 sq->end(false /*didModify*/);
Eric Laurent81784c32012-11-19 14:55:58 -08003767 }
Eric Laurent10351942014-05-08 18:49:52 -07003768 }
Eric Laurent81784c32012-11-19 14:55:58 -08003769
Eric Laurent10351942014-05-08 18:49:52 -07003770 AudioParameter param = AudioParameter(keyValuePair);
3771 int value;
3772 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3773 reconfig = true;
3774 }
3775 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07003776 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07003777 status = BAD_VALUE;
3778 } else {
3779 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08003780 reconfig = true;
3781 }
Eric Laurent10351942014-05-08 18:49:52 -07003782 }
3783 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07003784 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07003785 status = BAD_VALUE;
3786 } else {
3787 // no need to save value, since it's constant
3788 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003789 }
Eric Laurent10351942014-05-08 18:49:52 -07003790 }
3791 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3792 // do not accept frame count changes if tracks are open as the track buffer
3793 // size depends on frame count and correct behavior would not be guaranteed
3794 // if frame count is changed after track creation
3795 if (!mTracks.isEmpty()) {
3796 status = INVALID_OPERATION;
3797 } else {
3798 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003799 }
Eric Laurent10351942014-05-08 18:49:52 -07003800 }
3801 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08003802#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07003803 // when changing the audio output device, call addBatteryData to notify
3804 // the change
3805 if (mOutDevice != value) {
3806 uint32_t params = 0;
3807 // check whether speaker is on
3808 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
3809 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08003810 }
Eric Laurent10351942014-05-08 18:49:52 -07003811
3812 audio_devices_t deviceWithoutSpeaker
3813 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3814 // check if any other device (except speaker) is on
3815 if (value & deviceWithoutSpeaker ) {
3816 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3817 }
3818
3819 if (params != 0) {
3820 addBatteryData(params);
3821 }
3822 }
Eric Laurent81784c32012-11-19 14:55:58 -08003823#endif
3824
Eric Laurent10351942014-05-08 18:49:52 -07003825 // forward device change to effects that have requested to be
3826 // aware of attached audio device.
3827 if (value != AUDIO_DEVICE_NONE) {
3828 mOutDevice = value;
3829 for (size_t i = 0; i < mEffectChains.size(); i++) {
3830 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08003831 }
3832 }
Eric Laurent10351942014-05-08 18:49:52 -07003833 }
Eric Laurent81784c32012-11-19 14:55:58 -08003834
Eric Laurent10351942014-05-08 18:49:52 -07003835 if (status == NO_ERROR) {
3836 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3837 keyValuePair.string());
3838 if (!mStandby && status == INVALID_OPERATION) {
3839 mOutput->stream->common.standby(&mOutput->stream->common);
3840 mStandby = true;
3841 mBytesWritten = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003842 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Eric Laurent10351942014-05-08 18:49:52 -07003843 keyValuePair.string());
Eric Laurent81784c32012-11-19 14:55:58 -08003844 }
Eric Laurent10351942014-05-08 18:49:52 -07003845 if (status == NO_ERROR && reconfig) {
3846 readOutputParameters_l();
3847 delete mAudioMixer;
3848 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3849 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07003850 int name = getTrackName_l(mTracks[i]->mChannelMask,
3851 mTracks[i]->mFormat, mTracks[i]->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07003852 if (name < 0) {
3853 break;
3854 }
3855 mTracks[i]->mName = name;
3856 }
3857 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3858 }
Eric Laurent81784c32012-11-19 14:55:58 -08003859 }
3860
3861 if (!(previousCommand & FastMixerState::IDLE)) {
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003862 ALOG_ASSERT(mFastMixer != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08003863 FastMixerStateQueue *sq = mFastMixer->sq();
3864 FastMixerState *state = sq->begin();
3865 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3866 state->mCommand = previousCommand;
3867 sq->end();
3868 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3869 }
3870
3871 return reconfig;
3872}
3873
3874
3875void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
3876{
3877 const size_t SIZE = 256;
3878 char buffer[SIZE];
3879 String8 result;
3880
3881 PlaybackThread::dumpInternals(fd, args);
3882
Elliott Hughes87cebad2014-05-22 10:14:43 -07003883 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Eric Laurent81784c32012-11-19 14:55:58 -08003884
3885 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003886 const FastMixerDumpState copy(mFastMixerDumpState);
Eric Laurent81784c32012-11-19 14:55:58 -08003887 copy.dump(fd);
3888
3889#ifdef STATE_QUEUE_DUMP
3890 // Similar for state queue
3891 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
3892 observerCopy.dump(fd);
3893 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
3894 mutatorCopy.dump(fd);
3895#endif
3896
Glenn Kasten46909e72013-02-26 09:20:22 -08003897#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003898 // Write the tee output to a .wav file
3899 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08003900#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003901
3902#ifdef AUDIO_WATCHDOG
3903 if (mAudioWatchdog != 0) {
3904 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
3905 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
3906 wdCopy.dump(fd);
3907 }
3908#endif
3909}
3910
3911uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
3912{
3913 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
3914}
3915
3916uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
3917{
3918 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3919}
3920
3921void AudioFlinger::MixerThread::cacheParameters_l()
3922{
3923 PlaybackThread::cacheParameters_l();
3924
3925 // FIXME: Relaxed timing because of a certain device that can't meet latency
3926 // Should be reduced to 2x after the vendor fixes the driver issue
3927 // increase threshold again due to low power audio mode. The way this warning
3928 // threshold is calculated and its usefulness should be reconsidered anyway.
3929 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
3930}
3931
3932// ----------------------------------------------------------------------------
3933
3934AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3935 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
3936 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
3937 // mLeftVolFloat, mRightVolFloat
3938{
3939}
3940
Eric Laurentbfb1b832013-01-07 09:53:42 -08003941AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3942 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
3943 ThreadBase::type_t type)
3944 : PlaybackThread(audioFlinger, output, id, device, type)
3945 // mLeftVolFloat, mRightVolFloat
3946{
3947}
3948
Eric Laurent81784c32012-11-19 14:55:58 -08003949AudioFlinger::DirectOutputThread::~DirectOutputThread()
3950{
3951}
3952
Eric Laurentbfb1b832013-01-07 09:53:42 -08003953void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
3954{
3955 audio_track_cblk_t* cblk = track->cblk();
3956 float left, right;
3957
3958 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
3959 left = right = 0;
3960 } else {
3961 float typeVolume = mStreamTypes[track->streamType()].volume;
3962 float v = mMasterVolume * typeVolume;
3963 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07003964 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
3965 left = float_from_gain(gain_minifloat_unpack_left(vlr));
3966 if (left > GAIN_FLOAT_UNITY) {
3967 left = GAIN_FLOAT_UNITY;
3968 }
3969 left *= v;
3970 right = float_from_gain(gain_minifloat_unpack_right(vlr));
3971 if (right > GAIN_FLOAT_UNITY) {
3972 right = GAIN_FLOAT_UNITY;
3973 }
3974 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003975 }
3976
3977 if (lastTrack) {
3978 if (left != mLeftVolFloat || right != mRightVolFloat) {
3979 mLeftVolFloat = left;
3980 mRightVolFloat = right;
3981
3982 // Convert volumes from float to 8.24
3983 uint32_t vl = (uint32_t)(left * (1 << 24));
3984 uint32_t vr = (uint32_t)(right * (1 << 24));
3985
3986 // Delegate volume control to effect in track effect chain if needed
3987 // only one effect chain can be present on DirectOutputThread, so if
3988 // there is one, the track is connected to it
3989 if (!mEffectChains.isEmpty()) {
3990 mEffectChains[0]->setVolume_l(&vl, &vr);
3991 left = (float)vl / (1 << 24);
3992 right = (float)vr / (1 << 24);
3993 }
3994 if (mOutput->stream->set_volume) {
3995 mOutput->stream->set_volume(mOutput->stream, left, right);
3996 }
3997 }
3998 }
3999}
4000
4001
Eric Laurent81784c32012-11-19 14:55:58 -08004002AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4003 Vector< sp<Track> > *tracksToRemove
4004)
4005{
Eric Laurentd595b7c2013-04-03 17:27:56 -07004006 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08004007 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004008 bool doHwPause = false;
4009 bool doHwResume = false;
4010 bool flushPending = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004011
4012 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07004013 for (size_t i = 0; i < count; i++) {
4014 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08004015 // The track died recently
4016 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004017 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08004018 }
4019
4020 Track* const track = t.get();
4021 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07004022 // Only consider last track started for volume and mixer state control.
4023 // In theory an older track could underrun and restart after the new one starts
4024 // but as we only care about the transition phase between two tracks on a
4025 // direct output, it is not a problem to ignore the underrun case.
4026 sp<Track> l = mLatestActiveTrack.promote();
4027 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08004028
Eric Laurentd1f69b02014-12-15 14:33:13 -08004029 if (mHwSupportsPause && track->isPausing()) {
4030 track->setPaused();
4031 if (last && !mHwPaused) {
4032 doHwPause = true;
4033 mHwPaused = true;
4034 }
4035 tracksToRemove->add(track);
4036 } else if (track->isFlushPending()) {
4037 track->flushAck();
4038 if (last) {
4039 flushPending = true;
4040 }
4041 } else if (mHwSupportsPause && track->isResumePending()){
4042 track->resumeAck();
4043 if (last) {
4044 if (mHwPaused) {
4045 doHwResume = true;
4046 mHwPaused = false;
4047 }
4048 }
4049 }
4050
Eric Laurent81784c32012-11-19 14:55:58 -08004051 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08004052 // for all its buffers to be filled before processing it.
4053 // Allow draining the buffer in case the client
4054 // app does not call stop() and relies on underrun to stop:
4055 // hence the test on (track->mRetryCount > 1).
4056 // If retryCount<=1 then track is about to underrun and be removed.
Eric Laurent81784c32012-11-19 14:55:58 -08004057 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08004058 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
4059 && (track->mRetryCount > 1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004060 minFrames = mNormalFrameCount;
4061 } else {
4062 minFrames = 1;
4063 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004064
Eric Laurentab5cdba2014-06-09 17:22:27 -07004065 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4066 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08004067 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004068 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08004069
4070 if (track->mFillingUpStatus == Track::FS_FILLED) {
4071 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004072 // make sure processVolume_l() will apply new volume even if 0
4073 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004074 if (!mHwSupportsPause) {
4075 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08004076 }
4077 }
4078
4079 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004080 processVolume_l(track, last);
4081 if (last) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004082 // reset retry count
4083 track->mRetryCount = kMaxTrackRetriesDirect;
4084 mActiveTrack = t;
4085 mixerStatus = MIXER_TRACKS_READY;
4086 }
Eric Laurent81784c32012-11-19 14:55:58 -08004087 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004088 // clear effect chain input buffer if the last active track started underruns
4089 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07004090 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004091 mEffectChains[0]->clearInputBuffer();
4092 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004093 if (track->isStopping_1()) {
4094 track->mState = TrackBase::STOPPING_2;
4095 }
4096 if ((track->sharedBuffer() != 0) || track->isStopped() ||
4097 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004098 // We have consumed all the buffers of this track.
4099 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07004100 size_t audioHALFrames;
4101 if (audio_is_linear_pcm(mFormat)) {
4102 audioHALFrames = (latency_l() * mSampleRate) / 1000;
4103 } else {
4104 audioHALFrames = 0;
4105 }
4106
Eric Laurent81784c32012-11-19 14:55:58 -08004107 size_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07004108 if (mStandby || !last ||
4109 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004110 if (track->isStopping_2()) {
4111 track->mState = TrackBase::STOPPED;
4112 }
Eric Laurent81784c32012-11-19 14:55:58 -08004113 if (track->isStopped()) {
Eric Laurente659ef42014-09-29 13:06:46 -07004114 if (track->mState == TrackBase::FLUSHED) {
4115 flushHw_l();
4116 }
Eric Laurent81784c32012-11-19 14:55:58 -08004117 track->reset();
4118 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004119 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08004120 }
4121 } else {
4122 // No buffers for this track. Give it a few chances to
4123 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07004124 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08004125 if (--(track->mRetryCount) <= 0) {
4126 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07004127 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004128 // indicate to client process that the track was disabled because of underrun;
4129 // it will then automatically call start() when data is available
4130 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004131 } else if (last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004132 mixerStatus = MIXER_TRACKS_ENABLED;
4133 }
4134 }
4135 }
4136 }
4137
Eric Laurentd1f69b02014-12-15 14:33:13 -08004138 // if an active track did not command a flush, check for pending flush on stopped tracks
4139 if (!flushPending) {
4140 for (size_t i = 0; i < mTracks.size(); i++) {
4141 if (mTracks[i]->isFlushPending()) {
4142 mTracks[i]->flushAck();
4143 flushPending = true;
4144 }
4145 }
4146 }
4147
4148 // make sure the pause/flush/resume sequence is executed in the right order.
4149 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4150 // before flush and then resume HW. This can happen in case of pause/flush/resume
4151 // if resume is received before pause is executed.
4152 if (mHwSupportsPause && !mStandby &&
4153 (doHwPause || (flushPending && !mHwPaused && (count != 0)))) {
4154 mOutput->stream->pause(mOutput->stream);
4155 }
4156 if (flushPending) {
4157 flushHw_l();
4158 }
4159 if (mHwSupportsPause && !mStandby && doHwResume) {
4160 mOutput->stream->resume(mOutput->stream);
4161 }
Eric Laurent81784c32012-11-19 14:55:58 -08004162 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004163 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004164
4165 return mixerStatus;
4166}
4167
4168void AudioFlinger::DirectOutputThread::threadLoop_mix()
4169{
Eric Laurent81784c32012-11-19 14:55:58 -08004170 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08004171 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004172 // output audio to hardware
4173 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07004174 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004175 buffer.frameCount = frameCount;
4176 mActiveTrack->getNextBuffer(&buffer);
Glenn Kastenfa319e62013-07-29 17:17:38 -07004177 if (buffer.raw == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08004178 memset(curBuf, 0, frameCount * mFrameSize);
4179 break;
4180 }
4181 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
4182 frameCount -= buffer.frameCount;
4183 curBuf += buffer.frameCount * mFrameSize;
4184 mActiveTrack->releaseBuffer(&buffer);
4185 }
Andy Hung2098f272014-02-27 14:00:06 -08004186 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004187 sleepTime = 0;
4188 standbyTime = systemTime() + standbyDelay;
4189 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004190}
4191
4192void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
4193{
Eric Laurentd1f69b02014-12-15 14:33:13 -08004194 // do not write to HAL when paused
4195 if (mHwPaused) {
4196 sleepTime = idleSleepTime;
4197 return;
4198 }
Eric Laurent81784c32012-11-19 14:55:58 -08004199 if (sleepTime == 0) {
4200 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4201 sleepTime = activeSleepTime;
4202 } else {
4203 sleepTime = idleSleepTime;
4204 }
4205 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08004206 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004207 sleepTime = 0;
4208 }
4209}
4210
Eric Laurentd1f69b02014-12-15 14:33:13 -08004211void AudioFlinger::DirectOutputThread::threadLoop_exit()
4212{
4213 {
4214 Mutex::Autolock _l(mLock);
4215 bool flushPending = false;
4216 for (size_t i = 0; i < mTracks.size(); i++) {
4217 if (mTracks[i]->isFlushPending()) {
4218 mTracks[i]->flushAck();
4219 flushPending = true;
4220 }
4221 }
4222 if (flushPending) {
4223 flushHw_l();
4224 }
4225 }
4226 PlaybackThread::threadLoop_exit();
4227}
4228
4229// must be called with thread mutex locked
4230bool AudioFlinger::DirectOutputThread::shouldStandby_l()
4231{
4232 bool trackPaused = false;
4233
4234 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4235 // after a timeout and we will enter standby then.
4236 if (mTracks.size() > 0) {
4237 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
4238 }
4239
4240 return !mStandby && !trackPaused;
4241}
4242
Eric Laurent81784c32012-11-19 14:55:58 -08004243// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004244int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Andy Hunge8a1ced2014-05-09 15:02:21 -07004245 audio_format_t format __unused, int sessionId __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004246{
4247 return 0;
4248}
4249
4250// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004251void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004252{
4253}
4254
Eric Laurent10351942014-05-08 18:49:52 -07004255// checkForNewParameter_l() must be called with ThreadBase::mLock held
4256bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
4257 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004258{
4259 bool reconfig = false;
4260
Eric Laurent10351942014-05-08 18:49:52 -07004261 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004262
Eric Laurent10351942014-05-08 18:49:52 -07004263 AudioParameter param = AudioParameter(keyValuePair);
4264 int value;
4265 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4266 // forward device change to effects that have requested to be
4267 // aware of attached audio device.
4268 if (value != AUDIO_DEVICE_NONE) {
4269 mOutDevice = value;
4270 for (size_t i = 0; i < mEffectChains.size(); i++) {
4271 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07004272 }
4273 }
Eric Laurent81784c32012-11-19 14:55:58 -08004274 }
Eric Laurent10351942014-05-08 18:49:52 -07004275 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4276 // do not accept frame count changes if tracks are open as the track buffer
4277 // size depends on frame count and correct behavior would not be garantied
4278 // if frame count is changed after track creation
4279 if (!mTracks.isEmpty()) {
4280 status = INVALID_OPERATION;
4281 } else {
4282 reconfig = true;
4283 }
4284 }
4285 if (status == NO_ERROR) {
4286 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4287 keyValuePair.string());
4288 if (!mStandby && status == INVALID_OPERATION) {
4289 mOutput->stream->common.standby(&mOutput->stream->common);
4290 mStandby = true;
4291 mBytesWritten = 0;
4292 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4293 keyValuePair.string());
4294 }
4295 if (status == NO_ERROR && reconfig) {
4296 readOutputParameters_l();
4297 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
4298 }
4299 }
4300
Eric Laurent81784c32012-11-19 14:55:58 -08004301 return reconfig;
4302}
4303
4304uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
4305{
4306 uint32_t time;
4307 if (audio_is_linear_pcm(mFormat)) {
4308 time = PlaybackThread::activeSleepTimeUs();
4309 } else {
4310 time = 10000;
4311 }
4312 return time;
4313}
4314
4315uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
4316{
4317 uint32_t time;
4318 if (audio_is_linear_pcm(mFormat)) {
4319 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
4320 } else {
4321 time = 10000;
4322 }
4323 return time;
4324}
4325
4326uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
4327{
4328 uint32_t time;
4329 if (audio_is_linear_pcm(mFormat)) {
4330 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
4331 } else {
4332 time = 10000;
4333 }
4334 return time;
4335}
4336
4337void AudioFlinger::DirectOutputThread::cacheParameters_l()
4338{
4339 PlaybackThread::cacheParameters_l();
4340
4341 // use shorter standby delay as on normal output to release
4342 // hardware resources as soon as possible
Eric Laurent972a1732013-09-04 09:42:59 -07004343 if (audio_is_linear_pcm(mFormat)) {
4344 standbyDelay = microseconds(activeSleepTime*2);
4345 } else {
4346 standbyDelay = kOffloadStandbyDelayNs;
4347 }
Eric Laurent81784c32012-11-19 14:55:58 -08004348}
4349
Eric Laurente659ef42014-09-29 13:06:46 -07004350void AudioFlinger::DirectOutputThread::flushHw_l()
4351{
Eric Laurentd1f69b02014-12-15 14:33:13 -08004352 if (mOutput->stream->flush != NULL) {
Eric Laurente659ef42014-09-29 13:06:46 -07004353 mOutput->stream->flush(mOutput->stream);
Eric Laurentd1f69b02014-12-15 14:33:13 -08004354 }
4355 mHwPaused = false;
Eric Laurente659ef42014-09-29 13:06:46 -07004356}
4357
Eric Laurent81784c32012-11-19 14:55:58 -08004358// ----------------------------------------------------------------------------
4359
Eric Laurentbfb1b832013-01-07 09:53:42 -08004360AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07004361 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004362 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07004363 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07004364 mWriteAckSequence(0),
4365 mDrainSequence(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004366{
4367}
4368
4369AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
4370{
4371}
4372
4373void AudioFlinger::AsyncCallbackThread::onFirstRef()
4374{
4375 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
4376}
4377
4378bool AudioFlinger::AsyncCallbackThread::threadLoop()
4379{
4380 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004381 uint32_t writeAckSequence;
4382 uint32_t drainSequence;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004383
4384 {
4385 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08004386 while (!((mWriteAckSequence & 1) ||
4387 (mDrainSequence & 1) ||
4388 exitPending())) {
4389 mWaitWorkCV.wait(mLock);
4390 }
4391
Eric Laurentbfb1b832013-01-07 09:53:42 -08004392 if (exitPending()) {
4393 break;
4394 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004395 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
4396 mWriteAckSequence, mDrainSequence);
4397 writeAckSequence = mWriteAckSequence;
4398 mWriteAckSequence &= ~1;
4399 drainSequence = mDrainSequence;
4400 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004401 }
4402 {
Eric Laurent4de95592013-09-26 15:28:21 -07004403 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
4404 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004405 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004406 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004407 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004408 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004409 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004410 }
4411 }
4412 }
4413 }
4414 return false;
4415}
4416
4417void AudioFlinger::AsyncCallbackThread::exit()
4418{
4419 ALOGV("AsyncCallbackThread::exit");
4420 Mutex::Autolock _l(mLock);
4421 requestExit();
4422 mWaitWorkCV.broadcast();
4423}
4424
Eric Laurent3b4529e2013-09-05 18:09:19 -07004425void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004426{
4427 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004428 // bit 0 is cleared
4429 mWriteAckSequence = sequence << 1;
4430}
4431
4432void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
4433{
4434 Mutex::Autolock _l(mLock);
4435 // ignore unexpected callbacks
4436 if (mWriteAckSequence & 2) {
4437 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004438 mWaitWorkCV.signal();
4439 }
4440}
4441
Eric Laurent3b4529e2013-09-05 18:09:19 -07004442void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004443{
4444 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004445 // bit 0 is cleared
4446 mDrainSequence = sequence << 1;
4447}
4448
4449void AudioFlinger::AsyncCallbackThread::resetDraining()
4450{
4451 Mutex::Autolock _l(mLock);
4452 // ignore unexpected callbacks
4453 if (mDrainSequence & 2) {
4454 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004455 mWaitWorkCV.signal();
4456 }
4457}
4458
4459
4460// ----------------------------------------------------------------------------
4461AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
4462 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
4463 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD),
Eric Laurentd7e59222013-11-15 12:02:28 -08004464 mPausedBytesRemaining(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004465{
Eric Laurentfd477972013-10-25 18:10:40 -07004466 //FIXME: mStandby should be set to true by ThreadBase constructor
4467 mStandby = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004468}
4469
Eric Laurentbfb1b832013-01-07 09:53:42 -08004470void AudioFlinger::OffloadThread::threadLoop_exit()
4471{
4472 if (mFlushPending || mHwPaused) {
4473 // If a flush is pending or track was paused, just discard buffered data
4474 flushHw_l();
4475 } else {
4476 mMixerStatus = MIXER_DRAIN_ALL;
4477 threadLoop_drain();
4478 }
Uday Gupta56604aa2014-05-13 11:19:17 -07004479 if (mUseAsyncWrite) {
4480 ALOG_ASSERT(mCallbackThread != 0);
4481 mCallbackThread->exit();
4482 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004483 PlaybackThread::threadLoop_exit();
4484}
4485
4486AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
4487 Vector< sp<Track> > *tracksToRemove
4488)
4489{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004490 size_t count = mActiveTracks.size();
4491
4492 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07004493 bool doHwPause = false;
4494 bool doHwResume = false;
4495
Eric Laurentede6c3b2013-09-19 14:37:46 -07004496 ALOGV("OffloadThread::prepareTracks_l active tracks %d", count);
4497
Eric Laurentbfb1b832013-01-07 09:53:42 -08004498 // find out which tracks need to be processed
4499 for (size_t i = 0; i < count; i++) {
4500 sp<Track> t = mActiveTracks[i].promote();
4501 // The track died recently
4502 if (t == 0) {
4503 continue;
4504 }
4505 Track* const track = t.get();
4506 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07004507 // Only consider last track started for volume and mixer state control.
4508 // In theory an older track could underrun and restart after the new one starts
4509 // but as we only care about the transition phase between two tracks on a
4510 // direct output, it is not a problem to ignore the underrun case.
4511 sp<Track> l = mLatestActiveTrack.promote();
4512 bool last = l.get() == track;
4513
Haynes Mathew George7844f672014-01-15 12:32:55 -08004514 if (track->isInvalid()) {
4515 ALOGW("An invalidated track shouldn't be in active list");
4516 tracksToRemove->add(track);
4517 continue;
4518 }
4519
4520 if (track->mState == TrackBase::IDLE) {
4521 ALOGW("An idle track shouldn't be in active list");
4522 continue;
4523 }
4524
Eric Laurentbfb1b832013-01-07 09:53:42 -08004525 if (track->isPausing()) {
4526 track->setPaused();
4527 if (last) {
4528 if (!mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07004529 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004530 mHwPaused = true;
4531 }
4532 // If we were part way through writing the mixbuffer to
4533 // the HAL we must save this until we resume
4534 // BUG - this will be wrong if a different track is made active,
4535 // in that case we want to discard the pending data in the
4536 // mixbuffer and tell the client to present it again when the
4537 // track is resumed
4538 mPausedWriteLength = mCurrentWriteLength;
4539 mPausedBytesRemaining = mBytesRemaining;
4540 mBytesRemaining = 0; // stop writing
4541 }
4542 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08004543 } else if (track->isFlushPending()) {
4544 track->flushAck();
4545 if (last) {
4546 mFlushPending = true;
4547 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08004548 } else if (track->isResumePending()){
4549 track->resumeAck();
4550 if (last) {
4551 if (mPausedBytesRemaining) {
4552 // Need to continue write that was interrupted
4553 mCurrentWriteLength = mPausedWriteLength;
4554 mBytesRemaining = mPausedBytesRemaining;
4555 mPausedBytesRemaining = 0;
4556 }
4557 if (mHwPaused) {
4558 doHwResume = true;
4559 mHwPaused = false;
4560 // threadLoop_mix() will handle the case that we need to
4561 // resume an interrupted write
4562 }
4563 // enable write to audio HAL
4564 sleepTime = 0;
4565
4566 // Do not handle new data in this iteration even if track->framesReady()
4567 mixerStatus = MIXER_TRACKS_ENABLED;
4568 }
4569 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07004570 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004571 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004572 if (track->mFillingUpStatus == Track::FS_FILLED) {
4573 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004574 // make sure processVolume_l() will apply new volume even if 0
4575 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004576 }
4577
4578 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08004579 sp<Track> previousTrack = mPreviousTrack.promote();
4580 if (previousTrack != 0) {
4581 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08004582 // Flush any data still being written from last track
4583 mBytesRemaining = 0;
4584 if (mPausedBytesRemaining) {
4585 // Last track was paused so we also need to flush saved
4586 // mixbuffer state and invalidate track so that it will
4587 // re-submit that unwritten data when it is next resumed
4588 mPausedBytesRemaining = 0;
4589 // Invalidate is a bit drastic - would be more efficient
4590 // to have a flag to tell client that some of the
4591 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08004592 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004593 }
4594 // flush data already sent to the DSP if changing audio session as audio
4595 // comes from a different source. Also invalidate previous track to force a
4596 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08004597 if (previousTrack->sessionId() != track->sessionId()) {
4598 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004599 }
4600 }
4601 }
4602 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004603 // reset retry count
4604 track->mRetryCount = kMaxTrackRetriesOffload;
4605 mActiveTrack = t;
4606 mixerStatus = MIXER_TRACKS_READY;
4607 }
4608 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004609 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004610 if (track->isStopping_1()) {
4611 // Hardware buffer can hold a large amount of audio so we must
4612 // wait for all current track's data to drain before we say
4613 // that the track is stopped.
4614 if (mBytesRemaining == 0) {
4615 // Only start draining when all data in mixbuffer
4616 // has been written
4617 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
4618 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004619 // do not drain if no data was ever sent to HAL (mStandby == true)
4620 if (last && !mStandby) {
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004621 // do not modify drain sequence if we are already draining. This happens
4622 // when resuming from pause after drain.
4623 if ((mDrainSequence & 1) == 0) {
4624 sleepTime = 0;
4625 standbyTime = systemTime() + standbyDelay;
4626 mixerStatus = MIXER_DRAIN_TRACK;
4627 mDrainSequence += 2;
4628 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004629 if (mHwPaused) {
4630 // It is possible to move from PAUSED to STOPPING_1 without
4631 // a resume so we must ensure hardware is running
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004632 doHwResume = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004633 mHwPaused = false;
4634 }
4635 }
4636 }
4637 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004638 // Drain has completed or we are in standby, signal presentation complete
4639 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004640 track->mState = TrackBase::STOPPED;
4641 size_t audioHALFrames =
4642 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
4643 size_t framesWritten =
Eric Laurent665470b2014-07-03 16:37:08 -07004644 mBytesWritten / audio_stream_out_frame_size(mOutput->stream);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004645 track->presentationComplete(framesWritten, audioHALFrames);
4646 track->reset();
4647 tracksToRemove->add(track);
4648 }
4649 } else {
4650 // No buffers for this track. Give it a few chances to
4651 // fill a buffer, then remove it from active list.
4652 if (--(track->mRetryCount) <= 0) {
4653 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
4654 track->name());
4655 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004656 // indicate to client process that the track was disabled because of underrun;
4657 // it will then automatically call start() when data is available
4658 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004659 } else if (last){
4660 mixerStatus = MIXER_TRACKS_ENABLED;
4661 }
4662 }
4663 }
4664 // compute volume for this track
4665 processVolume_l(track, last);
4666 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004667
Eric Laurentea0fade2013-10-04 16:23:48 -07004668 // make sure the pause/flush/resume sequence is executed in the right order.
4669 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4670 // before flush and then resume HW. This can happen in case of pause/flush/resume
4671 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07004672 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurent972a1732013-09-04 09:42:59 -07004673 mOutput->stream->pause(mOutput->stream);
4674 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004675 if (mFlushPending) {
4676 flushHw_l();
4677 mFlushPending = false;
4678 }
Eric Laurentfd477972013-10-25 18:10:40 -07004679 if (!mStandby && doHwResume) {
Eric Laurent972a1732013-09-04 09:42:59 -07004680 mOutput->stream->resume(mOutput->stream);
4681 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004682
Eric Laurentbfb1b832013-01-07 09:53:42 -08004683 // remove all the tracks that need to be...
4684 removeTracks_l(*tracksToRemove);
4685
4686 return mixerStatus;
4687}
4688
Eric Laurentbfb1b832013-01-07 09:53:42 -08004689// must be called with thread mutex locked
4690bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
4691{
Eric Laurent3b4529e2013-09-05 18:09:19 -07004692 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
4693 mWriteAckSequence, mDrainSequence);
4694 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004695 return true;
4696 }
4697 return false;
4698}
4699
Eric Laurentbfb1b832013-01-07 09:53:42 -08004700bool AudioFlinger::OffloadThread::waitingAsyncCallback()
4701{
4702 Mutex::Autolock _l(mLock);
4703 return waitingAsyncCallback_l();
4704}
4705
4706void AudioFlinger::OffloadThread::flushHw_l()
4707{
Eric Laurente659ef42014-09-29 13:06:46 -07004708 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004709 // Flush anything still waiting in the mixbuffer
4710 mCurrentWriteLength = 0;
4711 mBytesRemaining = 0;
4712 mPausedWriteLength = 0;
4713 mPausedBytesRemaining = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08004714
Eric Laurentbfb1b832013-01-07 09:53:42 -08004715 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004716 // discard any pending drain or write ack by incrementing sequence
4717 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4718 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004719 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004720 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4721 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004722 }
4723}
4724
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08004725void AudioFlinger::OffloadThread::onAddNewTrack_l()
4726{
4727 sp<Track> previousTrack = mPreviousTrack.promote();
4728 sp<Track> latestTrack = mLatestActiveTrack.promote();
4729
4730 if (previousTrack != 0 && latestTrack != 0 &&
4731 (previousTrack->sessionId() != latestTrack->sessionId())) {
4732 mFlushPending = true;
4733 }
4734 PlaybackThread::onAddNewTrack_l();
4735}
4736
Eric Laurentbfb1b832013-01-07 09:53:42 -08004737// ----------------------------------------------------------------------------
4738
Eric Laurent81784c32012-11-19 14:55:58 -08004739AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
4740 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
4741 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
4742 DUPLICATING),
4743 mWaitTimeMs(UINT_MAX)
4744{
4745 addOutputTrack(mainThread);
4746}
4747
4748AudioFlinger::DuplicatingThread::~DuplicatingThread()
4749{
4750 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4751 mOutputTracks[i]->destroy();
4752 }
4753}
4754
4755void AudioFlinger::DuplicatingThread::threadLoop_mix()
4756{
4757 // mix buffers...
4758 if (outputsReady(outputTracks)) {
4759 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
4760 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08004761 if (mMixerBufferValid) {
4762 memset(mMixerBuffer, 0, mMixerBufferSize);
4763 } else {
4764 memset(mSinkBuffer, 0, mSinkBufferSize);
4765 }
Eric Laurent81784c32012-11-19 14:55:58 -08004766 }
4767 sleepTime = 0;
4768 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08004769 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004770 standbyTime = systemTime() + standbyDelay;
4771}
4772
4773void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
4774{
4775 if (sleepTime == 0) {
4776 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4777 sleepTime = activeSleepTime;
4778 } else {
4779 sleepTime = idleSleepTime;
4780 }
4781 } else if (mBytesWritten != 0) {
4782 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4783 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08004784 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004785 } else {
4786 // flush remaining overflow buffers in output tracks
4787 writeFrames = 0;
4788 }
4789 sleepTime = 0;
4790 }
4791}
4792
Eric Laurentbfb1b832013-01-07 09:53:42 -08004793ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004794{
Haynes Mathew Georgeec0eeaf2014-11-20 11:32:27 -08004795 // We convert the duplicating thread format to AUDIO_FORMAT_PCM_16_BIT
4796 // for delivery downstream as needed. This in-place conversion is safe as
4797 // AUDIO_FORMAT_PCM_16_BIT is smaller than any other supported format
4798 // (AUDIO_FORMAT_PCM_8_BIT is not allowed here).
4799 if (mFormat != AUDIO_FORMAT_PCM_16_BIT) {
4800 memcpy_by_audio_format(mSinkBuffer, AUDIO_FORMAT_PCM_16_BIT,
4801 mSinkBuffer, mFormat, writeFrames * mChannelCount);
4802 }
Eric Laurent81784c32012-11-19 14:55:58 -08004803 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung010a1a12014-03-13 13:57:33 -07004804 outputTracks[i]->write(reinterpret_cast<int16_t*>(mSinkBuffer), writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08004805 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07004806 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08004807 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004808}
4809
4810void AudioFlinger::DuplicatingThread::threadLoop_standby()
4811{
4812 // DuplicatingThread implements standby by stopping all tracks
4813 for (size_t i = 0; i < outputTracks.size(); i++) {
4814 outputTracks[i]->stop();
4815 }
4816}
4817
4818void AudioFlinger::DuplicatingThread::saveOutputTracks()
4819{
4820 outputTracks = mOutputTracks;
4821}
4822
4823void AudioFlinger::DuplicatingThread::clearOutputTracks()
4824{
4825 outputTracks.clear();
4826}
4827
4828void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
4829{
4830 Mutex::Autolock _l(mLock);
4831 // FIXME explain this formula
4832 size_t frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
Andy Hung010a1a12014-03-13 13:57:33 -07004833 // OutputTrack is forced to AUDIO_FORMAT_PCM_16_BIT regardless of mFormat
4834 // due to current usage case and restrictions on the AudioBufferProvider.
4835 // Actual buffer conversion is done in threadLoop_write().
4836 //
4837 // TODO: This may change in the future, depending on multichannel
4838 // (and non int16_t*) support on AF::PlaybackThread::OutputTrack
Eric Laurent81784c32012-11-19 14:55:58 -08004839 OutputTrack *outputTrack = new OutputTrack(thread,
4840 this,
4841 mSampleRate,
Andy Hung010a1a12014-03-13 13:57:33 -07004842 AUDIO_FORMAT_PCM_16_BIT,
Eric Laurent81784c32012-11-19 14:55:58 -08004843 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004844 frameCount,
4845 IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08004846 if (outputTrack->cblk() != NULL) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004847 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
Eric Laurent81784c32012-11-19 14:55:58 -08004848 mOutputTracks.add(outputTrack);
4849 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
4850 updateWaitTime_l();
4851 }
4852}
4853
4854void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
4855{
4856 Mutex::Autolock _l(mLock);
4857 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4858 if (mOutputTracks[i]->thread() == thread) {
4859 mOutputTracks[i]->destroy();
4860 mOutputTracks.removeAt(i);
4861 updateWaitTime_l();
4862 return;
4863 }
4864 }
4865 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
4866}
4867
4868// caller must hold mLock
4869void AudioFlinger::DuplicatingThread::updateWaitTime_l()
4870{
4871 mWaitTimeMs = UINT_MAX;
4872 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4873 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
4874 if (strong != 0) {
4875 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4876 if (waitTimeMs < mWaitTimeMs) {
4877 mWaitTimeMs = waitTimeMs;
4878 }
4879 }
4880 }
4881}
4882
4883
4884bool AudioFlinger::DuplicatingThread::outputsReady(
4885 const SortedVector< sp<OutputTrack> > &outputTracks)
4886{
4887 for (size_t i = 0; i < outputTracks.size(); i++) {
4888 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
4889 if (thread == 0) {
4890 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
4891 outputTracks[i].get());
4892 return false;
4893 }
4894 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4895 // see note at standby() declaration
4896 if (playbackThread->standby() && !playbackThread->isSuspended()) {
4897 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
4898 thread.get());
4899 return false;
4900 }
4901 }
4902 return true;
4903}
4904
4905uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
4906{
4907 return (mWaitTimeMs * 1000) / 2;
4908}
4909
4910void AudioFlinger::DuplicatingThread::cacheParameters_l()
4911{
4912 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
4913 updateWaitTime_l();
4914
4915 MixerThread::cacheParameters_l();
4916}
4917
4918// ----------------------------------------------------------------------------
4919// Record
4920// ----------------------------------------------------------------------------
4921
4922AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4923 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08004924 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08004925 audio_devices_t outDevice,
Glenn Kasten46909e72013-02-26 09:20:22 -08004926 audio_devices_t inDevice
4927#ifdef TEE_SINK
4928 , const sp<NBAIO_Sink>& teeSink
4929#endif
4930 ) :
Eric Laurentd3922f72013-02-01 17:57:04 -08004931 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD),
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004932 mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
Glenn Kastendeca2ae2014-02-07 10:25:56 -08004933 // mRsmpInFrames and mRsmpInFramesP2 are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08004934 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08004935#ifdef TEE_SINK
4936 , mTeeSink(teeSink)
4937#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07004938 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
4939 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07004940 // mFastCapture below
4941 , mFastCaptureFutex(0)
4942 // mInputSource
4943 // mPipeSink
4944 // mPipeSource
4945 , mPipeFramesP2(0)
4946 // mPipeMemory
4947 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07004948 , mFastTrackAvail(false)
Eric Laurent81784c32012-11-19 14:55:58 -08004949{
4950 snprintf(mName, kNameLength, "AudioIn_%X", id);
Glenn Kasten481fb672013-09-30 14:39:28 -07004951 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mName);
Eric Laurent81784c32012-11-19 14:55:58 -08004952
Glenn Kastendeca2ae2014-02-07 10:25:56 -08004953 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07004954
4955 // create an NBAIO source for the HAL input stream, and negotiate
4956 mInputSource = new AudioStreamInSource(input->stream);
4957 size_t numCounterOffers = 0;
4958 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
4959 ssize_t index = mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
4960 ALOG_ASSERT(index == 0);
4961
4962 // initialize fast capture depending on configuration
4963 bool initFastCapture;
4964 switch (kUseFastCapture) {
4965 case FastCapture_Never:
4966 initFastCapture = false;
4967 break;
4968 case FastCapture_Always:
4969 initFastCapture = true;
4970 break;
4971 case FastCapture_Static:
4972 uint32_t primaryOutputSampleRate;
4973 {
4974 AutoMutex _l(audioFlinger->mHardwareLock);
4975 primaryOutputSampleRate = audioFlinger->mPrimaryOutputSampleRate;
4976 }
4977 initFastCapture =
4978 // either capture sample rate is same as (a reasonable) primary output sample rate
4979 (((primaryOutputSampleRate == 44100 || primaryOutputSampleRate == 48000) &&
4980 (mSampleRate == primaryOutputSampleRate)) ||
4981 // or primary output sample rate is unknown, and capture sample rate is reasonable
4982 ((primaryOutputSampleRate == 0) &&
4983 ((mSampleRate == 44100 || mSampleRate == 48000)))) &&
Glenn Kasten9f81de32014-07-27 15:02:23 -07004984 // and the buffer size is < 12 ms
4985 (mFrameCount * 1000) / mSampleRate < 12;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07004986 break;
4987 // case FastCapture_Dynamic:
4988 }
4989
4990 if (initFastCapture) {
4991 // create a Pipe for FastMixer to write to, and for us and fast tracks to read from
4992 NBAIO_Format format = mInputSource->format();
Glenn Kasten49d00ad2014-07-21 11:22:03 -07004993 size_t pipeFramesP2 = roundup(mSampleRate / 25); // double-buffering of 20 ms each
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07004994 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
4995 void *pipeBuffer;
4996 const sp<MemoryDealer> roHeap(readOnlyHeap());
4997 sp<IMemory> pipeMemory;
4998 if ((roHeap == 0) ||
4999 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
5000 (pipeBuffer = pipeMemory->pointer()) == NULL) {
5001 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
5002 goto failed;
5003 }
5004 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
5005 memset(pipeBuffer, 0, pipeSize);
5006 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
5007 const NBAIO_Format offers[1] = {format};
5008 size_t numCounterOffers = 0;
5009 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
5010 ALOG_ASSERT(index == 0);
5011 mPipeSink = pipe;
5012 PipeReader *pipeReader = new PipeReader(*pipe);
5013 numCounterOffers = 0;
5014 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
5015 ALOG_ASSERT(index == 0);
5016 mPipeSource = pipeReader;
5017 mPipeFramesP2 = pipeFramesP2;
5018 mPipeMemory = pipeMemory;
5019
5020 // create fast capture
5021 mFastCapture = new FastCapture();
5022 FastCaptureStateQueue *sq = mFastCapture->sq();
5023#ifdef STATE_QUEUE_DUMP
5024 // FIXME
5025#endif
5026 FastCaptureState *state = sq->begin();
5027 state->mCblk = NULL;
5028 state->mInputSource = mInputSource.get();
5029 state->mInputSourceGen++;
5030 state->mPipeSink = pipe;
5031 state->mPipeSinkGen++;
5032 state->mFrameCount = mFrameCount;
5033 state->mCommand = FastCaptureState::COLD_IDLE;
5034 // already done in constructor initialization list
5035 //mFastCaptureFutex = 0;
5036 state->mColdFutexAddr = &mFastCaptureFutex;
5037 state->mColdGen++;
5038 state->mDumpState = &mFastCaptureDumpState;
5039#ifdef TEE_SINK
5040 // FIXME
5041#endif
5042 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
5043 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
5044 sq->end();
5045 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5046
5047 // start the fast capture
5048 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
5049 pid_t tid = mFastCapture->getTid();
5050 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
5051 if (err != 0) {
5052 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
5053 kPriorityFastCapture, getpid_cached, tid, err);
5054 }
5055
5056#ifdef AUDIO_WATCHDOG
5057 // FIXME
5058#endif
5059
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005060 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005061 }
5062failed: ;
5063
5064 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08005065}
5066
5067
5068AudioFlinger::RecordThread::~RecordThread()
5069{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005070 if (mFastCapture != 0) {
5071 FastCaptureStateQueue *sq = mFastCapture->sq();
5072 FastCaptureState *state = sq->begin();
5073 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5074 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5075 if (old == -1) {
5076 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5077 }
5078 }
5079 state->mCommand = FastCaptureState::EXIT;
5080 sq->end();
5081 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5082 mFastCapture->join();
5083 mFastCapture.clear();
5084 }
5085 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07005086 mAudioFlinger->unregisterWriter(mNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08005087 delete[] mRsmpInBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005088}
5089
5090void AudioFlinger::RecordThread::onFirstRef()
5091{
5092 run(mName, PRIORITY_URGENT_AUDIO);
5093}
5094
Eric Laurent81784c32012-11-19 14:55:58 -08005095bool AudioFlinger::RecordThread::threadLoop()
5096{
Eric Laurent81784c32012-11-19 14:55:58 -08005097 nsecs_t lastWarning = 0;
5098
5099 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08005100
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005101reacquire_wakelock:
5102 sp<RecordTrack> activeTrack;
Glenn Kasten2b806402013-11-20 16:37:38 -08005103 int activeTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005104 {
5105 Mutex::Autolock _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005106 size_t size = mActiveTracks.size();
5107 activeTracksGen = mActiveTracksGen;
5108 if (size > 0) {
5109 // FIXME an arbitrary choice
5110 activeTrack = mActiveTracks[0];
5111 acquireWakeLock_l(activeTrack->uid());
5112 if (size > 1) {
5113 SortedVector<int> tmp;
5114 for (size_t i = 0; i < size; i++) {
5115 tmp.add(mActiveTracks[i]->uid());
5116 }
5117 updateWakeLockUids_l(tmp);
5118 }
5119 } else {
5120 acquireWakeLock_l(-1);
5121 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005122 }
5123
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005124 // used to request a deferred sleep, to be executed later while mutex is unlocked
5125 uint32_t sleepUs = 0;
5126
5127 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005128 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005129 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07005130
Glenn Kasten5edadd42013-08-14 16:30:49 -07005131 // sleep with mutex unlocked
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005132 if (sleepUs > 0) {
5133 usleep(sleepUs);
5134 sleepUs = 0;
Glenn Kasten5edadd42013-08-14 16:30:49 -07005135 }
5136
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005137 // activeTracks accumulates a copy of a subset of mActiveTracks
5138 Vector< sp<RecordTrack> > activeTracks;
5139
Glenn Kasten735f45f2014-08-18 15:51:59 -07005140 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005141 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07005142
Glenn Kasten735f45f2014-08-18 15:51:59 -07005143 // reference to a fast track which is about to be removed
5144 sp<RecordTrack> fastTrackToRemove;
5145
Eric Laurent81784c32012-11-19 14:55:58 -08005146 { // scope for mLock
5147 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08005148
Eric Laurent021cf962014-05-13 10:18:14 -07005149 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005150
Eric Laurent000a4192014-01-29 15:17:32 -08005151 // check exitPending here because checkForNewParameters_l() and
5152 // checkForNewParameters_l() can temporarily release mLock
5153 if (exitPending()) {
5154 break;
5155 }
5156
Glenn Kasten2b806402013-11-20 16:37:38 -08005157 // if no active track(s), then standby and release wakelock
5158 size_t size = mActiveTracks.size();
5159 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07005160 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005161 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08005162 releaseWakeLock_l();
5163 ALOGV("RecordThread: loop stopping");
5164 // go to sleep
5165 mWaitWorkCV.wait(mLock);
5166 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005167 goto reacquire_wakelock;
5168 }
5169
Glenn Kasten2b806402013-11-20 16:37:38 -08005170 if (mActiveTracksGen != activeTracksGen) {
5171 activeTracksGen = mActiveTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005172 SortedVector<int> tmp;
Glenn Kasten2b806402013-11-20 16:37:38 -08005173 for (size_t i = 0; i < size; i++) {
5174 tmp.add(mActiveTracks[i]->uid());
5175 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005176 updateWakeLockUids_l(tmp);
Eric Laurent81784c32012-11-19 14:55:58 -08005177 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005178
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005179 bool doBroadcast = false;
5180 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07005181
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005182 activeTrack = mActiveTracks[i];
5183 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07005184 if (activeTrack->isFastTrack()) {
5185 ALOG_ASSERT(fastTrackToRemove == 0);
5186 fastTrackToRemove = activeTrack;
5187 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005188 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08005189 mActiveTracks.remove(activeTrack);
5190 mActiveTracksGen++;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005191 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07005192 continue;
5193 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005194
5195 TrackBase::track_state activeTrackState = activeTrack->mState;
5196 switch (activeTrackState) {
5197
5198 case TrackBase::PAUSING:
5199 mActiveTracks.remove(activeTrack);
5200 mActiveTracksGen++;
5201 doBroadcast = true;
5202 size--;
5203 continue;
5204
5205 case TrackBase::STARTING_1:
5206 sleepUs = 10000;
5207 i++;
5208 continue;
5209
5210 case TrackBase::STARTING_2:
5211 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005212 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07005213 activeTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005214 break;
5215
5216 case TrackBase::ACTIVE:
5217 break;
5218
5219 case TrackBase::IDLE:
5220 i++;
5221 continue;
5222
5223 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08005224 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07005225 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005226
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005227 activeTracks.add(activeTrack);
5228 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07005229
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005230 if (activeTrack->isFastTrack()) {
5231 ALOG_ASSERT(!mFastTrackAvail);
5232 ALOG_ASSERT(fastTrack == 0);
5233 fastTrack = activeTrack;
5234 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005235 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005236 if (doBroadcast) {
5237 mStartStopCond.broadcast();
5238 }
5239
5240 // sleep if there are no active tracks to process
5241 if (activeTracks.size() == 0) {
5242 if (sleepUs == 0) {
5243 sleepUs = kRecordThreadSleepUs;
5244 }
5245 continue;
5246 }
5247 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07005248
Eric Laurent81784c32012-11-19 14:55:58 -08005249 lockEffectChains_l(effectChains);
5250 }
5251
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005252 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07005253
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005254 size_t size = effectChains.size();
5255 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005256 // thread mutex is not locked, but effect chain is locked
5257 effectChains[i]->process_l();
5258 }
5259
Glenn Kasten735f45f2014-08-18 15:51:59 -07005260 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005261 if (mFastCapture != 0) {
5262 FastCaptureStateQueue *sq = mFastCapture->sq();
5263 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07005264 bool didModify = false;
5265 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005266 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
5267 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
5268 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5269 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5270 if (old == -1) {
5271 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5272 }
5273 }
5274 state->mCommand = FastCaptureState::READ_WRITE;
5275#if 0 // FIXME
5276 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
5277 FastCaptureDumpState::kSamplingNforLowRamDevice : FastMixerDumpState::kSamplingN);
5278#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07005279 didModify = true;
5280 }
5281 audio_track_cblk_t *cblkOld = state->mCblk;
5282 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
5283 if (cblkNew != cblkOld) {
5284 state->mCblk = cblkNew;
5285 // block until acked if removing a fast track
5286 if (cblkOld != NULL) {
5287 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
5288 }
5289 didModify = true;
5290 }
5291 sq->end(didModify);
5292 if (didModify) {
5293 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005294#if 0
5295 if (kUseFastCapture == FastCapture_Dynamic) {
5296 mNormalSource = mPipeSource;
5297 }
5298#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005299 }
5300 }
5301
Glenn Kasten735f45f2014-08-18 15:51:59 -07005302 // now run the fast track destructor with thread mutex unlocked
5303 fastTrackToRemove.clear();
5304
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005305 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
5306 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
5307 // slow, then this RecordThread will overrun by not calling HAL read often enough.
5308 // If destination is non-contiguous, first read past the nominal end of buffer, then
5309 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005310
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005311 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005312 ssize_t framesRead;
5313
5314 // If an NBAIO source is present, use it to read the normal capture's data
5315 if (mPipeSource != 0) {
5316 size_t framesToRead = mBufferSize / mFrameSize;
5317 framesRead = mPipeSource->read(&mRsmpInBuffer[rear * mChannelCount],
5318 framesToRead, AudioBufferProvider::kInvalidPTS);
5319 if (framesRead == 0) {
5320 // since pipe is non-blocking, simulate blocking input
5321 sleepUs = (framesToRead * 1000000LL) / mSampleRate;
5322 }
5323 // otherwise use the HAL / AudioStreamIn directly
5324 } else {
5325 ssize_t bytesRead = mInput->stream->read(mInput->stream,
5326 &mRsmpInBuffer[rear * mChannelCount], mBufferSize);
5327 if (bytesRead < 0) {
5328 framesRead = bytesRead;
5329 } else {
5330 framesRead = bytesRead / mFrameSize;
5331 }
5332 }
5333
5334 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
5335 ALOGE("read failed: framesRead=%d", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005336 // Force input into standby so that it tries to recover at next read attempt
5337 inputStandBy();
5338 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005339 }
5340 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005341 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005342 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005343 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005344
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005345 if (mTeeSink != 0) {
5346 (void) mTeeSink->write(&mRsmpInBuffer[rear * mChannelCount], framesRead);
5347 }
5348 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005349 {
5350 size_t part1 = mRsmpInFramesP2 - rear;
5351 if ((size_t) framesRead > part1) {
5352 memcpy(mRsmpInBuffer, &mRsmpInBuffer[mRsmpInFramesP2 * mChannelCount],
5353 (framesRead - part1) * mFrameSize);
5354 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005355 }
5356 rear = mRsmpInRear += framesRead;
5357
5358 size = activeTracks.size();
5359 // loop over each active track
5360 for (size_t i = 0; i < size; i++) {
5361 activeTrack = activeTracks[i];
5362
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005363 // skip fast tracks, as those are handled directly by FastCapture
5364 if (activeTrack->isFastTrack()) {
5365 continue;
5366 }
5367
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005368 enum {
5369 OVERRUN_UNKNOWN,
5370 OVERRUN_TRUE,
5371 OVERRUN_FALSE
5372 } overrun = OVERRUN_UNKNOWN;
5373
5374 // loop over getNextBuffer to handle circular sink
5375 for (;;) {
5376
5377 activeTrack->mSink.frameCount = ~0;
5378 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
5379 size_t framesOut = activeTrack->mSink.frameCount;
5380 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
5381
5382 int32_t front = activeTrack->mRsmpInFront;
5383 ssize_t filled = rear - front;
5384 size_t framesIn;
5385
5386 if (filled < 0) {
5387 // should not happen, but treat like a massive overrun and re-sync
5388 framesIn = 0;
5389 activeTrack->mRsmpInFront = rear;
5390 overrun = OVERRUN_TRUE;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005391 } else if ((size_t) filled <= mRsmpInFrames) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005392 framesIn = (size_t) filled;
5393 } else {
5394 // client is not keeping up with server, but give it latest data
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005395 framesIn = mRsmpInFrames;
5396 activeTrack->mRsmpInFront = front = rear - framesIn;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005397 overrun = OVERRUN_TRUE;
5398 }
5399
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005400 if (framesOut == 0 || framesIn == 0) {
5401 break;
5402 }
5403
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005404 if (activeTrack->mResampler == NULL) {
5405 // no resampling
5406 if (framesIn > framesOut) {
5407 framesIn = framesOut;
5408 } else {
5409 framesOut = framesIn;
5410 }
5411 int8_t *dst = activeTrack->mSink.i8;
5412 while (framesIn > 0) {
5413 front &= mRsmpInFramesP2 - 1;
5414 size_t part1 = mRsmpInFramesP2 - front;
5415 if (part1 > framesIn) {
5416 part1 = framesIn;
5417 }
5418 int8_t *src = (int8_t *)mRsmpInBuffer + (front * mFrameSize);
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005419 if (mChannelCount == activeTrack->mChannelCount) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005420 memcpy(dst, src, part1 * mFrameSize);
5421 } else if (mChannelCount == 1) {
Glenn Kastencd704212014-07-14 17:26:36 -07005422 upmix_to_stereo_i16_from_mono_i16((int16_t *)dst, (const int16_t *)src,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005423 part1);
5424 } else {
Glenn Kastencd704212014-07-14 17:26:36 -07005425 downmix_to_mono_i16_from_stereo_i16((int16_t *)dst, (const int16_t *)src,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005426 part1);
5427 }
5428 dst += part1 * activeTrack->mFrameSize;
5429 front += part1;
5430 framesIn -= part1;
5431 }
5432 activeTrack->mRsmpInFront += framesOut;
5433
5434 } else {
5435 // resampling
5436 // FIXME framesInNeeded should really be part of resampler API, and should
5437 // depend on the SRC ratio
5438 // to keep mRsmpInBuffer full so resampler always has sufficient input
5439 size_t framesInNeeded;
5440 // FIXME only re-calculate when it changes, and optimize for common ratios
Andy Hung8661aaf2014-07-28 14:38:41 -07005441 // Do not precompute in/out because floating point is not associative
5442 // e.g. a*b/c != a*(b/c).
5443 const double in(mSampleRate);
5444 const double out(activeTrack->mSampleRate);
5445 framesInNeeded = ceil(framesOut * in / out) + 1;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005446 ALOGV("need %u frames in to produce %u out given in/out ratio of %.4g",
Andy Hung8661aaf2014-07-28 14:38:41 -07005447 framesInNeeded, framesOut, in / out);
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005448 // Although we theoretically have framesIn in circular buffer, some of those are
5449 // unreleased frames, and thus must be discounted for purpose of budgeting.
5450 size_t unreleased = activeTrack->mRsmpInUnrel;
5451 framesIn = framesIn > unreleased ? framesIn - unreleased : 0;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005452 if (framesIn < framesInNeeded) {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005453 ALOGV("not enough to resample: have %u frames in but need %u in to "
5454 "produce %u out given in/out ratio of %.4g",
Andy Hung8661aaf2014-07-28 14:38:41 -07005455 framesIn, framesInNeeded, framesOut, in / out);
5456 size_t newFramesOut = framesIn > 0 ? floor((framesIn - 1) * out / in) : 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005457 LOG_ALWAYS_FATAL_IF(newFramesOut >= framesOut);
5458 if (newFramesOut == 0) {
5459 break;
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005460 }
Andy Hung8661aaf2014-07-28 14:38:41 -07005461 framesInNeeded = ceil(newFramesOut * in / out) + 1;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005462 ALOGV("now need %u frames in to produce %u out given out/in ratio of %.4g",
Andy Hung8661aaf2014-07-28 14:38:41 -07005463 framesInNeeded, newFramesOut, out / in);
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005464 LOG_ALWAYS_FATAL_IF(framesIn < framesInNeeded);
5465 ALOGV("success 2: have %u frames in and need %u in to produce %u out "
5466 "given in/out ratio of %.4g",
Andy Hung8661aaf2014-07-28 14:38:41 -07005467 framesIn, framesInNeeded, newFramesOut, in / out);
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005468 framesOut = newFramesOut;
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005469 } else {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005470 ALOGV("success 1: have %u in and need %u in to produce %u out "
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005471 "given in/out ratio of %.4g",
Andy Hung8661aaf2014-07-28 14:38:41 -07005472 framesIn, framesInNeeded, framesOut, in / out);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005473 }
5474
5475 // reallocate mRsmpOutBuffer as needed; we will grow but never shrink
5476 if (activeTrack->mRsmpOutFrameCount < framesOut) {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005477 // FIXME why does each track need it's own mRsmpOutBuffer? can't they share?
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005478 delete[] activeTrack->mRsmpOutBuffer;
5479 // resampler always outputs stereo
5480 activeTrack->mRsmpOutBuffer = new int32_t[framesOut * FCC_2];
5481 activeTrack->mRsmpOutFrameCount = framesOut;
5482 }
5483
5484 // resampler accumulates, but we only have one source track
5485 memset(activeTrack->mRsmpOutBuffer, 0, framesOut * FCC_2 * sizeof(int32_t));
5486 activeTrack->mResampler->resample(activeTrack->mRsmpOutBuffer, framesOut,
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005487 // FIXME how about having activeTrack implement this interface itself?
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005488 activeTrack->mResamplerBufferProvider
5489 /*this*/ /* AudioBufferProvider* */);
5490 // ditherAndClamp() works as long as all buffers returned by
5491 // activeTrack->getNextBuffer() are 32 bit aligned which should be always true.
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005492 if (activeTrack->mChannelCount == 1) {
Andy Hung84a0c6e2014-04-02 11:24:53 -07005493 // temporarily type pun mRsmpOutBuffer from Q4.27 to int16_t
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005494 ditherAndClamp(activeTrack->mRsmpOutBuffer, activeTrack->mRsmpOutBuffer,
5495 framesOut);
5496 // the resampler always outputs stereo samples:
5497 // do post stereo to mono conversion
5498 downmix_to_mono_i16_from_stereo_i16(activeTrack->mSink.i16,
Glenn Kastencd704212014-07-14 17:26:36 -07005499 (const int16_t *)activeTrack->mRsmpOutBuffer, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005500 } else {
5501 ditherAndClamp((int32_t *)activeTrack->mSink.raw,
5502 activeTrack->mRsmpOutBuffer, framesOut);
5503 }
5504 // now done with mRsmpOutBuffer
5505
5506 }
5507
5508 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
5509 overrun = OVERRUN_FALSE;
5510 }
5511
5512 if (activeTrack->mFramesToDrop == 0) {
5513 if (framesOut > 0) {
5514 activeTrack->mSink.frameCount = framesOut;
5515 activeTrack->releaseBuffer(&activeTrack->mSink);
5516 }
5517 } else {
5518 // FIXME could do a partial drop of framesOut
5519 if (activeTrack->mFramesToDrop > 0) {
5520 activeTrack->mFramesToDrop -= framesOut;
5521 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005522 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005523 }
5524 } else {
5525 activeTrack->mFramesToDrop += framesOut;
5526 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
5527 activeTrack->mSyncStartEvent->isCancelled()) {
5528 ALOGW("Synced record %s, session %d, trigger session %d",
5529 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
5530 activeTrack->sessionId(),
5531 (activeTrack->mSyncStartEvent != 0) ?
5532 activeTrack->mSyncStartEvent->triggerSession() : 0);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005533 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005534 }
5535 }
5536 }
5537
5538 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005539 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005540 }
5541 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005542
5543 switch (overrun) {
5544 case OVERRUN_TRUE:
5545 // client isn't retrieving buffers fast enough
5546 if (!activeTrack->setOverflow()) {
5547 nsecs_t now = systemTime();
5548 // FIXME should lastWarning per track?
5549 if ((now - lastWarning) > kWarningThrottleNs) {
5550 ALOGW("RecordThread: buffer overflow");
5551 lastWarning = now;
5552 }
5553 }
5554 break;
5555 case OVERRUN_FALSE:
5556 activeTrack->clearOverflow();
5557 break;
5558 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005559 break;
5560 }
5561
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005562 }
5563
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005564unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08005565 // enable changes in effect chain
5566 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005567 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08005568 }
5569
Glenn Kasten93e471f2013-08-19 08:40:07 -07005570 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08005571
5572 {
5573 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07005574 for (size_t i = 0; i < mTracks.size(); i++) {
5575 sp<RecordTrack> track = mTracks[i];
5576 track->invalidate();
5577 }
Glenn Kasten2b806402013-11-20 16:37:38 -08005578 mActiveTracks.clear();
5579 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08005580 mStartStopCond.broadcast();
5581 }
5582
5583 releaseWakeLock();
5584
5585 ALOGV("RecordThread %p exiting", this);
5586 return false;
5587}
5588
Glenn Kasten93e471f2013-08-19 08:40:07 -07005589void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08005590{
5591 if (!mStandby) {
5592 inputStandBy();
5593 mStandby = true;
5594 }
5595}
5596
5597void AudioFlinger::RecordThread::inputStandBy()
5598{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005599 // Idle the fast capture if it's currently running
5600 if (mFastCapture != 0) {
5601 FastCaptureStateQueue *sq = mFastCapture->sq();
5602 FastCaptureState *state = sq->begin();
5603 if (!(state->mCommand & FastCaptureState::IDLE)) {
5604 state->mCommand = FastCaptureState::COLD_IDLE;
5605 state->mColdFutexAddr = &mFastCaptureFutex;
5606 state->mColdGen++;
5607 mFastCaptureFutex = 0;
5608 sq->end();
5609 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
5610 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
5611#if 0
5612 if (kUseFastCapture == FastCapture_Dynamic) {
5613 // FIXME
5614 }
5615#endif
5616#ifdef AUDIO_WATCHDOG
5617 // FIXME
5618#endif
5619 } else {
5620 sq->end(false /*didModify*/);
5621 }
5622 }
Eric Laurent81784c32012-11-19 14:55:58 -08005623 mInput->stream->common.standby(&mInput->stream->common);
5624}
5625
Glenn Kasten05997e22014-03-13 15:08:33 -07005626// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07005627sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08005628 const sp<AudioFlinger::Client>& client,
5629 uint32_t sampleRate,
5630 audio_format_t format,
5631 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08005632 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08005633 int sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07005634 size_t *notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005635 int uid,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07005636 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08005637 pid_t tid,
5638 status_t *status)
5639{
Glenn Kasten74935e42013-12-19 08:56:45 -08005640 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005641 sp<RecordTrack> track;
5642 status_t lStatus;
5643
Glenn Kasten90e58b12013-07-31 16:16:02 -07005644 // client expresses a preference for FAST, but we get the final say
5645 if (*flags & IAudioFlinger::TRACK_FAST) {
5646 if (
Glenn Kasten74105912014-07-03 12:28:53 -07005647 // use case: callback handler
5648 (tid != -1) &&
5649 // frame count is not specified, or is exactly the pipe depth
5650 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005651 // PCM data
5652 audio_is_linear_pcm(format) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005653 // native format
5654 (format == mFormat) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005655 // native channel mask
5656 (channelMask == mChannelMask) &&
5657 // native hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07005658 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005659 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005660 hasFastCapture() &&
5661 // there are sufficient fast track slots available
5662 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07005663 ) {
Glenn Kasten74105912014-07-03 12:28:53 -07005664 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%u mFrameCount=%u",
Glenn Kasten90e58b12013-07-31 16:16:02 -07005665 frameCount, mFrameCount);
5666 } else {
Glenn Kasten74105912014-07-03 12:28:53 -07005667 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%u mFrameCount=%u mPipeFramesP2=%u "
5668 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005669 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Glenn Kasten74105912014-07-03 12:28:53 -07005670 frameCount, mFrameCount, mPipeFramesP2,
5671 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
5672 hasFastCapture(), tid, mFastTrackAvail);
Glenn Kasten90e58b12013-07-31 16:16:02 -07005673 *flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kasten74105912014-07-03 12:28:53 -07005674 }
5675 }
5676
5677 // compute track buffer size in frames, and suggest the notification frame count
5678 if (*flags & IAudioFlinger::TRACK_FAST) {
5679 // fast track: frame count is exactly the pipe depth
5680 frameCount = mPipeFramesP2;
5681 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
5682 *notificationFrames = mFrameCount;
5683 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07005684 // not fast track: max notification period is resampled equivalent of one HAL buffer time
5685 // or 20 ms if there is a fast capture
5686 // TODO This could be a roundupRatio inline, and const
5687 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
5688 * sampleRate + mSampleRate - 1) / mSampleRate;
5689 // minimum number of notification periods is at least kMinNotifications,
5690 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
5691 static const size_t kMinNotifications = 3;
5692 static const uint32_t kMinMs = 30;
5693 // TODO This could be a roundupRatio inline
5694 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
5695 // TODO This could be a roundupRatio inline
5696 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
5697 maxNotificationFrames;
5698 const size_t minFrameCount = maxNotificationFrames *
5699 max(kMinNotifications, minNotificationsByMs);
5700 frameCount = max(frameCount, minFrameCount);
5701 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
5702 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07005703 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07005704 }
Glenn Kasten74935e42013-12-19 08:56:45 -08005705 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07005706
Glenn Kasten15e57982013-09-24 11:52:37 -07005707 lStatus = initCheck();
5708 if (lStatus != NO_ERROR) {
5709 ALOGE("createRecordTrack_l() audio driver not initialized");
5710 goto Exit;
5711 }
Eric Laurent81784c32012-11-19 14:55:58 -08005712
5713 { // scope for mLock
5714 Mutex::Autolock _l(mLock);
5715
5716 track = new RecordTrack(this, client, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07005717 format, channelMask, frameCount, NULL, sessionId, uid,
5718 *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08005719
Glenn Kasten03003332013-08-06 15:40:54 -07005720 lStatus = track->initCheck();
5721 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07005722 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08005723 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08005724 goto Exit;
5725 }
5726 mTracks.add(track);
5727
5728 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5729 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
5730 mAudioFlinger->btNrecIsOff();
5731 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
5732 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07005733
5734 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
5735 pid_t callingPid = IPCThreadState::self()->getCallingPid();
5736 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
5737 // so ask activity manager to do this on our behalf
5738 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
5739 }
Eric Laurent81784c32012-11-19 14:55:58 -08005740 }
Glenn Kasten05997e22014-03-13 15:08:33 -07005741
Eric Laurent81784c32012-11-19 14:55:58 -08005742 lStatus = NO_ERROR;
5743
5744Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07005745 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08005746 return track;
5747}
5748
5749status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
5750 AudioSystem::sync_event_t event,
5751 int triggerSession)
5752{
5753 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
5754 sp<ThreadBase> strongMe = this;
5755 status_t status = NO_ERROR;
5756
5757 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005758 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08005759 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005760 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08005761 triggerSession,
5762 recordTrack->sessionId(),
5763 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005764 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08005765 // Sync event can be cancelled by the trigger session if the track is not in a
5766 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005767 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005768 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08005769 } else {
5770 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005771 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005772 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08005773 }
5774 }
5775
5776 {
Glenn Kasten47c20702013-08-13 15:37:35 -07005777 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08005778 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005779 if (mActiveTracks.indexOf(recordTrack) >= 0) {
5780 if (recordTrack->mState == TrackBase::PAUSING) {
5781 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005782 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005783 } else {
5784 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08005785 }
5786 return status;
5787 }
5788
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005789 // TODO consider other ways of handling this, such as changing the state to :STARTING and
5790 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
5791 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005792 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08005793 mActiveTracks.add(recordTrack);
5794 mActiveTracksGen++;
Eric Laurent83b88082014-06-20 18:31:16 -07005795 status_t status = NO_ERROR;
5796 if (recordTrack->isExternalTrack()) {
5797 mLock.unlock();
Eric Laurent4dc68062014-07-28 17:26:49 -07005798 status = AudioSystem::startInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07005799 mLock.lock();
5800 // FIXME should verify that recordTrack is still in mActiveTracks
5801 if (status != NO_ERROR) {
5802 mActiveTracks.remove(recordTrack);
5803 mActiveTracksGen++;
5804 recordTrack->clearSyncStartEvent();
5805 ALOGV("RecordThread::start error %d", status);
5806 return status;
5807 }
Eric Laurent81784c32012-11-19 14:55:58 -08005808 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005809 // Catch up with current buffer indices if thread is already running.
5810 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
5811 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
5812 // see previously buffered data before it called start(), but with greater risk of overrun.
5813
5814 recordTrack->mRsmpInFront = mRsmpInRear;
5815 recordTrack->mRsmpInUnrel = 0;
5816 // FIXME why reset?
5817 if (recordTrack->mResampler != NULL) {
5818 recordTrack->mResampler->reset();
Eric Laurent81784c32012-11-19 14:55:58 -08005819 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005820 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08005821 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08005822 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08005823 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005824 ALOGV("Record failed to start");
5825 status = BAD_VALUE;
5826 goto startError;
5827 }
Eric Laurent81784c32012-11-19 14:55:58 -08005828 return status;
5829 }
Glenn Kasten7c027242012-12-26 14:43:16 -08005830
Eric Laurent81784c32012-11-19 14:55:58 -08005831startError:
Eric Laurent83b88082014-06-20 18:31:16 -07005832 if (recordTrack->isExternalTrack()) {
Eric Laurent4dc68062014-07-28 17:26:49 -07005833 AudioSystem::stopInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07005834 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005835 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005836 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08005837 return status;
5838}
5839
Eric Laurent81784c32012-11-19 14:55:58 -08005840void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
5841{
5842 sp<SyncEvent> strongEvent = event.promote();
5843
5844 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08005845 sp<RefBase> ptr = strongEvent->cookie().promote();
5846 if (ptr != 0) {
5847 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
5848 recordTrack->handleSyncStartEvent(strongEvent);
5849 }
Eric Laurent81784c32012-11-19 14:55:58 -08005850 }
5851}
5852
Glenn Kastena8356f62013-07-25 14:37:52 -07005853bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08005854 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07005855 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005856 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08005857 return false;
5858 }
Glenn Kasten47c20702013-08-13 15:37:35 -07005859 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08005860 recordTrack->mState = TrackBase::PAUSING;
5861 // do not wait for mStartStopCond if exiting
5862 if (exitPending()) {
5863 return true;
5864 }
Glenn Kasten47c20702013-08-13 15:37:35 -07005865 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08005866 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005867 // if we have been restarted, recordTrack is in mActiveTracks here
5868 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005869 ALOGV("Record stopped OK");
5870 return true;
5871 }
5872 return false;
5873}
5874
Glenn Kasten0f11b512014-01-31 16:18:54 -08005875bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08005876{
5877 return false;
5878}
5879
Glenn Kasten0f11b512014-01-31 16:18:54 -08005880status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005881{
5882#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
5883 if (!isValidSyncEvent(event)) {
5884 return BAD_VALUE;
5885 }
5886
5887 int eventSession = event->triggerSession();
5888 status_t ret = NAME_NOT_FOUND;
5889
5890 Mutex::Autolock _l(mLock);
5891
5892 for (size_t i = 0; i < mTracks.size(); i++) {
5893 sp<RecordTrack> track = mTracks[i];
5894 if (eventSession == track->sessionId()) {
5895 (void) track->setSyncEvent(event);
5896 ret = NO_ERROR;
5897 }
5898 }
5899 return ret;
5900#else
5901 return BAD_VALUE;
5902#endif
5903}
5904
5905// destroyTrack_l() must be called with ThreadBase::mLock held
5906void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
5907{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005908 track->terminate();
5909 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08005910 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08005911 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005912 removeTrack_l(track);
5913 }
5914}
5915
5916void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
5917{
5918 mTracks.remove(track);
5919 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005920 if (track->isFastTrack()) {
5921 ALOG_ASSERT(!mFastTrackAvail);
5922 mFastTrackAvail = true;
5923 }
Eric Laurent81784c32012-11-19 14:55:58 -08005924}
5925
5926void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
5927{
5928 dumpInternals(fd, args);
5929 dumpTracks(fd, args);
5930 dumpEffectChains(fd, args);
5931}
5932
5933void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
5934{
Elliott Hughes87cebad2014-05-22 10:14:43 -07005935 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08005936
Glenn Kasten2b806402013-11-20 16:37:38 -08005937 if (mActiveTracks.size() > 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07005938 dprintf(fd, " Buffer size: %zu bytes\n", mBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005939 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07005940 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08005941 }
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005942 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005943 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Eric Laurent81784c32012-11-19 14:55:58 -08005944
Eric Laurent81784c32012-11-19 14:55:58 -08005945 dumpBase(fd, args);
5946}
5947
Glenn Kasten0f11b512014-01-31 16:18:54 -08005948void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005949{
5950 const size_t SIZE = 256;
5951 char buffer[SIZE];
5952 String8 result;
5953
Marco Nelissenb2208842014-02-07 14:00:50 -08005954 size_t numtracks = mTracks.size();
5955 size_t numactive = mActiveTracks.size();
5956 size_t numactiveseen = 0;
Elliott Hughes87cebad2014-05-22 10:14:43 -07005957 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08005958 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07005959 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08005960 RecordTrack::appendDumpHeader(result);
5961 for (size_t i = 0; i < numtracks ; ++i) {
5962 sp<RecordTrack> track = mTracks[i];
5963 if (track != 0) {
5964 bool active = mActiveTracks.indexOf(track) >= 0;
5965 if (active) {
5966 numactiveseen++;
5967 }
5968 track->dump(buffer, SIZE, active);
5969 result.append(buffer);
5970 }
Eric Laurent81784c32012-11-19 14:55:58 -08005971 }
Marco Nelissenb2208842014-02-07 14:00:50 -08005972 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07005973 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08005974 }
5975
Marco Nelissenb2208842014-02-07 14:00:50 -08005976 if (numactiveseen != numactive) {
5977 snprintf(buffer, SIZE, " The following tracks are in the active list but"
5978 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08005979 result.append(buffer);
5980 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08005981 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08005982 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08005983 if (mTracks.indexOf(track) < 0) {
5984 track->dump(buffer, SIZE, true);
5985 result.append(buffer);
5986 }
Glenn Kasten2b806402013-11-20 16:37:38 -08005987 }
Eric Laurent81784c32012-11-19 14:55:58 -08005988
5989 }
5990 write(fd, result.string(), result.size());
5991}
5992
5993// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005994status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
5995 AudioBufferProvider::Buffer* buffer, int64_t pts __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005996{
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005997 RecordTrack *activeTrack = mRecordTrack;
5998 sp<ThreadBase> threadBase = activeTrack->mThread.promote();
5999 if (threadBase == 0) {
6000 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006001 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006002 return NOT_ENOUGH_DATA;
6003 }
6004 RecordThread *recordThread = (RecordThread *) threadBase.get();
6005 int32_t rear = recordThread->mRsmpInRear;
6006 int32_t front = activeTrack->mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07006007 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006008 // FIXME should not be P2 (don't want to increase latency)
6009 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006010 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07006011 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006012 front &= recordThread->mRsmpInFramesP2 - 1;
6013 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07006014 if (part1 > (size_t) filled) {
6015 part1 = filled;
6016 }
6017 size_t ask = buffer->frameCount;
6018 ALOG_ASSERT(ask > 0);
6019 if (part1 > ask) {
6020 part1 = ask;
6021 }
6022 if (part1 == 0) {
6023 // Higher-level should keep mRsmpInBuffer full, and not call resampler if empty
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006024 LOG_ALWAYS_FATAL("RecordThread::getNextBuffer() starved");
Glenn Kasten85948432013-08-19 12:09:05 -07006025 buffer->raw = NULL;
6026 buffer->frameCount = 0;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006027 activeTrack->mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07006028 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08006029 }
6030
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006031 buffer->raw = recordThread->mRsmpInBuffer + front * recordThread->mChannelCount;
Glenn Kasten85948432013-08-19 12:09:05 -07006032 buffer->frameCount = part1;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006033 activeTrack->mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08006034 return NO_ERROR;
6035}
6036
6037// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006038void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
6039 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006040{
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006041 RecordTrack *activeTrack = mRecordTrack;
Glenn Kasten85948432013-08-19 12:09:05 -07006042 size_t stepCount = buffer->frameCount;
6043 if (stepCount == 0) {
6044 return;
6045 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006046 ALOG_ASSERT(stepCount <= activeTrack->mRsmpInUnrel);
6047 activeTrack->mRsmpInUnrel -= stepCount;
6048 activeTrack->mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07006049 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006050 buffer->frameCount = 0;
6051}
6052
Eric Laurent10351942014-05-08 18:49:52 -07006053bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
6054 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006055{
6056 bool reconfig = false;
6057
Eric Laurent10351942014-05-08 18:49:52 -07006058 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006059
Eric Laurent10351942014-05-08 18:49:52 -07006060 audio_format_t reqFormat = mFormat;
6061 uint32_t samplingRate = mSampleRate;
6062 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
6063
6064 AudioParameter param = AudioParameter(keyValuePair);
6065 int value;
6066 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
6067 // channel count change can be requested. Do we mandate the first client defines the
6068 // HAL sampling rate and channel count or do we allow changes on the fly?
6069 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6070 samplingRate = value;
6071 reconfig = true;
6072 }
6073 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
6074 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
6075 status = BAD_VALUE;
6076 } else {
6077 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08006078 reconfig = true;
6079 }
Eric Laurent10351942014-05-08 18:49:52 -07006080 }
6081 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
6082 audio_channel_mask_t mask = (audio_channel_mask_t) value;
6083 if (mask != AUDIO_CHANNEL_IN_MONO && mask != AUDIO_CHANNEL_IN_STEREO) {
6084 status = BAD_VALUE;
6085 } else {
6086 channelMask = mask;
6087 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006088 }
Eric Laurent10351942014-05-08 18:49:52 -07006089 }
6090 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6091 // do not accept frame count changes if tracks are open as the track buffer
6092 // size depends on frame count and correct behavior would not be guaranteed
6093 // if frame count is changed after track creation
6094 if (mActiveTracks.size() > 0) {
6095 status = INVALID_OPERATION;
6096 } else {
6097 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006098 }
Eric Laurent10351942014-05-08 18:49:52 -07006099 }
6100 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6101 // forward device change to effects that have requested to be
6102 // aware of attached audio device.
6103 for (size_t i = 0; i < mEffectChains.size(); i++) {
6104 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08006105 }
Eric Laurent81784c32012-11-19 14:55:58 -08006106
Eric Laurent10351942014-05-08 18:49:52 -07006107 // store input device and output device but do not forward output device to audio HAL.
6108 // Note that status is ignored by the caller for output device
6109 // (see AudioFlinger::setParameters()
6110 if (audio_is_output_devices(value)) {
6111 mOutDevice = value;
6112 status = BAD_VALUE;
6113 } else {
6114 mInDevice = value;
6115 // disable AEC and NS if the device is a BT SCO headset supporting those
6116 // pre processings
6117 if (mTracks.size() > 0) {
6118 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6119 mAudioFlinger->btNrecIsOff();
6120 for (size_t i = 0; i < mTracks.size(); i++) {
6121 sp<RecordTrack> track = mTracks[i];
6122 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
6123 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08006124 }
6125 }
6126 }
Eric Laurent10351942014-05-08 18:49:52 -07006127 }
6128 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
6129 mAudioSource != (audio_source_t)value) {
6130 // forward device change to effects that have requested to be
6131 // aware of attached audio device.
6132 for (size_t i = 0; i < mEffectChains.size(); i++) {
6133 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08006134 }
Eric Laurent10351942014-05-08 18:49:52 -07006135 mAudioSource = (audio_source_t)value;
6136 }
Glenn Kastene198c362013-08-13 09:13:36 -07006137
Eric Laurent10351942014-05-08 18:49:52 -07006138 if (status == NO_ERROR) {
6139 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6140 keyValuePair.string());
6141 if (status == INVALID_OPERATION) {
6142 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006143 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6144 keyValuePair.string());
Eric Laurent10351942014-05-08 18:49:52 -07006145 }
6146 if (reconfig) {
6147 if (status == BAD_VALUE &&
6148 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
6149 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
6150 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
6151 <= (2 * samplingRate)) &&
Andy Hunge5412692014-05-16 11:25:07 -07006152 audio_channel_count_from_in_mask(
6153 mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
Eric Laurent10351942014-05-08 18:49:52 -07006154 (channelMask == AUDIO_CHANNEL_IN_MONO ||
6155 channelMask == AUDIO_CHANNEL_IN_STEREO)) {
6156 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006157 }
Eric Laurent10351942014-05-08 18:49:52 -07006158 if (status == NO_ERROR) {
6159 readInputParameters_l();
6160 sendIoConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08006161 }
6162 }
Eric Laurent81784c32012-11-19 14:55:58 -08006163 }
Eric Laurent10351942014-05-08 18:49:52 -07006164
Eric Laurent81784c32012-11-19 14:55:58 -08006165 return reconfig;
6166}
6167
6168String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6169{
Eric Laurent81784c32012-11-19 14:55:58 -08006170 Mutex::Autolock _l(mLock);
6171 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07006172 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08006173 }
6174
Glenn Kastend8ea6992013-07-16 14:17:15 -07006175 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
6176 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08006177 free(s);
6178 return out_s8;
6179}
6180
Eric Laurent021cf962014-05-13 10:18:14 -07006181void AudioFlinger::RecordThread::audioConfigChanged(int event, int param __unused) {
Eric Laurent81784c32012-11-19 14:55:58 -08006182 AudioSystem::OutputDescriptor desc;
Glenn Kastenb2737d02013-08-19 12:03:11 -07006183 const void *param2 = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006184
6185 switch (event) {
6186 case AudioSystem::INPUT_OPENED:
6187 case AudioSystem::INPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07006188 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08006189 desc.samplingRate = mSampleRate;
6190 desc.format = mFormat;
6191 desc.frameCount = mFrameCount;
6192 desc.latency = 0;
6193 param2 = &desc;
6194 break;
6195
6196 case AudioSystem::INPUT_CLOSED:
6197 default:
6198 break;
6199 }
Eric Laurent021cf962014-05-13 10:18:14 -07006200 mAudioFlinger->audioConfigChanged(event, mId, param2);
Eric Laurent81784c32012-11-19 14:55:58 -08006201}
6202
Glenn Kastendeca2ae2014-02-07 10:25:56 -08006203void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006204{
Eric Laurent81784c32012-11-19 14:55:58 -08006205 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
6206 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Andy Hunge5412692014-05-16 11:25:07 -07006207 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Andy Hung463be252014-07-10 16:56:07 -07006208 mHALFormat = mInput->stream->common.get_format(&mInput->stream->common);
6209 mFormat = mHALFormat;
Glenn Kasten291bb6d2013-07-16 17:23:39 -07006210 if (mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08006211 ALOGE("HAL format %#x not supported; must be AUDIO_FORMAT_PCM_16_BIT", mFormat);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07006212 }
Eric Laurent665470b2014-07-03 16:37:08 -07006213 mFrameSize = audio_stream_in_frame_size(mInput->stream);
Glenn Kasten548efc92012-11-29 08:48:51 -08006214 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
6215 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006216 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08006217 // 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 -07006218 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08006219 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006220 // A larger value should allow more old data to be read after a track calls start(),
6221 // without increasing latency.
Glenn Kastene8426142014-02-28 16:45:03 -08006222 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07006223 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006224 delete[] mRsmpInBuffer;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006225
6226 // TODO optimize audio capture buffer sizes ...
6227 // Here we calculate the size of the sliding buffer used as a source
6228 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
6229 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
6230 // be better to have it derived from the pipe depth in the long term.
6231 // The current value is higher than necessary. However it should not add to latency.
6232
Glenn Kasten85948432013-08-19 12:09:05 -07006233 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
6234 mRsmpInBuffer = new int16_t[(mRsmpInFramesP2 + mFrameCount - 1) * mChannelCount];
Eric Laurent81784c32012-11-19 14:55:58 -08006235
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006236 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
6237 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08006238}
6239
Glenn Kasten5f972c02014-01-13 09:59:31 -08006240uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08006241{
6242 Mutex::Autolock _l(mLock);
6243 if (initCheck() != NO_ERROR) {
6244 return 0;
6245 }
6246
6247 return mInput->stream->get_input_frames_lost(mInput->stream);
6248}
6249
6250uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
6251{
6252 Mutex::Autolock _l(mLock);
6253 uint32_t result = 0;
6254 if (getEffectChain_l(sessionId) != 0) {
6255 result = EFFECT_SESSION;
6256 }
6257
6258 for (size_t i = 0; i < mTracks.size(); ++i) {
6259 if (sessionId == mTracks[i]->sessionId()) {
6260 result |= TRACK_SESSION;
6261 break;
6262 }
6263 }
6264
6265 return result;
6266}
6267
6268KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
6269{
6270 KeyedVector<int, bool> ids;
6271 Mutex::Autolock _l(mLock);
6272 for (size_t j = 0; j < mTracks.size(); ++j) {
6273 sp<RecordThread::RecordTrack> track = mTracks[j];
6274 int sessionId = track->sessionId();
6275 if (ids.indexOfKey(sessionId) < 0) {
6276 ids.add(sessionId, true);
6277 }
6278 }
6279 return ids;
6280}
6281
6282AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
6283{
6284 Mutex::Autolock _l(mLock);
6285 AudioStreamIn *input = mInput;
6286 mInput = NULL;
6287 return input;
6288}
6289
6290// this method must always be called either with ThreadBase mLock held or inside the thread loop
6291audio_stream_t* AudioFlinger::RecordThread::stream() const
6292{
6293 if (mInput == NULL) {
6294 return NULL;
6295 }
6296 return &mInput->stream->common;
6297}
6298
6299status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6300{
6301 // only one chain per input thread
6302 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07006303 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08006304 return INVALID_OPERATION;
6305 }
6306 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07006307 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08006308 chain->setInBuffer(NULL);
6309 chain->setOutBuffer(NULL);
6310
6311 checkSuspendOnAddEffectChain_l(chain);
6312
Eric Laurent1b928682014-10-02 19:41:47 -07006313 // make sure enabled pre processing effects state is communicated to the HAL as we
6314 // just moved them to a new input stream.
6315 chain->syncHalEffectsState();
6316
Eric Laurent81784c32012-11-19 14:55:58 -08006317 mEffectChains.add(chain);
6318
6319 return NO_ERROR;
6320}
6321
6322size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6323{
6324 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
6325 ALOGW_IF(mEffectChains.size() != 1,
6326 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6327 chain.get(), mEffectChains.size(), this);
6328 if (mEffectChains.size() == 1) {
6329 mEffectChains.removeAt(0);
6330 }
6331 return 0;
6332}
6333
Eric Laurent1c333e22014-05-20 10:48:17 -07006334status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
6335 audio_patch_handle_t *handle)
6336{
6337 status_t status = NO_ERROR;
6338 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
6339 // store new device and send to effects
6340 mInDevice = patch->sources[0].ext.device.type;
6341 for (size_t i = 0; i < mEffectChains.size(); i++) {
6342 mEffectChains[i]->setDevice_l(mInDevice);
6343 }
6344
6345 // disable AEC and NS if the device is a BT SCO headset supporting those
6346 // pre processings
6347 if (mTracks.size() > 0) {
6348 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6349 mAudioFlinger->btNrecIsOff();
6350 for (size_t i = 0; i < mTracks.size(); i++) {
6351 sp<RecordTrack> track = mTracks[i];
6352 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
6353 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
6354 }
6355 }
6356
6357 // store new source and send to effects
6358 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
6359 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
6360 for (size_t i = 0; i < mEffectChains.size(); i++) {
6361 mEffectChains[i]->setAudioSource_l(mAudioSource);
6362 }
6363 }
6364
6365 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
6366 status = hwDevice->create_audio_patch(hwDevice,
6367 patch->num_sources,
6368 patch->sources,
6369 patch->num_sinks,
6370 patch->sinks,
6371 handle);
6372 } else {
6373 ALOG_ASSERT(false, "createAudioPatch_l() called on a pre 3.0 HAL");
6374 }
6375 return status;
6376}
6377
6378status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
6379{
6380 status_t status = NO_ERROR;
6381 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
6382 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
6383 status = hwDevice->release_audio_patch(hwDevice, handle);
6384 } else {
6385 ALOG_ASSERT(false, "releaseAudioPatch_l() called on a pre 3.0 HAL");
6386 }
6387 return status;
6388}
6389
Eric Laurent83b88082014-06-20 18:31:16 -07006390void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
6391{
6392 Mutex::Autolock _l(mLock);
6393 mTracks.add(record);
6394}
6395
6396void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
6397{
6398 Mutex::Autolock _l(mLock);
6399 destroyTrack_l(record);
6400}
6401
6402void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
6403{
6404 ThreadBase::getAudioPortConfig(config);
6405 config->role = AUDIO_PORT_ROLE_SINK;
6406 config->ext.mix.hw_module = mInput->audioHwDev->handle();
6407 config->ext.mix.usecase.source = mAudioSource;
6408}
Eric Laurent1c333e22014-05-20 10:48:17 -07006409
Eric Laurent81784c32012-11-19 14:55:58 -08006410}; // namespace android