blob: 646833bdb35a4022c7785643ab8a876c0ddc7714 [file] [log] [blame]
Eric Laurent81784c32012-11-19 14:55:58 -08001/*
2**
3** Copyright 2012, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
Alex Ray371eb972012-11-30 11:11:54 -080021#define ATRACE_TAG ATRACE_TAG_AUDIO
Eric Laurent81784c32012-11-19 14:55:58 -080022
Glenn Kasten153b9fe2013-07-15 11:23:36 -070023#include "Configuration.h"
Eric Laurent81784c32012-11-19 14:55:58 -080024#include <math.h>
25#include <fcntl.h>
26#include <sys/stat.h>
27#include <cutils/properties.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070028#include <media/AudioParameter.h>
Andy Hungcd044842014-08-07 11:04:34 -070029#include <media/AudioResamplerPublic.h>
Eric Laurent81784c32012-11-19 14:55:58 -080030#include <utils/Log.h>
Alex Ray371eb972012-11-30 11:11:54 -080031#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080032
33#include <private/media/AudioTrackShared.h>
34#include <hardware/audio.h>
35#include <audio_effects/effect_ns.h>
36#include <audio_effects/effect_aec.h>
37#include <audio_utils/primitives.h>
Andy Hung98ef9782014-03-04 14:46:50 -080038#include <audio_utils/format.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070039#include <audio_utils/minifloat.h>
Eric Laurent81784c32012-11-19 14:55:58 -080040
41// NBAIO implementations
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070042#include <media/nbaio/AudioStreamInSource.h>
Eric Laurent81784c32012-11-19 14:55:58 -080043#include <media/nbaio/AudioStreamOutSink.h>
44#include <media/nbaio/MonoPipe.h>
45#include <media/nbaio/MonoPipeReader.h>
46#include <media/nbaio/Pipe.h>
47#include <media/nbaio/PipeReader.h>
48#include <media/nbaio/SourceAudioBufferProvider.h>
49
50#include <powermanager/PowerManager.h>
51
52#include <common_time/cc_helper.h>
53#include <common_time/local_clock.h>
54
55#include "AudioFlinger.h"
56#include "AudioMixer.h"
57#include "FastMixer.h"
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070058#include "FastCapture.h"
Eric Laurent81784c32012-11-19 14:55:58 -080059#include "ServiceUtilities.h"
60#include "SchedulingPolicyService.h"
61
Eric Laurent81784c32012-11-19 14:55:58 -080062#ifdef ADD_BATTERY_DATA
63#include <media/IMediaPlayerService.h>
64#include <media/IMediaDeathNotifier.h>
65#endif
66
Eric Laurent81784c32012-11-19 14:55:58 -080067#ifdef DEBUG_CPU_USAGE
68#include <cpustats/CentralTendencyStatistics.h>
69#include <cpustats/ThreadCpuUsage.h>
70#endif
71
72// ----------------------------------------------------------------------------
73
74// Note: the following macro is used for extremely verbose logging message. In
75// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
76// 0; but one side effect of this is to turn all LOGV's as well. Some messages
77// are so verbose that we want to suppress them even when we have ALOG_ASSERT
78// turned on. Do not uncomment the #def below unless you really know what you
79// are doing and want to see all of the extremely verbose messages.
80//#define VERY_VERY_VERBOSE_LOGGING
81#ifdef VERY_VERY_VERBOSE_LOGGING
82#define ALOGVV ALOGV
83#else
84#define ALOGVV(a...) do { } while(0)
85#endif
86
Glenn Kasten49d00ad2014-07-21 11:22:03 -070087#define max(a, b) ((a) > (b) ? (a) : (b))
88
Eric Laurent81784c32012-11-19 14:55:58 -080089namespace android {
90
91// retry counts for buffer fill timeout
92// 50 * ~20msecs = 1 second
93static const int8_t kMaxTrackRetries = 50;
94static const int8_t kMaxTrackStartupRetries = 50;
95// allow less retry attempts on direct output thread.
96// direct outputs can be a scarce resource in audio hardware and should
97// be released as quickly as possible.
98static const int8_t kMaxTrackRetriesDirect = 2;
99
100// don't warn about blocked writes or record buffer overflows more often than this
101static const nsecs_t kWarningThrottleNs = seconds(5);
102
103// RecordThread loop sleep time upon application overrun or audio HAL read error
104static const int kRecordThreadSleepUs = 5000;
105
Eric Laurent10351942014-05-08 18:49:52 -0700106// maximum time to wait in sendConfigEvent_l() for a status to be received
107static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800108
109// minimum sleep time for the mixer thread loop when tracks are active but in underrun
110static const uint32_t kMinThreadSleepTimeUs = 5000;
111// maximum divider applied to the active sleep time in the mixer thread loop
112static const uint32_t kMaxThreadSleepTimeShift = 2;
113
Andy Hung09a50072014-02-27 14:30:47 -0800114// minimum normal sink buffer size, expressed in milliseconds rather than frames
115static const uint32_t kMinNormalSinkBufferSizeMs = 20;
116// maximum normal sink buffer size
117static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800118
Eric Laurent972a1732013-09-04 09:42:59 -0700119// Offloaded output thread standby delay: allows track transition without going to standby
120static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
121
Eric Laurent81784c32012-11-19 14:55:58 -0800122// Whether to use fast mixer
123static const enum {
124 FastMixer_Never, // never initialize or use: for debugging only
125 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
126 // normal mixer multiplier is 1
127 FastMixer_Static, // initialize if needed, then use all the time if initialized,
128 // multiplier is calculated based on min & max normal mixer buffer size
129 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
130 // multiplier is calculated based on min & max normal mixer buffer size
131 // FIXME for FastMixer_Dynamic:
132 // Supporting this option will require fixing HALs that can't handle large writes.
133 // For example, one HAL implementation returns an error from a large write,
134 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
135 // We could either fix the HAL implementations, or provide a wrapper that breaks
136 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
137} kUseFastMixer = FastMixer_Static;
138
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700139// Whether to use fast capture
140static const enum {
141 FastCapture_Never, // never initialize or use: for debugging only
142 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
143 FastCapture_Static, // initialize if needed, then use all the time if initialized
144} kUseFastCapture = FastCapture_Static;
145
Eric Laurent81784c32012-11-19 14:55:58 -0800146// Priorities for requestPriority
147static const int kPriorityAudioApp = 2;
148static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700149static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800150
151// IAudioFlinger::createTrack() reports back to client the total size of shared memory area
152// for the track. The client then sub-divides this into smaller buffers for its use.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800153// Currently the client uses N-buffering by default, but doesn't tell us about the value of N.
154// So for now we just assume that client is double-buffered for fast tracks.
155// FIXME It would be better for client to tell AudioFlinger the value of N,
156// so AudioFlinger could allocate the right amount of memory.
Eric Laurent81784c32012-11-19 14:55:58 -0800157// See the client's minBufCount and mNotificationFramesAct calculations for details.
Glenn Kasten03490092014-05-27 12:30:54 -0700158
159// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800160static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800161
Glenn Kasten03490092014-05-27 12:30:54 -0700162// The minimum and maximum allowed values
163static const int kFastTrackMultiplierMin = 1;
164static const int kFastTrackMultiplierMax = 2;
165
166// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
167static int sFastTrackMultiplier = kFastTrackMultiplier;
168
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700169// See Thread::readOnlyHeap().
170// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
171// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
172// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Glenn Kasten9f81de32014-07-27 15:02:23 -0700173static const size_t kRecordThreadReadOnlyHeapSize = 0x2000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700174
Eric Laurent81784c32012-11-19 14:55:58 -0800175// ----------------------------------------------------------------------------
176
Glenn Kasten03490092014-05-27 12:30:54 -0700177static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
178
179static void sFastTrackMultiplierInit()
180{
181 char value[PROPERTY_VALUE_MAX];
182 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
183 char *endptr;
184 unsigned long ul = strtoul(value, &endptr, 0);
185 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
186 sFastTrackMultiplier = (int) ul;
187 }
188 }
189}
190
191// ----------------------------------------------------------------------------
192
Eric Laurent81784c32012-11-19 14:55:58 -0800193#ifdef ADD_BATTERY_DATA
194// To collect the amplifier usage
195static void addBatteryData(uint32_t params) {
196 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
197 if (service == NULL) {
198 // it already logged
199 return;
200 }
201
202 service->addBatteryData(params);
203}
204#endif
205
206
207// ----------------------------------------------------------------------------
208// CPU Stats
209// ----------------------------------------------------------------------------
210
211class CpuStats {
212public:
213 CpuStats();
214 void sample(const String8 &title);
215#ifdef DEBUG_CPU_USAGE
216private:
217 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
218 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
219
220 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
221
222 int mCpuNum; // thread's current CPU number
223 int mCpukHz; // frequency of thread's current CPU in kHz
224#endif
225};
226
227CpuStats::CpuStats()
228#ifdef DEBUG_CPU_USAGE
229 : mCpuNum(-1), mCpukHz(-1)
230#endif
231{
232}
233
Glenn Kasten0f11b512014-01-31 16:18:54 -0800234void CpuStats::sample(const String8 &title
235#ifndef DEBUG_CPU_USAGE
236 __unused
237#endif
238 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800239#ifdef DEBUG_CPU_USAGE
240 // get current thread's delta CPU time in wall clock ns
241 double wcNs;
242 bool valid = mCpuUsage.sampleAndEnable(wcNs);
243
244 // record sample for wall clock statistics
245 if (valid) {
246 mWcStats.sample(wcNs);
247 }
248
249 // get the current CPU number
250 int cpuNum = sched_getcpu();
251
252 // get the current CPU frequency in kHz
253 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
254
255 // check if either CPU number or frequency changed
256 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
257 mCpuNum = cpuNum;
258 mCpukHz = cpukHz;
259 // ignore sample for purposes of cycles
260 valid = false;
261 }
262
263 // if no change in CPU number or frequency, then record sample for cycle statistics
264 if (valid && mCpukHz > 0) {
265 double cycles = wcNs * cpukHz * 0.000001;
266 mHzStats.sample(cycles);
267 }
268
269 unsigned n = mWcStats.n();
270 // mCpuUsage.elapsed() is expensive, so don't call it every loop
271 if ((n & 127) == 1) {
272 long long elapsed = mCpuUsage.elapsed();
273 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
274 double perLoop = elapsed / (double) n;
275 double perLoop100 = perLoop * 0.01;
276 double perLoop1k = perLoop * 0.001;
277 double mean = mWcStats.mean();
278 double stddev = mWcStats.stddev();
279 double minimum = mWcStats.minimum();
280 double maximum = mWcStats.maximum();
281 double meanCycles = mHzStats.mean();
282 double stddevCycles = mHzStats.stddev();
283 double minCycles = mHzStats.minimum();
284 double maxCycles = mHzStats.maximum();
285 mCpuUsage.resetElapsed();
286 mWcStats.reset();
287 mHzStats.reset();
288 ALOGD("CPU usage for %s over past %.1f secs\n"
289 " (%u mixer loops at %.1f mean ms per loop):\n"
290 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
291 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
292 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
293 title.string(),
294 elapsed * .000000001, n, perLoop * .000001,
295 mean * .001,
296 stddev * .001,
297 minimum * .001,
298 maximum * .001,
299 mean / perLoop100,
300 stddev / perLoop100,
301 minimum / perLoop100,
302 maximum / perLoop100,
303 meanCycles / perLoop1k,
304 stddevCycles / perLoop1k,
305 minCycles / perLoop1k,
306 maxCycles / perLoop1k);
307
308 }
309 }
310#endif
311};
312
313// ----------------------------------------------------------------------------
314// ThreadBase
315// ----------------------------------------------------------------------------
316
317AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
318 audio_devices_t outDevice, audio_devices_t inDevice, type_t type)
319 : Thread(false /*canCallJava*/),
320 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700321 mAudioFlinger(audioFlinger),
Glenn Kasten70949c42013-08-06 07:40:12 -0700322 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800323 // are set by PlaybackThread::readOutputParameters_l() or
324 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700325 //FIXME: mStandby should be true here. Is this some kind of hack?
Eric Laurent81784c32012-11-19 14:55:58 -0800326 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
327 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
328 // mName will be set by concrete (non-virtual) subclass
329 mDeathRecipient(new PMDeathRecipient(this))
330{
331}
332
333AudioFlinger::ThreadBase::~ThreadBase()
334{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700335 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700336 mConfigEvents.clear();
337
Eric Laurent81784c32012-11-19 14:55:58 -0800338 // do not lock the mutex in destructor
339 releaseWakeLock_l();
340 if (mPowerManager != 0) {
341 sp<IBinder> binder = mPowerManager->asBinder();
342 binder->unlinkToDeath(mDeathRecipient);
343 }
344}
345
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700346status_t AudioFlinger::ThreadBase::readyToRun()
347{
348 status_t status = initCheck();
349 if (status == NO_ERROR) {
350 ALOGI("AudioFlinger's thread %p ready to run", this);
351 } else {
352 ALOGE("No working audio driver found.");
353 }
354 return status;
355}
356
Eric Laurent81784c32012-11-19 14:55:58 -0800357void AudioFlinger::ThreadBase::exit()
358{
359 ALOGV("ThreadBase::exit");
360 // do any cleanup required for exit to succeed
361 preExit();
362 {
363 // This lock prevents the following race in thread (uniprocessor for illustration):
364 // if (!exitPending()) {
365 // // context switch from here to exit()
366 // // exit() calls requestExit(), what exitPending() observes
367 // // exit() calls signal(), which is dropped since no waiters
368 // // context switch back from exit() to here
369 // mWaitWorkCV.wait(...);
370 // // now thread is hung
371 // }
372 AutoMutex lock(mLock);
373 requestExit();
374 mWaitWorkCV.broadcast();
375 }
376 // When Thread::requestExitAndWait is made virtual and this method is renamed to
377 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
378 requestExitAndWait();
379}
380
381status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
382{
383 status_t status;
384
385 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
386 Mutex::Autolock _l(mLock);
387
Eric Laurent10351942014-05-08 18:49:52 -0700388 return sendSetParameterConfigEvent_l(keyValuePairs);
389}
390
391// sendConfigEvent_l() must be called with ThreadBase::mLock held
392// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
393status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
394{
395 status_t status = NO_ERROR;
396
397 mConfigEvents.add(event);
398 ALOGV("sendConfigEvent_l() num events %d event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800399 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700400 mLock.unlock();
401 {
402 Mutex::Autolock _l(event->mLock);
403 while (event->mWaitStatus) {
404 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
405 event->mStatus = TIMED_OUT;
406 event->mWaitStatus = false;
407 }
408 }
409 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800410 }
Eric Laurent10351942014-05-08 18:49:52 -0700411 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800412 return status;
413}
414
415void AudioFlinger::ThreadBase::sendIoConfigEvent(int event, int param)
416{
417 Mutex::Autolock _l(mLock);
418 sendIoConfigEvent_l(event, param);
419}
420
421// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
422void AudioFlinger::ThreadBase::sendIoConfigEvent_l(int event, int param)
423{
Eric Laurent10351942014-05-08 18:49:52 -0700424 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, param);
425 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800426}
427
428// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
429void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
430{
Eric Laurent10351942014-05-08 18:49:52 -0700431 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio);
432 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800433}
434
Eric Laurent10351942014-05-08 18:49:52 -0700435// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
436status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800437{
Eric Laurent10351942014-05-08 18:49:52 -0700438 sp<ConfigEvent> configEvent = (ConfigEvent *)new SetParameterConfigEvent(keyValuePair);
439 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700440}
441
Eric Laurent1c333e22014-05-20 10:48:17 -0700442status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
443 const struct audio_patch *patch,
444 audio_patch_handle_t *handle)
445{
446 Mutex::Autolock _l(mLock);
447 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
448 status_t status = sendConfigEvent_l(configEvent);
449 if (status == NO_ERROR) {
450 CreateAudioPatchConfigEventData *data =
451 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
452 *handle = data->mHandle;
453 }
454 return status;
455}
456
457status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
458 const audio_patch_handle_t handle)
459{
460 Mutex::Autolock _l(mLock);
461 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
462 return sendConfigEvent_l(configEvent);
463}
464
465
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700466// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700467void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700468{
Eric Laurent10351942014-05-08 18:49:52 -0700469 bool configChanged = false;
470
Eric Laurent81784c32012-11-19 14:55:58 -0800471 while (!mConfigEvents.isEmpty()) {
Eric Laurent10351942014-05-08 18:49:52 -0700472 ALOGV("processConfigEvents_l() remaining events %d", mConfigEvents.size());
473 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800474 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700475 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700476 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700477 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
478 // FIXME Need to understand why this has to be done asynchronously
479 int err = requestPriority(data->mPid, data->mTid, data->mPrio,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700480 true /*asynchronous*/);
481 if (err != 0) {
482 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700483 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700484 }
485 } break;
486 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700487 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent021cf962014-05-13 10:18:14 -0700488 audioConfigChanged(data->mEvent, data->mParam);
Eric Laurent10351942014-05-08 18:49:52 -0700489 } break;
490 case CFG_EVENT_SET_PARAMETER: {
491 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
492 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
493 configChanged = true;
Glenn Kastend5418eb2013-08-14 13:11:06 -0700494 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700495 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700496 case CFG_EVENT_CREATE_AUDIO_PATCH: {
497 CreateAudioPatchConfigEventData *data =
498 (CreateAudioPatchConfigEventData *)event->mData.get();
499 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
500 } break;
501 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
502 ReleaseAudioPatchConfigEventData *data =
503 (ReleaseAudioPatchConfigEventData *)event->mData.get();
504 event->mStatus = releaseAudioPatch_l(data->mHandle);
505 } break;
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700506 default:
Eric Laurent10351942014-05-08 18:49:52 -0700507 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700508 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800509 }
Eric Laurent10351942014-05-08 18:49:52 -0700510 {
511 Mutex::Autolock _l(event->mLock);
512 if (event->mWaitStatus) {
513 event->mWaitStatus = false;
514 event->mCond.signal();
515 }
516 }
517 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
518 }
519
520 if (configChanged) {
521 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800522 }
Eric Laurent81784c32012-11-19 14:55:58 -0800523}
524
Marco Nelissenb2208842014-02-07 14:00:50 -0800525String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
526 String8 s;
527 if (output) {
528 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
529 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
530 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
531 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
532 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
533 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
534 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
535 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
536 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
537 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
538 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
539 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
540 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
541 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
542 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
543 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
544 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
545 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
546 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
547 } else {
548 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
549 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
550 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
551 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
552 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
553 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
554 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
555 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
556 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
557 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
558 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
559 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
560 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
561 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
562 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
563 }
564 int len = s.length();
565 if (s.length() > 2) {
566 char *str = s.lockBuffer(len);
567 s.unlockBuffer(len - 2);
568 }
569 return s;
570}
571
Glenn Kasten0f11b512014-01-31 16:18:54 -0800572void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800573{
574 const size_t SIZE = 256;
575 char buffer[SIZE];
576 String8 result;
577
578 bool locked = AudioFlinger::dumpTryLock(mLock);
579 if (!locked) {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700580 dprintf(fd, "thread %p maybe dead locked\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -0800581 }
582
Elliott Hughes87cebad2014-05-22 10:14:43 -0700583 dprintf(fd, " I/O handle: %d\n", mId);
584 dprintf(fd, " TID: %d\n", getTid());
585 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
586 dprintf(fd, " Sample rate: %u\n", mSampleRate);
587 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
588 dprintf(fd, " HAL buffer size: %u bytes\n", mBufferSize);
589 dprintf(fd, " Channel Count: %u\n", mChannelCount);
590 dprintf(fd, " Channel Mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800591 channelMaskToString(mChannelMask, mType != RECORD).string());
Andy Hung463be252014-07-10 16:56:07 -0700592 dprintf(fd, " Format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat));
Elliott Hughes87cebad2014-05-22 10:14:43 -0700593 dprintf(fd, " Frame size: %zu\n", mFrameSize);
594 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800595 size_t numConfig = mConfigEvents.size();
596 if (numConfig) {
597 for (size_t i = 0; i < numConfig; i++) {
598 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700599 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800600 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700601 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800602 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700603 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800604 }
Eric Laurent81784c32012-11-19 14:55:58 -0800605
606 if (locked) {
607 mLock.unlock();
608 }
609}
610
611void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
612{
613 const size_t SIZE = 256;
614 char buffer[SIZE];
615 String8 result;
616
Marco Nelissenb2208842014-02-07 14:00:50 -0800617 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000618 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800619 write(fd, buffer, strlen(buffer));
620
Marco Nelissenb2208842014-02-07 14:00:50 -0800621 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800622 sp<EffectChain> chain = mEffectChains[i];
623 if (chain != 0) {
624 chain->dump(fd, args);
625 }
626 }
627}
628
Marco Nelissene14a5d62013-10-03 08:51:24 -0700629void AudioFlinger::ThreadBase::acquireWakeLock(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800630{
631 Mutex::Autolock _l(mLock);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700632 acquireWakeLock_l(uid);
Eric Laurent81784c32012-11-19 14:55:58 -0800633}
634
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100635String16 AudioFlinger::ThreadBase::getWakeLockTag()
636{
637 switch (mType) {
638 case MIXER:
639 return String16("AudioMix");
640 case DIRECT:
641 return String16("AudioDirectOut");
642 case DUPLICATING:
643 return String16("AudioDup");
644 case RECORD:
645 return String16("AudioIn");
646 case OFFLOAD:
647 return String16("AudioOffload");
648 default:
649 ALOG_ASSERT(false);
650 return String16("AudioUnknown");
651 }
652}
653
Marco Nelissene14a5d62013-10-03 08:51:24 -0700654void AudioFlinger::ThreadBase::acquireWakeLock_l(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800655{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800656 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800657 if (mPowerManager != 0) {
658 sp<IBinder> binder = new BBinder();
Marco Nelissene14a5d62013-10-03 08:51:24 -0700659 status_t status;
660 if (uid >= 0) {
Eric Laurent547789d2013-10-04 11:46:55 -0700661 status = mPowerManager->acquireWakeLockWithUid(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700662 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100663 getWakeLockTag(),
Marco Nelissene14a5d62013-10-03 08:51:24 -0700664 String16("media"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700665 uid,
666 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700667 } else {
Eric Laurent547789d2013-10-04 11:46:55 -0700668 status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700669 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100670 getWakeLockTag(),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700671 String16("media"),
672 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700673 }
Eric Laurent81784c32012-11-19 14:55:58 -0800674 if (status == NO_ERROR) {
675 mWakeLockToken = binder;
676 }
677 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
678 }
679}
680
681void AudioFlinger::ThreadBase::releaseWakeLock()
682{
683 Mutex::Autolock _l(mLock);
684 releaseWakeLock_l();
685}
686
687void AudioFlinger::ThreadBase::releaseWakeLock_l()
688{
689 if (mWakeLockToken != 0) {
690 ALOGV("releaseWakeLock_l() %s", mName);
691 if (mPowerManager != 0) {
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700692 mPowerManager->releaseWakeLock(mWakeLockToken, 0,
693 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800694 }
695 mWakeLockToken.clear();
696 }
697}
698
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800699void AudioFlinger::ThreadBase::updateWakeLockUids(const SortedVector<int> &uids) {
700 Mutex::Autolock _l(mLock);
701 updateWakeLockUids_l(uids);
702}
703
704void AudioFlinger::ThreadBase::getPowerManager_l() {
705
706 if (mPowerManager == 0) {
707 // use checkService() to avoid blocking if power service is not up yet
708 sp<IBinder> binder =
709 defaultServiceManager()->checkService(String16("power"));
710 if (binder == 0) {
711 ALOGW("Thread %s cannot connect to the power manager service", mName);
712 } else {
713 mPowerManager = interface_cast<IPowerManager>(binder);
714 binder->linkToDeath(mDeathRecipient);
715 }
716 }
717}
718
719void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<int> &uids) {
720
721 getPowerManager_l();
722 if (mWakeLockToken == NULL) {
723 ALOGE("no wake lock to update!");
724 return;
725 }
726 if (mPowerManager != 0) {
727 sp<IBinder> binder = new BBinder();
728 status_t status;
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700729 status = mPowerManager->updateWakeLockUids(mWakeLockToken, uids.size(), uids.array(),
730 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800731 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
732 }
733}
734
Eric Laurent81784c32012-11-19 14:55:58 -0800735void AudioFlinger::ThreadBase::clearPowerManager()
736{
737 Mutex::Autolock _l(mLock);
738 releaseWakeLock_l();
739 mPowerManager.clear();
740}
741
Glenn Kasten0f11b512014-01-31 16:18:54 -0800742void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800743{
744 sp<ThreadBase> thread = mThread.promote();
745 if (thread != 0) {
746 thread->clearPowerManager();
747 }
748 ALOGW("power manager service died !!!");
749}
750
751void AudioFlinger::ThreadBase::setEffectSuspended(
752 const effect_uuid_t *type, bool suspend, int sessionId)
753{
754 Mutex::Autolock _l(mLock);
755 setEffectSuspended_l(type, suspend, sessionId);
756}
757
758void AudioFlinger::ThreadBase::setEffectSuspended_l(
759 const effect_uuid_t *type, bool suspend, int sessionId)
760{
761 sp<EffectChain> chain = getEffectChain_l(sessionId);
762 if (chain != 0) {
763 if (type != NULL) {
764 chain->setEffectSuspended_l(type, suspend);
765 } else {
766 chain->setEffectSuspendedAll_l(suspend);
767 }
768 }
769
770 updateSuspendedSessions_l(type, suspend, sessionId);
771}
772
773void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
774{
775 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
776 if (index < 0) {
777 return;
778 }
779
780 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
781 mSuspendedSessions.valueAt(index);
782
783 for (size_t i = 0; i < sessionEffects.size(); i++) {
784 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
785 for (int j = 0; j < desc->mRefCount; j++) {
786 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
787 chain->setEffectSuspendedAll_l(true);
788 } else {
789 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
790 desc->mType.timeLow);
791 chain->setEffectSuspended_l(&desc->mType, true);
792 }
793 }
794 }
795}
796
797void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
798 bool suspend,
799 int sessionId)
800{
801 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
802
803 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
804
805 if (suspend) {
806 if (index >= 0) {
807 sessionEffects = mSuspendedSessions.valueAt(index);
808 } else {
809 mSuspendedSessions.add(sessionId, sessionEffects);
810 }
811 } else {
812 if (index < 0) {
813 return;
814 }
815 sessionEffects = mSuspendedSessions.valueAt(index);
816 }
817
818
819 int key = EffectChain::kKeyForSuspendAll;
820 if (type != NULL) {
821 key = type->timeLow;
822 }
823 index = sessionEffects.indexOfKey(key);
824
825 sp<SuspendedSessionDesc> desc;
826 if (suspend) {
827 if (index >= 0) {
828 desc = sessionEffects.valueAt(index);
829 } else {
830 desc = new SuspendedSessionDesc();
831 if (type != NULL) {
832 desc->mType = *type;
833 }
834 sessionEffects.add(key, desc);
835 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
836 }
837 desc->mRefCount++;
838 } else {
839 if (index < 0) {
840 return;
841 }
842 desc = sessionEffects.valueAt(index);
843 if (--desc->mRefCount == 0) {
844 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
845 sessionEffects.removeItemsAt(index);
846 if (sessionEffects.isEmpty()) {
847 ALOGV("updateSuspendedSessions_l() restore removing session %d",
848 sessionId);
849 mSuspendedSessions.removeItem(sessionId);
850 }
851 }
852 }
853 if (!sessionEffects.isEmpty()) {
854 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
855 }
856}
857
858void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
859 bool enabled,
860 int sessionId)
861{
862 Mutex::Autolock _l(mLock);
863 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
864}
865
866void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
867 bool enabled,
868 int sessionId)
869{
870 if (mType != RECORD) {
871 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
872 // another session. This gives the priority to well behaved effect control panels
873 // and applications not using global effects.
874 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
875 // global effects
876 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
877 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
878 }
879 }
880
881 sp<EffectChain> chain = getEffectChain_l(sessionId);
882 if (chain != 0) {
883 chain->checkSuspendOnEffectEnabled(effect, enabled);
884 }
885}
886
887// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
888sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
889 const sp<AudioFlinger::Client>& client,
890 const sp<IEffectClient>& effectClient,
891 int32_t priority,
892 int sessionId,
893 effect_descriptor_t *desc,
894 int *enabled,
Glenn Kasten9156ef32013-08-06 15:39:08 -0700895 status_t *status)
Eric Laurent81784c32012-11-19 14:55:58 -0800896{
897 sp<EffectModule> effect;
898 sp<EffectHandle> handle;
899 status_t lStatus;
900 sp<EffectChain> chain;
901 bool chainCreated = false;
902 bool effectCreated = false;
903 bool effectRegistered = false;
904
905 lStatus = initCheck();
906 if (lStatus != NO_ERROR) {
907 ALOGW("createEffect_l() Audio driver not initialized.");
908 goto Exit;
909 }
910
Andy Hung98ef9782014-03-04 14:46:50 -0800911 // Reject any effect on Direct output threads for now, since the format of
912 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
913 if (mType == DIRECT) {
914 ALOGW("createEffect_l() Cannot add effect %s on Direct output type thread %s",
915 desc->name, mName);
916 lStatus = BAD_VALUE;
917 goto Exit;
918 }
919
Andy Hung389cfdb2014-08-07 17:49:53 -0700920 // Reject any effect on mixer or duplicating multichannel sinks.
Andy Hung9a592762014-07-21 21:56:01 -0700921 // TODO: fix both format and multichannel issues with effects.
Andy Hung389cfdb2014-08-07 17:49:53 -0700922 if ((mType == MIXER || mType == DUPLICATING) && mChannelCount != FCC_2) {
923 ALOGW("createEffect_l() Cannot add effect %s for multichannel(%d) %s threads",
924 desc->name, mChannelCount, mType == MIXER ? "MIXER" : "DUPLICATING");
Andy Hung9a592762014-07-21 21:56:01 -0700925 lStatus = BAD_VALUE;
926 goto Exit;
927 }
928
Eric Laurent5baf2af2013-09-12 17:37:00 -0700929 // Allow global effects only on offloaded and mixer threads
930 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
931 switch (mType) {
932 case MIXER:
933 case OFFLOAD:
934 break;
935 case DIRECT:
936 case DUPLICATING:
937 case RECORD:
938 default:
939 ALOGW("createEffect_l() Cannot add global effect %s on thread %s", desc->name, mName);
940 lStatus = BAD_VALUE;
941 goto Exit;
942 }
Eric Laurent81784c32012-11-19 14:55:58 -0800943 }
Eric Laurent5baf2af2013-09-12 17:37:00 -0700944
Eric Laurent81784c32012-11-19 14:55:58 -0800945 // Only Pre processor effects are allowed on input threads and only on input threads
946 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
947 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
948 desc->name, desc->flags, mType);
949 lStatus = BAD_VALUE;
950 goto Exit;
951 }
952
953 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
954
955 { // scope for mLock
956 Mutex::Autolock _l(mLock);
957
958 // check for existing effect chain with the requested audio session
959 chain = getEffectChain_l(sessionId);
960 if (chain == 0) {
961 // create a new chain for this session
962 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
963 chain = new EffectChain(this, sessionId);
964 addEffectChain_l(chain);
965 chain->setStrategy(getStrategyForSession_l(sessionId));
966 chainCreated = true;
967 } else {
968 effect = chain->getEffectFromDesc_l(desc);
969 }
970
971 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
972
973 if (effect == 0) {
974 int id = mAudioFlinger->nextUniqueId();
975 // Check CPU and memory usage
976 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
977 if (lStatus != NO_ERROR) {
978 goto Exit;
979 }
980 effectRegistered = true;
981 // create a new effect module if none present in the chain
982 effect = new EffectModule(this, chain, desc, id, sessionId);
983 lStatus = effect->status();
984 if (lStatus != NO_ERROR) {
985 goto Exit;
986 }
Eric Laurent5baf2af2013-09-12 17:37:00 -0700987 effect->setOffloaded(mType == OFFLOAD, mId);
988
Eric Laurent81784c32012-11-19 14:55:58 -0800989 lStatus = chain->addEffect_l(effect);
990 if (lStatus != NO_ERROR) {
991 goto Exit;
992 }
993 effectCreated = true;
994
995 effect->setDevice(mOutDevice);
996 effect->setDevice(mInDevice);
997 effect->setMode(mAudioFlinger->getMode());
998 effect->setAudioSource(mAudioSource);
999 }
1000 // create effect handle and connect it to effect module
1001 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001002 lStatus = handle->initCheck();
1003 if (lStatus == OK) {
1004 lStatus = effect->addHandle(handle.get());
1005 }
Eric Laurent81784c32012-11-19 14:55:58 -08001006 if (enabled != NULL) {
1007 *enabled = (int)effect->isEnabled();
1008 }
1009 }
1010
1011Exit:
1012 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1013 Mutex::Autolock _l(mLock);
1014 if (effectCreated) {
1015 chain->removeEffect_l(effect);
1016 }
1017 if (effectRegistered) {
1018 AudioSystem::unregisterEffect(effect->id());
1019 }
1020 if (chainCreated) {
1021 removeEffectChain_l(chain);
1022 }
1023 handle.clear();
1024 }
1025
Glenn Kasten9156ef32013-08-06 15:39:08 -07001026 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001027 return handle;
1028}
1029
1030sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
1031{
1032 Mutex::Autolock _l(mLock);
1033 return getEffect_l(sessionId, effectId);
1034}
1035
1036sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
1037{
1038 sp<EffectChain> chain = getEffectChain_l(sessionId);
1039 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1040}
1041
1042// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1043// PlaybackThread::mLock held
1044status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1045{
1046 // check for existing effect chain with the requested audio session
1047 int sessionId = effect->sessionId();
1048 sp<EffectChain> chain = getEffectChain_l(sessionId);
1049 bool chainCreated = false;
1050
Eric Laurent5baf2af2013-09-12 17:37:00 -07001051 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
1052 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
1053 this, effect->desc().name, effect->desc().flags);
1054
Eric Laurent81784c32012-11-19 14:55:58 -08001055 if (chain == 0) {
1056 // create a new chain for this session
1057 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1058 chain = new EffectChain(this, sessionId);
1059 addEffectChain_l(chain);
1060 chain->setStrategy(getStrategyForSession_l(sessionId));
1061 chainCreated = true;
1062 }
1063 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1064
1065 if (chain->getEffectFromId_l(effect->id()) != 0) {
1066 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1067 this, effect->desc().name, chain.get());
1068 return BAD_VALUE;
1069 }
1070
Eric Laurent5baf2af2013-09-12 17:37:00 -07001071 effect->setOffloaded(mType == OFFLOAD, mId);
1072
Eric Laurent81784c32012-11-19 14:55:58 -08001073 status_t status = chain->addEffect_l(effect);
1074 if (status != NO_ERROR) {
1075 if (chainCreated) {
1076 removeEffectChain_l(chain);
1077 }
1078 return status;
1079 }
1080
1081 effect->setDevice(mOutDevice);
1082 effect->setDevice(mInDevice);
1083 effect->setMode(mAudioFlinger->getMode());
1084 effect->setAudioSource(mAudioSource);
1085 return NO_ERROR;
1086}
1087
1088void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
1089
1090 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
1091 effect_descriptor_t desc = effect->desc();
1092 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1093 detachAuxEffect_l(effect->id());
1094 }
1095
1096 sp<EffectChain> chain = effect->chain().promote();
1097 if (chain != 0) {
1098 // remove effect chain if removing last effect
1099 if (chain->removeEffect_l(effect) == 0) {
1100 removeEffectChain_l(chain);
1101 }
1102 } else {
1103 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1104 }
1105}
1106
1107void AudioFlinger::ThreadBase::lockEffectChains_l(
1108 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1109{
1110 effectChains = mEffectChains;
1111 for (size_t i = 0; i < mEffectChains.size(); i++) {
1112 mEffectChains[i]->lock();
1113 }
1114}
1115
1116void AudioFlinger::ThreadBase::unlockEffectChains(
1117 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1118{
1119 for (size_t i = 0; i < effectChains.size(); i++) {
1120 effectChains[i]->unlock();
1121 }
1122}
1123
1124sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
1125{
1126 Mutex::Autolock _l(mLock);
1127 return getEffectChain_l(sessionId);
1128}
1129
1130sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const
1131{
1132 size_t size = mEffectChains.size();
1133 for (size_t i = 0; i < size; i++) {
1134 if (mEffectChains[i]->sessionId() == sessionId) {
1135 return mEffectChains[i];
1136 }
1137 }
1138 return 0;
1139}
1140
1141void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1142{
1143 Mutex::Autolock _l(mLock);
1144 size_t size = mEffectChains.size();
1145 for (size_t i = 0; i < size; i++) {
1146 mEffectChains[i]->setMode_l(mode);
1147 }
1148}
1149
Eric Laurent83b88082014-06-20 18:31:16 -07001150void AudioFlinger::ThreadBase::getAudioPortConfig(struct audio_port_config *config)
1151{
1152 config->type = AUDIO_PORT_TYPE_MIX;
1153 config->ext.mix.handle = mId;
1154 config->sample_rate = mSampleRate;
1155 config->format = mFormat;
1156 config->channel_mask = mChannelMask;
1157 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1158 AUDIO_PORT_CONFIG_FORMAT;
1159}
1160
1161
Eric Laurent81784c32012-11-19 14:55:58 -08001162// ----------------------------------------------------------------------------
1163// Playback
1164// ----------------------------------------------------------------------------
1165
1166AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1167 AudioStreamOut* output,
1168 audio_io_handle_t id,
1169 audio_devices_t device,
1170 type_t type)
1171 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type),
Andy Hung2098f272014-02-27 14:00:06 -08001172 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001173 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001174 mMixerBuffer(NULL),
1175 mMixerBufferSize(0),
1176 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1177 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001178 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001179 mEffectBuffer(NULL),
1180 mEffectBufferSize(0),
1181 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1182 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001183 mSuspended(0), mBytesWritten(0),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001184 mActiveTracksGeneration(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001185 // mStreamTypes[] initialized in constructor body
1186 mOutput(output),
1187 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
1188 mMixerStatus(MIXER_IDLE),
1189 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
1190 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001191 mBytesRemaining(0),
1192 mCurrentWriteLength(0),
1193 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001194 mWriteAckSequence(0),
1195 mDrainSequence(0),
Eric Laurentede6c3b2013-09-19 14:37:46 -07001196 mSignalPending(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001197 mScreenState(AudioFlinger::mScreenState),
1198 // index 0 is reserved for normal mixer's submix
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001199 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1),
1200 // mLatchD, mLatchQ,
1201 mLatchDValid(false), mLatchQValid(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001202{
1203 snprintf(mName, kNameLength, "AudioOut_%X", id);
Glenn Kasten9e58b552013-01-18 15:09:48 -08001204 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mName);
Eric Laurent81784c32012-11-19 14:55:58 -08001205
1206 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1207 // it would be safer to explicitly pass initial masterVolume/masterMute as
1208 // parameter.
1209 //
1210 // If the HAL we are using has support for master volume or master mute,
1211 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1212 // and the mute set to false).
1213 mMasterVolume = audioFlinger->masterVolume_l();
1214 mMasterMute = audioFlinger->masterMute_l();
1215 if (mOutput && mOutput->audioHwDev) {
1216 if (mOutput->audioHwDev->canSetMasterVolume()) {
1217 mMasterVolume = 1.0;
1218 }
1219
1220 if (mOutput->audioHwDev->canSetMasterMute()) {
1221 mMasterMute = false;
1222 }
1223 }
1224
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001225 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001226
1227 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
1228 // There is no AUDIO_STREAM_MIN, and ++ 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 }
1234 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1235 // because mAudioFlinger doesn't have one to copy from
1236}
1237
1238AudioFlinger::PlaybackThread::~PlaybackThread()
1239{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001240 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001241 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001242 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001243 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001244}
1245
1246void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1247{
1248 dumpInternals(fd, args);
1249 dumpTracks(fd, args);
1250 dumpEffectChains(fd, args);
1251}
1252
Glenn Kasten0f11b512014-01-31 16:18:54 -08001253void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001254{
1255 const size_t SIZE = 256;
1256 char buffer[SIZE];
1257 String8 result;
1258
Marco Nelissenb2208842014-02-07 14:00:50 -08001259 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001260 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1261 const stream_type_t *st = &mStreamTypes[i];
1262 if (i > 0) {
1263 result.appendFormat(", ");
1264 }
1265 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1266 if (st->mute) {
1267 result.append("M");
1268 }
1269 }
1270 result.append("\n");
1271 write(fd, result.string(), result.length());
1272 result.clear();
1273
Eric Laurent81784c32012-11-19 14:55:58 -08001274 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1275 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001276 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001277 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001278
1279 size_t numtracks = mTracks.size();
1280 size_t numactive = mActiveTracks.size();
Elliott Hughes87cebad2014-05-22 10:14:43 -07001281 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001282 size_t numactiveseen = 0;
1283 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07001284 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08001285 Track::appendDumpHeader(result);
1286 for (size_t i = 0; i < numtracks; ++i) {
1287 sp<Track> track = mTracks[i];
1288 if (track != 0) {
1289 bool active = mActiveTracks.indexOf(track) >= 0;
1290 if (active) {
1291 numactiveseen++;
1292 }
1293 track->dump(buffer, SIZE, active);
1294 result.append(buffer);
1295 }
1296 }
1297 } else {
1298 result.append("\n");
1299 }
1300 if (numactiveseen != numactive) {
1301 // some tracks in the active list were not in the tracks list
1302 snprintf(buffer, SIZE, " The following tracks are in the active list but"
1303 " not in the track list\n");
1304 result.append(buffer);
1305 Track::appendDumpHeader(result);
1306 for (size_t i = 0; i < numactive; ++i) {
1307 sp<Track> track = mActiveTracks[i].promote();
1308 if (track != 0 && mTracks.indexOf(track) < 0) {
1309 track->dump(buffer, SIZE, true);
1310 result.append(buffer);
1311 }
1312 }
1313 }
1314
1315 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001316}
1317
1318void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1319{
Elliott Hughes87cebad2014-05-22 10:14:43 -07001320 dprintf(fd, "\nOutput thread %p:\n", this);
1321 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
1322 dprintf(fd, " Last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1323 dprintf(fd, " Total writes: %d\n", mNumWrites);
1324 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1325 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1326 dprintf(fd, " Suspend count: %d\n", mSuspended);
1327 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1328 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1329 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1330 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent81784c32012-11-19 14:55:58 -08001331
1332 dumpBase(fd, args);
1333}
1334
1335// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001336
1337void AudioFlinger::PlaybackThread::onFirstRef()
1338{
1339 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
1340}
1341
1342// ThreadBase virtuals
1343void AudioFlinger::PlaybackThread::preExit()
1344{
1345 ALOGV(" preExit()");
1346 // FIXME this is using hard-coded strings but in the future, this functionality will be
1347 // converted to use audio HAL extensions required to support tunneling
1348 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1349}
1350
1351// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1352sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1353 const sp<AudioFlinger::Client>& client,
1354 audio_stream_type_t streamType,
1355 uint32_t sampleRate,
1356 audio_format_t format,
1357 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001358 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001359 const sp<IMemory>& sharedBuffer,
1360 int sessionId,
1361 IAudioFlinger::track_flags_t *flags,
1362 pid_t tid,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001363 int uid,
Eric Laurent81784c32012-11-19 14:55:58 -08001364 status_t *status)
1365{
Glenn Kasten74935e42013-12-19 08:56:45 -08001366 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001367 sp<Track> track;
1368 status_t lStatus;
1369
1370 bool isTimed = (*flags & IAudioFlinger::TRACK_TIMED) != 0;
1371
1372 // client expresses a preference for FAST, but we get the final say
1373 if (*flags & IAudioFlinger::TRACK_FAST) {
1374 if (
1375 // not timed
1376 (!isTimed) &&
1377 // either of these use cases:
1378 (
1379 // use case 1: shared buffer with any frame count
1380 (
1381 (sharedBuffer != 0)
1382 ) ||
1383 // use case 2: callback handler and frame count is default or at least as large as HAL
1384 (
1385 (tid != -1) &&
1386 ((frameCount == 0) ||
Glenn Kastenb5fed682013-12-03 09:06:43 -08001387 (frameCount >= mFrameCount))
Eric Laurent81784c32012-11-19 14:55:58 -08001388 )
1389 ) &&
1390 // PCM data
1391 audio_is_linear_pcm(format) &&
Andy Hung9a592762014-07-21 21:56:01 -07001392 // identical channel mask to sink, or mono in and stereo sink
1393 (channelMask == mChannelMask ||
1394 (channelMask == AUDIO_CHANNEL_OUT_MONO &&
1395 mChannelMask == AUDIO_CHANNEL_OUT_STEREO)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001396 // hardware sample rate
1397 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001398 // normal mixer has an associated fast mixer
1399 hasFastMixer() &&
1400 // there are sufficient fast track slots available
1401 (mFastTrackAvailMask != 0)
1402 // FIXME test that MixerThread for this fast track has a capable output HAL
1403 // FIXME add a permission test also?
1404 ) {
1405 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1406 if (frameCount == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001407 // read the fast track multiplier property the first time it is needed
1408 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1409 if (ok != 0) {
1410 ALOGE("%s pthread_once failed: %d", __func__, ok);
1411 }
1412 frameCount = mFrameCount * sFastTrackMultiplier;
Eric Laurent81784c32012-11-19 14:55:58 -08001413 }
1414 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
1415 frameCount, mFrameCount);
1416 } else {
1417 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
Andy Hung6146c082014-03-18 11:56:15 -07001418 "mFrameCount=%d format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
1419 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001420 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Andy Hung6146c082014-03-18 11:56:15 -07001421 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001422 audio_is_linear_pcm(format),
1423 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
1424 *flags &= ~IAudioFlinger::TRACK_FAST;
1425 // For compatibility with AudioTrack calculation, buffer depth is forced
1426 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1427 // This is probably too conservative, but legacy application code may depend on it.
1428 // If you change this calculation, also review the start threshold which is related.
1429 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1430 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1431 if (minBufCount < 2) {
1432 minBufCount = 2;
1433 }
1434 size_t minFrameCount = mNormalFrameCount * minBufCount;
1435 if (frameCount < minFrameCount) {
1436 frameCount = minFrameCount;
1437 }
1438 }
1439 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001440 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001441
Glenn Kastenc3df8382014-03-13 15:05:25 -07001442 switch (mType) {
1443
1444 case DIRECT:
Glenn Kasten993fa062014-05-02 11:14:34 -07001445 if (audio_is_linear_pcm(format)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001446 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001447 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1448 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001449 sampleRate, format, channelMask, mOutput, mFormat);
1450 lStatus = BAD_VALUE;
1451 goto Exit;
1452 }
1453 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001454 break;
1455
1456 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001457 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001458 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1459 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001460 sampleRate, format, channelMask, mOutput, mFormat);
1461 lStatus = BAD_VALUE;
1462 goto Exit;
1463 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001464 break;
1465
1466 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07001467 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001468 ALOGE("createTrack_l() Bad parameter: format %#x \""
1469 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001470 format, mOutput, mFormat);
1471 lStatus = BAD_VALUE;
1472 goto Exit;
1473 }
Andy Hungcd044842014-08-07 11:04:34 -07001474 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08001475 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1476 lStatus = BAD_VALUE;
1477 goto Exit;
1478 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001479 break;
1480
Eric Laurent81784c32012-11-19 14:55:58 -08001481 }
1482
1483 lStatus = initCheck();
1484 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07001485 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08001486 goto Exit;
1487 }
1488
1489 { // scope for mLock
1490 Mutex::Autolock _l(mLock);
1491
1492 // all tracks in same audio session must share the same routing strategy otherwise
1493 // conflicts will happen when tracks are moved from one output to another by audio policy
1494 // manager
1495 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1496 for (size_t i = 0; i < mTracks.size(); ++i) {
1497 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07001498 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001499 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1500 if (sessionId == t->sessionId() && strategy != actual) {
1501 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1502 strategy, actual);
1503 lStatus = BAD_VALUE;
1504 goto Exit;
1505 }
1506 }
1507 }
1508
1509 if (!isTimed) {
1510 track = new Track(this, client, streamType, sampleRate, format,
Eric Laurent83b88082014-06-20 18:31:16 -07001511 channelMask, frameCount, NULL, sharedBuffer,
1512 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08001513 } else {
1514 track = TimedTrack::create(this, client, streamType, sampleRate, format,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001515 channelMask, frameCount, sharedBuffer, sessionId, uid);
Eric Laurent81784c32012-11-19 14:55:58 -08001516 }
Glenn Kasten03003332013-08-06 15:40:54 -07001517
1518 // new Track always returns non-NULL,
1519 // but TimedTrack::create() is a factory that could fail by returning NULL
1520 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
1521 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08001522 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001523 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08001524 goto Exit;
1525 }
1526 mTracks.add(track);
1527
1528 sp<EffectChain> chain = getEffectChain_l(sessionId);
1529 if (chain != 0) {
1530 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1531 track->setMainBuffer(chain->inBuffer());
1532 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1533 chain->incTrackCnt();
1534 }
1535
1536 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1537 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1538 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1539 // so ask activity manager to do this on our behalf
1540 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1541 }
1542 }
1543
1544 lStatus = NO_ERROR;
1545
1546Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001547 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001548 return track;
1549}
1550
1551uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1552{
1553 return latency;
1554}
1555
1556uint32_t AudioFlinger::PlaybackThread::latency() const
1557{
1558 Mutex::Autolock _l(mLock);
1559 return latency_l();
1560}
1561uint32_t AudioFlinger::PlaybackThread::latency_l() const
1562{
1563 if (initCheck() == NO_ERROR) {
1564 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
1565 } else {
1566 return 0;
1567 }
1568}
1569
1570void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1571{
1572 Mutex::Autolock _l(mLock);
1573 // Don't apply master volume in SW if our HAL can do it for us.
1574 if (mOutput && mOutput->audioHwDev &&
1575 mOutput->audioHwDev->canSetMasterVolume()) {
1576 mMasterVolume = 1.0;
1577 } else {
1578 mMasterVolume = value;
1579 }
1580}
1581
1582void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1583{
1584 Mutex::Autolock _l(mLock);
1585 // Don't apply master mute in SW if our HAL can do it for us.
1586 if (mOutput && mOutput->audioHwDev &&
1587 mOutput->audioHwDev->canSetMasterMute()) {
1588 mMasterMute = false;
1589 } else {
1590 mMasterMute = muted;
1591 }
1592}
1593
1594void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
1595{
1596 Mutex::Autolock _l(mLock);
1597 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001598 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001599}
1600
1601void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
1602{
1603 Mutex::Autolock _l(mLock);
1604 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001605 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001606}
1607
1608float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
1609{
1610 Mutex::Autolock _l(mLock);
1611 return mStreamTypes[stream].volume;
1612}
1613
1614// addTrack_l() must be called with ThreadBase::mLock held
1615status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1616{
1617 status_t status = ALREADY_EXISTS;
1618
1619 // set retry count for buffer fill
1620 track->mRetryCount = kMaxTrackStartupRetries;
1621 if (mActiveTracks.indexOf(track) < 0) {
1622 // the track is newly added, make sure it fills up all its
1623 // buffers before playing. This is to ensure the client will
1624 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07001625 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001626 TrackBase::track_state state = track->mState;
1627 mLock.unlock();
1628 status = AudioSystem::startOutput(mId, track->streamType(), track->sessionId());
1629 mLock.lock();
1630 // abort track was stopped/paused while we released the lock
1631 if (state != track->mState) {
1632 if (status == NO_ERROR) {
1633 mLock.unlock();
1634 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
1635 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
Andy Hung09a50072014-02-27 14:30:47 -08001851 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08001852 double multiplier = 1.0;
1853 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
1854 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08001855 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
1856 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Eric Laurent81784c32012-11-19 14:55:58 -08001857 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
1858 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
1859 maxNormalFrameCount = maxNormalFrameCount & ~15;
1860 if (maxNormalFrameCount < minNormalFrameCount) {
1861 maxNormalFrameCount = minNormalFrameCount;
1862 }
1863 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
1864 if (multiplier <= 1.0) {
1865 multiplier = 1.0;
1866 } else if (multiplier <= 2.0) {
1867 if (2 * mFrameCount <= maxNormalFrameCount) {
1868 multiplier = 2.0;
1869 } else {
1870 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
1871 }
1872 } else {
1873 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
Andy Hung09a50072014-02-27 14:30:47 -08001874 // 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 -08001875 // track, but we sometimes have to do this to satisfy the maximum frame count
1876 // constraint)
1877 // FIXME this rounding up should not be done if no HAL SRC
1878 uint32_t truncMult = (uint32_t) multiplier;
1879 if ((truncMult & 1)) {
1880 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
1881 ++truncMult;
1882 }
1883 }
1884 multiplier = (double) truncMult;
1885 }
1886 }
1887 mNormalFrameCount = multiplier * mFrameCount;
1888 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07001889 if (mType == MIXER || mType == DUPLICATING) {
1890 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
1891 }
Andy Hung09a50072014-02-27 14:30:47 -08001892 ALOGI("HAL output buffer size %u frames, normal sink buffer size %u frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001893 mNormalFrameCount);
1894
Andy Hung010a1a12014-03-13 13:57:33 -07001895 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
1896 // Originally this was int16_t[] array, need to remove legacy implications.
1897 free(mSinkBuffer);
1898 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07001899 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
1900 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
1901 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07001902 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08001903
Andy Hung69aed5f2014-02-25 17:24:40 -08001904 // We resize the mMixerBuffer according to the requirements of the sink buffer which
1905 // drives the output.
1906 free(mMixerBuffer);
1907 mMixerBuffer = NULL;
1908 if (mMixerBufferEnabled) {
1909 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
1910 mMixerBufferSize = mNormalFrameCount * mChannelCount
1911 * audio_bytes_per_sample(mMixerBufferFormat);
1912 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
1913 }
Andy Hung98ef9782014-03-04 14:46:50 -08001914 free(mEffectBuffer);
1915 mEffectBuffer = NULL;
1916 if (mEffectBufferEnabled) {
1917 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
1918 mEffectBufferSize = mNormalFrameCount * mChannelCount
1919 * audio_bytes_per_sample(mEffectBufferFormat);
1920 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
1921 }
Andy Hung69aed5f2014-02-25 17:24:40 -08001922
Eric Laurent81784c32012-11-19 14:55:58 -08001923 // force reconfiguration of effect chains and engines to take new buffer size and audio
1924 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001925 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08001926 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1927 // matter.
1928 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1929 Vector< sp<EffectChain> > effectChains = mEffectChains;
1930 for (size_t i = 0; i < effectChains.size(); i ++) {
1931 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
1932 }
1933}
1934
1935
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001936status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08001937{
1938 if (halFrames == NULL || dspFrames == NULL) {
1939 return BAD_VALUE;
1940 }
1941 Mutex::Autolock _l(mLock);
1942 if (initCheck() != NO_ERROR) {
1943 return INVALID_OPERATION;
1944 }
1945 size_t framesWritten = mBytesWritten / mFrameSize;
1946 *halFrames = framesWritten;
1947
1948 if (isSuspended()) {
1949 // return an estimation of rendered frames when the output is suspended
1950 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
1951 *dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0;
1952 return NO_ERROR;
1953 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001954 status_t status;
1955 uint32_t frames;
1956 status = mOutput->stream->get_render_position(mOutput->stream, &frames);
1957 *dspFrames = (size_t)frames;
1958 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08001959 }
1960}
1961
1962uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
1963{
1964 Mutex::Autolock _l(mLock);
1965 uint32_t result = 0;
1966 if (getEffectChain_l(sessionId) != 0) {
1967 result = EFFECT_SESSION;
1968 }
1969
1970 for (size_t i = 0; i < mTracks.size(); ++i) {
1971 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08001972 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001973 result |= TRACK_SESSION;
1974 break;
1975 }
1976 }
1977
1978 return result;
1979}
1980
1981uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1982{
1983 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
1984 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
1985 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1986 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
1987 }
1988 for (size_t i = 0; i < mTracks.size(); i++) {
1989 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08001990 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001991 return AudioSystem::getStrategyForStream(track->streamType());
1992 }
1993 }
1994 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
1995}
1996
1997
1998AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
1999{
2000 Mutex::Autolock _l(mLock);
2001 return mOutput;
2002}
2003
2004AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
2005{
2006 Mutex::Autolock _l(mLock);
2007 AudioStreamOut *output = mOutput;
2008 mOutput = NULL;
2009 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2010 // must push a NULL and wait for ack
2011 mOutputSink.clear();
2012 mPipeSink.clear();
2013 mNormalSink.clear();
2014 return output;
2015}
2016
2017// this method must always be called either with ThreadBase mLock held or inside the thread loop
2018audio_stream_t* AudioFlinger::PlaybackThread::stream() const
2019{
2020 if (mOutput == NULL) {
2021 return NULL;
2022 }
2023 return &mOutput->stream->common;
2024}
2025
2026uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2027{
2028 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2029}
2030
2031status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2032{
2033 if (!isValidSyncEvent(event)) {
2034 return BAD_VALUE;
2035 }
2036
2037 Mutex::Autolock _l(mLock);
2038
2039 for (size_t i = 0; i < mTracks.size(); ++i) {
2040 sp<Track> track = mTracks[i];
2041 if (event->triggerSession() == track->sessionId()) {
2042 (void) track->setSyncEvent(event);
2043 return NO_ERROR;
2044 }
2045 }
2046
2047 return NAME_NOT_FOUND;
2048}
2049
2050bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2051{
2052 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2053}
2054
2055void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2056 const Vector< sp<Track> >& tracksToRemove)
2057{
2058 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002059 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002060 for (size_t i = 0 ; i < count ; i++) {
2061 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002062 if (track->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002063 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002064#ifdef ADD_BATTERY_DATA
2065 // to track the speaker usage
2066 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2067#endif
2068 if (track->isTerminated()) {
2069 AudioSystem::releaseOutput(mId);
2070 }
Eric Laurent81784c32012-11-19 14:55:58 -08002071 }
2072 }
2073 }
Eric Laurent81784c32012-11-19 14:55:58 -08002074}
2075
2076void AudioFlinger::PlaybackThread::checkSilentMode_l()
2077{
2078 if (!mMasterMute) {
2079 char value[PROPERTY_VALUE_MAX];
2080 if (property_get("ro.audio.silent", value, "0") > 0) {
2081 char *endptr;
2082 unsigned long ul = strtoul(value, &endptr, 0);
2083 if (*endptr == '\0' && ul != 0) {
2084 ALOGD("Silence is golden");
2085 // The setprop command will not allow a property to be changed after
2086 // the first time it is set, so we don't have to worry about un-muting.
2087 setMasterMute_l(true);
2088 }
2089 }
2090 }
2091}
2092
2093// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002094ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002095{
2096 // FIXME rewrite to reduce number of system calls
2097 mLastWriteTime = systemTime();
2098 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002099 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002100 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002101
2102 // If an NBAIO sink is present, use it to write the normal mixer's submix
2103 if (mNormalSink != 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002104 const size_t count = mBytesRemaining / mFrameSize;
2105
Simon Wilson2d590962012-11-29 15:18:50 -08002106 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002107 // update the setpoint when AudioFlinger::mScreenState changes
2108 uint32_t screenState = AudioFlinger::mScreenState;
2109 if (screenState != mScreenState) {
2110 mScreenState = screenState;
2111 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2112 if (pipe != NULL) {
2113 pipe->setAvgFrames((mScreenState & 1) ?
2114 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2115 }
2116 }
Andy Hung010a1a12014-03-13 13:57:33 -07002117 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002118 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002119 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002120 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002121 } else {
2122 bytesWritten = framesWritten;
2123 }
Glenn Kastenefaa7ab2014-08-20 08:48:54 -07002124 mLatchDValid = false;
Glenn Kasten767094d2013-08-23 13:51:43 -07002125 status_t status = mNormalSink->getTimestamp(mLatchD.mTimestamp);
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002126 if (status == NO_ERROR) {
2127 size_t totalFramesWritten = mNormalSink->framesWritten();
2128 if (totalFramesWritten >= mLatchD.mTimestamp.mPosition) {
2129 mLatchD.mUnpresentedFrames = totalFramesWritten - mLatchD.mTimestamp.mPosition;
2130 mLatchDValid = true;
2131 }
2132 }
Eric Laurent81784c32012-11-19 14:55:58 -08002133 // otherwise use the HAL / AudioStreamOut directly
2134 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002135 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002136
Eric Laurentbfb1b832013-01-07 09:53:42 -08002137 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002138 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2139 mWriteAckSequence += 2;
2140 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002141 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002142 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002143 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002144 // FIXME We should have an implementation of timestamps for direct output threads.
2145 // They are used e.g for multichannel PCM playback over HDMI.
Eric Laurentbfb1b832013-01-07 09:53:42 -08002146 bytesWritten = mOutput->stream->write(mOutput->stream,
Andy Hung2098f272014-02-27 14:00:06 -08002147 (char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002148 if (mUseAsyncWrite &&
2149 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2150 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002151 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002152 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002153 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002154 }
Eric Laurent81784c32012-11-19 14:55:58 -08002155 }
2156
Eric Laurent81784c32012-11-19 14:55:58 -08002157 mNumWrites++;
2158 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002159 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002160 return bytesWritten;
2161}
2162
2163void AudioFlinger::PlaybackThread::threadLoop_drain()
2164{
2165 if (mOutput->stream->drain) {
2166 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2167 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002168 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2169 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002170 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002171 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002172 }
2173 mOutput->stream->drain(mOutput->stream,
2174 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
2175 : AUDIO_DRAIN_ALL);
2176 }
2177}
2178
2179void AudioFlinger::PlaybackThread::threadLoop_exit()
2180{
2181 // Default implementation has nothing to do
Eric Laurent81784c32012-11-19 14:55:58 -08002182}
2183
2184/*
2185The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002186 - mSinkBufferSize from frame count * frame size
Eric Laurent81784c32012-11-19 14:55:58 -08002187 - activeSleepTime from activeSleepTimeUs()
2188 - idleSleepTime from idleSleepTimeUs()
2189 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
2190 - maxPeriod from frame count and sample rate (MIXER only)
2191
2192The parameters that affect these derived values are:
2193 - frame count
2194 - frame size
2195 - sample rate
2196 - device type: A2DP or not
2197 - device latency
2198 - format: PCM or not
2199 - active sleep time
2200 - idle sleep time
2201*/
2202
2203void AudioFlinger::PlaybackThread::cacheParameters_l()
2204{
Andy Hung25c2dac2014-02-27 14:56:00 -08002205 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002206 activeSleepTime = activeSleepTimeUs();
2207 idleSleepTime = idleSleepTimeUs();
2208}
2209
2210void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2211{
Glenn Kasten7c027242012-12-26 14:43:16 -08002212 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurent81784c32012-11-19 14:55:58 -08002213 this, streamType, mTracks.size());
2214 Mutex::Autolock _l(mLock);
2215
2216 size_t size = mTracks.size();
2217 for (size_t i = 0; i < size; i++) {
2218 sp<Track> t = mTracks[i];
2219 if (t->streamType() == streamType) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002220 t->invalidate();
Eric Laurent81784c32012-11-19 14:55:58 -08002221 }
2222 }
2223}
2224
2225status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2226{
2227 int session = chain->sessionId();
Andy Hung010a1a12014-03-13 13:57:33 -07002228 int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled
2229 ? mEffectBuffer : mSinkBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002230 bool ownsBuffer = false;
2231
2232 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
2233 if (session > 0) {
2234 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002235 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002236 if (mType != DIRECT) {
2237 size_t numSamples = mNormalFrameCount * mChannelCount;
2238 buffer = new int16_t[numSamples];
2239 memset(buffer, 0, numSamples * sizeof(int16_t));
2240 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2241 ownsBuffer = true;
2242 }
2243
2244 // Attach all tracks with same session ID to this chain.
2245 for (size_t i = 0; i < mTracks.size(); ++i) {
2246 sp<Track> track = mTracks[i];
2247 if (session == track->sessionId()) {
2248 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2249 buffer);
2250 track->setMainBuffer(buffer);
2251 chain->incTrackCnt();
2252 }
2253 }
2254
2255 // indicate all active tracks in the chain
2256 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2257 sp<Track> track = mActiveTracks[i].promote();
2258 if (track == 0) {
2259 continue;
2260 }
2261 if (session == track->sessionId()) {
2262 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2263 chain->incActiveTrackCnt();
2264 }
2265 }
2266 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002267 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08002268 chain->setInBuffer(buffer, ownsBuffer);
Andy Hung010a1a12014-03-13 13:57:33 -07002269 chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled
2270 ? mEffectBuffer : mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002271 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
2272 // chains list in order to be processed last as it contains output stage effects
2273 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2274 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
2275 // after track specific effects and before output stage
2276 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
2277 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
2278 // Effect chain for other sessions are inserted at beginning of effect
2279 // chains list to be processed before output mix effects. Relative order between other
2280 // sessions is not important
2281 size_t size = mEffectChains.size();
2282 size_t i = 0;
2283 for (i = 0; i < size; i++) {
2284 if (mEffectChains[i]->sessionId() < session) {
2285 break;
2286 }
2287 }
2288 mEffectChains.insertAt(chain, i);
2289 checkSuspendOnAddEffectChain_l(chain);
2290
2291 return NO_ERROR;
2292}
2293
2294size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2295{
2296 int session = chain->sessionId();
2297
2298 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2299
2300 for (size_t i = 0; i < mEffectChains.size(); i++) {
2301 if (chain == mEffectChains[i]) {
2302 mEffectChains.removeAt(i);
2303 // detach all active tracks from the chain
2304 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2305 sp<Track> track = mActiveTracks[i].promote();
2306 if (track == 0) {
2307 continue;
2308 }
2309 if (session == track->sessionId()) {
2310 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2311 chain.get(), session);
2312 chain->decActiveTrackCnt();
2313 }
2314 }
2315
2316 // detach all tracks with same session ID from this chain
2317 for (size_t i = 0; i < mTracks.size(); ++i) {
2318 sp<Track> track = mTracks[i];
2319 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002320 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002321 chain->decTrackCnt();
2322 }
2323 }
2324 break;
2325 }
2326 }
2327 return mEffectChains.size();
2328}
2329
2330status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2331 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2332{
2333 Mutex::Autolock _l(mLock);
2334 return attachAuxEffect_l(track, EffectId);
2335}
2336
2337status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2338 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2339{
2340 status_t status = NO_ERROR;
2341
2342 if (EffectId == 0) {
2343 track->setAuxBuffer(0, NULL);
2344 } else {
2345 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2346 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2347 if (effect != 0) {
2348 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2349 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2350 } else {
2351 status = INVALID_OPERATION;
2352 }
2353 } else {
2354 status = BAD_VALUE;
2355 }
2356 }
2357 return status;
2358}
2359
2360void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2361{
2362 for (size_t i = 0; i < mTracks.size(); ++i) {
2363 sp<Track> track = mTracks[i];
2364 if (track->auxEffectId() == effectId) {
2365 attachAuxEffect_l(track, 0);
2366 }
2367 }
2368}
2369
2370bool AudioFlinger::PlaybackThread::threadLoop()
2371{
2372 Vector< sp<Track> > tracksToRemove;
2373
2374 standbyTime = systemTime();
2375
2376 // MIXER
2377 nsecs_t lastWarning = 0;
2378
2379 // DUPLICATING
2380 // FIXME could this be made local to while loop?
2381 writeFrames = 0;
2382
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002383 int lastGeneration = 0;
2384
Eric Laurent81784c32012-11-19 14:55:58 -08002385 cacheParameters_l();
2386 sleepTime = idleSleepTime;
2387
2388 if (mType == MIXER) {
2389 sleepTimeShift = 0;
2390 }
2391
2392 CpuStats cpuStats;
2393 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2394
2395 acquireWakeLock();
2396
Glenn Kasten9e58b552013-01-18 15:09:48 -08002397 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2398 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2399 // and then that string will be logged at the next convenient opportunity.
2400 const char *logString = NULL;
2401
Eric Laurent664539d2013-09-23 18:24:31 -07002402 checkSilentMode_l();
2403
Eric Laurent81784c32012-11-19 14:55:58 -08002404 while (!exitPending())
2405 {
2406 cpuStats.sample(myName);
2407
2408 Vector< sp<EffectChain> > effectChains;
2409
Eric Laurent81784c32012-11-19 14:55:58 -08002410 { // scope for mLock
2411
2412 Mutex::Autolock _l(mLock);
2413
Eric Laurent021cf962014-05-13 10:18:14 -07002414 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07002415
Glenn Kasten9e58b552013-01-18 15:09:48 -08002416 if (logString != NULL) {
2417 mNBLogWriter->logTimestamp();
2418 mNBLogWriter->log(logString);
2419 logString = NULL;
2420 }
2421
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002422 if (mLatchDValid) {
2423 mLatchQ = mLatchD;
2424 mLatchDValid = false;
2425 mLatchQValid = true;
2426 }
2427
Eric Laurent81784c32012-11-19 14:55:58 -08002428 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002429 if (mSignalPending) {
2430 // A signal was raised while we were unlocked
2431 mSignalPending = false;
2432 } else if (waitingAsyncCallback_l()) {
2433 if (exitPending()) {
2434 break;
2435 }
2436 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002437 mWakeLockUids.clear();
2438 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002439 ALOGV("wait async completion");
2440 mWaitWorkCV.wait(mLock);
2441 ALOGV("async completion/wake");
2442 acquireWakeLock_l();
Eric Laurent972a1732013-09-04 09:42:59 -07002443 standbyTime = systemTime() + standbyDelay;
2444 sleepTime = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002445
2446 continue;
2447 }
2448 if ((!mActiveTracks.size() && systemTime() > standbyTime) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08002449 isSuspended()) {
2450 // put audio hardware into standby after short delay
2451 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002452
2453 threadLoop_standby();
2454
2455 mStandby = true;
2456 }
2457
2458 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2459 // we're about to wait, flush the binder command buffer
2460 IPCThreadState::self()->flushCommands();
2461
2462 clearOutputTracks();
2463
2464 if (exitPending()) {
2465 break;
2466 }
2467
2468 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002469 mWakeLockUids.clear();
2470 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002471 // wait until we have something to do...
2472 ALOGV("%s going to sleep", myName.string());
2473 mWaitWorkCV.wait(mLock);
2474 ALOGV("%s waking up", myName.string());
2475 acquireWakeLock_l();
2476
2477 mMixerStatus = MIXER_IDLE;
2478 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2479 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002480 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002481 checkSilentMode_l();
2482
2483 standbyTime = systemTime() + standbyDelay;
2484 sleepTime = idleSleepTime;
2485 if (mType == MIXER) {
2486 sleepTimeShift = 0;
2487 }
2488
2489 continue;
2490 }
2491 }
Eric Laurent81784c32012-11-19 14:55:58 -08002492 // mMixerStatusIgnoringFastTracks is also updated internally
2493 mMixerStatus = prepareTracks_l(&tracksToRemove);
2494
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002495 // compare with previously applied list
2496 if (lastGeneration != mActiveTracksGeneration) {
2497 // update wakelock
2498 updateWakeLockUids_l(mWakeLockUids);
2499 lastGeneration = mActiveTracksGeneration;
2500 }
2501
Eric Laurent81784c32012-11-19 14:55:58 -08002502 // prevent any changes in effect chain list and in each effect chain
2503 // during mixing and effect process as the audio buffers could be deleted
2504 // or modified if an effect is created or deleted
2505 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002506 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08002507
Eric Laurentbfb1b832013-01-07 09:53:42 -08002508 if (mBytesRemaining == 0) {
2509 mCurrentWriteLength = 0;
2510 if (mMixerStatus == MIXER_TRACKS_READY) {
2511 // threadLoop_mix() sets mCurrentWriteLength
2512 threadLoop_mix();
2513 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
2514 && (mMixerStatus != MIXER_DRAIN_ALL)) {
2515 // threadLoop_sleepTime sets sleepTime to 0 if data
2516 // must be written to HAL
2517 threadLoop_sleepTime();
2518 if (sleepTime == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08002519 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002520 }
2521 }
Andy Hung98ef9782014-03-04 14:46:50 -08002522 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
2523 // mMixerBuffer with data if mMixerBufferValid is true and sleepTime == 0.
2524 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
2525 // or mSinkBuffer (if there are no effects).
2526 //
2527 // This is done pre-effects computation; if effects change to
2528 // support higher precision, this needs to move.
2529 //
2530 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
2531 // TODO use sleepTime == 0 as an additional condition.
2532 if (mMixerBufferValid) {
2533 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
2534 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
2535
2536 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
2537 mNormalFrameCount * mChannelCount);
2538 }
2539
Eric Laurentbfb1b832013-01-07 09:53:42 -08002540 mBytesRemaining = mCurrentWriteLength;
2541 if (isSuspended()) {
2542 sleepTime = suspendSleepTimeUs();
2543 // simulate write to HAL when suspended
Andy Hung25c2dac2014-02-27 14:56:00 -08002544 mBytesWritten += mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002545 mBytesRemaining = 0;
2546 }
Eric Laurent81784c32012-11-19 14:55:58 -08002547
Eric Laurentbfb1b832013-01-07 09:53:42 -08002548 // only process effects if we're going to write
Eric Laurent59fe0102013-09-27 18:48:26 -07002549 if (sleepTime == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002550 for (size_t i = 0; i < effectChains.size(); i ++) {
2551 effectChains[i]->process_l();
2552 }
Eric Laurent81784c32012-11-19 14:55:58 -08002553 }
2554 }
Eric Laurent59fe0102013-09-27 18:48:26 -07002555 // Process effect chains for offloaded thread even if no audio
2556 // was read from audio track: process only updates effect state
2557 // and thus does have to be synchronized with audio writes but may have
2558 // to be called while waiting for async write callback
2559 if (mType == OFFLOAD) {
2560 for (size_t i = 0; i < effectChains.size(); i ++) {
2561 effectChains[i]->process_l();
2562 }
2563 }
Eric Laurent81784c32012-11-19 14:55:58 -08002564
Andy Hung98ef9782014-03-04 14:46:50 -08002565 // Only if the Effects buffer is enabled and there is data in the
2566 // Effects buffer (buffer valid), we need to
2567 // copy into the sink buffer.
2568 // TODO use sleepTime == 0 as an additional condition.
2569 if (mEffectBufferValid) {
2570 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
2571 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
2572 mNormalFrameCount * mChannelCount);
2573 }
2574
Eric Laurent81784c32012-11-19 14:55:58 -08002575 // enable changes in effect chain
2576 unlockEffectChains(effectChains);
2577
Eric Laurentbfb1b832013-01-07 09:53:42 -08002578 if (!waitingAsyncCallback()) {
2579 // sleepTime == 0 means we must write to audio hardware
2580 if (sleepTime == 0) {
2581 if (mBytesRemaining) {
2582 ssize_t ret = threadLoop_write();
2583 if (ret < 0) {
2584 mBytesRemaining = 0;
2585 } else {
2586 mBytesWritten += ret;
2587 mBytesRemaining -= ret;
2588 }
2589 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
2590 (mMixerStatus == MIXER_DRAIN_ALL)) {
2591 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08002592 }
Glenn Kasten4944acb2013-08-19 08:39:20 -07002593 if (mType == MIXER) {
2594 // write blocked detection
2595 nsecs_t now = systemTime();
2596 nsecs_t delta = now - mLastWriteTime;
2597 if (!mStandby && delta > maxPeriod) {
2598 mNumDelayedWrites++;
2599 if ((now - lastWarning) > kWarningThrottleNs) {
2600 ATRACE_NAME("underrun");
2601 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2602 ns2ms(delta), mNumDelayedWrites, this);
2603 lastWarning = now;
2604 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002605 }
2606 }
Eric Laurent81784c32012-11-19 14:55:58 -08002607
Eric Laurentbfb1b832013-01-07 09:53:42 -08002608 } else {
2609 usleep(sleepTime);
2610 }
Eric Laurent81784c32012-11-19 14:55:58 -08002611 }
2612
2613 // Finally let go of removed track(s), without the lock held
2614 // since we can't guarantee the destructors won't acquire that
2615 // same lock. This will also mutate and push a new fast mixer state.
2616 threadLoop_removeTracks(tracksToRemove);
2617 tracksToRemove.clear();
2618
2619 // FIXME I don't understand the need for this here;
2620 // it was in the original code but maybe the
2621 // assignment in saveOutputTracks() makes this unnecessary?
2622 clearOutputTracks();
2623
2624 // Effect chains will be actually deleted here if they were removed from
2625 // mEffectChains list during mixing or effects processing
2626 effectChains.clear();
2627
2628 // FIXME Note that the above .clear() is no longer necessary since effectChains
2629 // is now local to this block, but will keep it for now (at least until merge done).
2630 }
2631
Eric Laurentbfb1b832013-01-07 09:53:42 -08002632 threadLoop_exit();
2633
Eric Laurentcf817a22014-08-04 20:36:31 -07002634 if (!mStandby) {
2635 threadLoop_standby();
2636 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08002637 }
2638
2639 releaseWakeLock();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002640 mWakeLockUids.clear();
2641 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002642
2643 ALOGV("Thread %p type %d exiting", this, mType);
2644 return false;
2645}
2646
Eric Laurentbfb1b832013-01-07 09:53:42 -08002647// removeTracks_l() must be called with ThreadBase::mLock held
2648void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
2649{
2650 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002651 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002652 for (size_t i=0 ; i<count ; i++) {
2653 const sp<Track>& track = tracksToRemove.itemAt(i);
2654 mActiveTracks.remove(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002655 mWakeLockUids.remove(track->uid());
2656 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002657 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
2658 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2659 if (chain != 0) {
2660 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
2661 track->sessionId());
2662 chain->decActiveTrackCnt();
2663 }
2664 if (track->isTerminated()) {
2665 removeTrack_l(track);
2666 }
2667 }
2668 }
2669
2670}
Eric Laurent81784c32012-11-19 14:55:58 -08002671
Eric Laurentaccc1472013-09-20 09:36:34 -07002672status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
2673{
2674 if (mNormalSink != 0) {
2675 return mNormalSink->getTimestamp(timestamp);
2676 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07002677 if ((mType == OFFLOAD || mType == DIRECT) && mOutput->stream->get_presentation_position) {
Eric Laurentaccc1472013-09-20 09:36:34 -07002678 uint64_t position64;
2679 int ret = mOutput->stream->get_presentation_position(
2680 mOutput->stream, &position64, &timestamp.mTime);
2681 if (ret == 0) {
2682 timestamp.mPosition = (uint32_t)position64;
2683 return NO_ERROR;
2684 }
2685 }
2686 return INVALID_OPERATION;
2687}
Eric Laurent1c333e22014-05-20 10:48:17 -07002688
2689status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
2690 audio_patch_handle_t *handle)
2691{
2692 status_t status = NO_ERROR;
2693 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
2694 // store new device and send to effects
2695 audio_devices_t type = AUDIO_DEVICE_NONE;
2696 for (unsigned int i = 0; i < patch->num_sinks; i++) {
2697 type |= patch->sinks[i].ext.device.type;
2698 }
2699 mOutDevice = type;
2700 for (size_t i = 0; i < mEffectChains.size(); i++) {
2701 mEffectChains[i]->setDevice_l(mOutDevice);
2702 }
2703
2704 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
2705 status = hwDevice->create_audio_patch(hwDevice,
2706 patch->num_sources,
2707 patch->sources,
2708 patch->num_sinks,
2709 patch->sinks,
2710 handle);
2711 } else {
2712 ALOG_ASSERT(false, "createAudioPatch_l() called on a pre 3.0 HAL");
2713 }
2714 return status;
2715}
2716
2717status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
2718{
2719 status_t status = NO_ERROR;
2720 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
2721 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
2722 status = hwDevice->release_audio_patch(hwDevice, handle);
2723 } else {
2724 ALOG_ASSERT(false, "releaseAudioPatch_l() called on a pre 3.0 HAL");
2725 }
2726 return status;
2727}
2728
Eric Laurent83b88082014-06-20 18:31:16 -07002729void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
2730{
2731 Mutex::Autolock _l(mLock);
2732 mTracks.add(track);
2733}
2734
2735void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
2736{
2737 Mutex::Autolock _l(mLock);
2738 destroyTrack_l(track);
2739}
2740
2741void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
2742{
2743 ThreadBase::getAudioPortConfig(config);
2744 config->role = AUDIO_PORT_ROLE_SOURCE;
2745 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
2746 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
2747}
2748
Eric Laurent81784c32012-11-19 14:55:58 -08002749// ----------------------------------------------------------------------------
2750
2751AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
2752 audio_io_handle_t id, audio_devices_t device, type_t type)
2753 : PlaybackThread(audioFlinger, output, id, device, type),
2754 // mAudioMixer below
2755 // mFastMixer below
2756 mFastMixerFutex(0)
2757 // mOutputSink below
2758 // mPipeSink below
2759 // mNormalSink below
2760{
2761 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07002762 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, "
Eric Laurent81784c32012-11-19 14:55:58 -08002763 "mFrameCount=%d, mNormalFrameCount=%d",
2764 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2765 mNormalFrameCount);
2766 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2767
Eric Laurent81784c32012-11-19 14:55:58 -08002768 // create an NBAIO sink for the HAL output stream, and negotiate
2769 mOutputSink = new AudioStreamOutSink(output->stream);
2770 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08002771 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Eric Laurent81784c32012-11-19 14:55:58 -08002772 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2773 ALOG_ASSERT(index == 0);
2774
2775 // initialize fast mixer depending on configuration
2776 bool initFastMixer;
2777 switch (kUseFastMixer) {
2778 case FastMixer_Never:
2779 initFastMixer = false;
2780 break;
2781 case FastMixer_Always:
2782 initFastMixer = true;
2783 break;
2784 case FastMixer_Static:
2785 case FastMixer_Dynamic:
2786 initFastMixer = mFrameCount < mNormalFrameCount;
2787 break;
2788 }
2789 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07002790 audio_format_t fastMixerFormat;
2791 if (mMixerBufferEnabled && mEffectBufferEnabled) {
2792 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
2793 } else {
2794 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
2795 }
2796 if (mFormat != fastMixerFormat) {
2797 // change our Sink format to accept our intermediate precision
2798 mFormat = fastMixerFormat;
2799 free(mSinkBuffer);
2800 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2801 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
2802 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
2803 }
Eric Laurent81784c32012-11-19 14:55:58 -08002804
2805 // create a MonoPipe to connect our submix to FastMixer
2806 NBAIO_Format format = mOutputSink->format();
Andy Hung1258c1a2014-05-23 21:22:17 -07002807 // adjust format to match that of the Fast Mixer
2808 format.mFormat = fastMixerFormat;
2809 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
2810
Eric Laurent81784c32012-11-19 14:55:58 -08002811 // This pipe depth compensates for scheduling latency of the normal mixer thread.
2812 // When it wakes up after a maximum latency, it runs a few cycles quickly before
2813 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
2814 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
2815 const NBAIO_Format offers[1] = {format};
2816 size_t numCounterOffers = 0;
2817 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2818 ALOG_ASSERT(index == 0);
2819 monoPipe->setAvgFrames((mScreenState & 1) ?
2820 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2821 mPipeSink = monoPipe;
2822
Glenn Kasten46909e72013-02-26 09:20:22 -08002823#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08002824 if (mTeeSinkOutputEnabled) {
2825 // create a Pipe to archive a copy of FastMixer's output for dumpsys
2826 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, format);
2827 numCounterOffers = 0;
2828 index = teeSink->negotiate(offers, 1, NULL, numCounterOffers);
2829 ALOG_ASSERT(index == 0);
2830 mTeeSink = teeSink;
2831 PipeReader *teeSource = new PipeReader(*teeSink);
2832 numCounterOffers = 0;
2833 index = teeSource->negotiate(offers, 1, NULL, numCounterOffers);
2834 ALOG_ASSERT(index == 0);
2835 mTeeSource = teeSource;
2836 }
Glenn Kasten46909e72013-02-26 09:20:22 -08002837#endif
Eric Laurent81784c32012-11-19 14:55:58 -08002838
2839 // create fast mixer and configure it initially with just one fast track for our submix
2840 mFastMixer = new FastMixer();
2841 FastMixerStateQueue *sq = mFastMixer->sq();
2842#ifdef STATE_QUEUE_DUMP
2843 sq->setObserverDump(&mStateQueueObserverDump);
2844 sq->setMutatorDump(&mStateQueueMutatorDump);
2845#endif
2846 FastMixerState *state = sq->begin();
2847 FastTrack *fastTrack = &state->mFastTracks[0];
2848 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2849 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2850 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07002851 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
2852 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08002853 fastTrack->mGeneration++;
2854 state->mFastTracksGen++;
2855 state->mTrackMask = 1;
2856 // fast mixer will use the HAL output sink
2857 state->mOutputSink = mOutputSink.get();
2858 state->mOutputSinkGen++;
2859 state->mFrameCount = mFrameCount;
2860 state->mCommand = FastMixerState::COLD_IDLE;
2861 // already done in constructor initialization list
2862 //mFastMixerFutex = 0;
2863 state->mColdFutexAddr = &mFastMixerFutex;
2864 state->mColdGen++;
2865 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08002866#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08002867 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08002868#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08002869 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
2870 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08002871 sq->end();
2872 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2873
2874 // start the fast mixer
2875 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
2876 pid_t tid = mFastMixer->getTid();
2877 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2878 if (err != 0) {
2879 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2880 kPriorityFastMixer, getpid_cached, tid, err);
2881 }
2882
2883#ifdef AUDIO_WATCHDOG
2884 // create and start the watchdog
2885 mAudioWatchdog = new AudioWatchdog();
2886 mAudioWatchdog->setDump(&mAudioWatchdogDump);
2887 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
2888 tid = mAudioWatchdog->getTid();
2889 err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2890 if (err != 0) {
2891 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2892 kPriorityFastMixer, getpid_cached, tid, err);
2893 }
2894#endif
2895
Eric Laurent81784c32012-11-19 14:55:58 -08002896 }
2897
2898 switch (kUseFastMixer) {
2899 case FastMixer_Never:
2900 case FastMixer_Dynamic:
2901 mNormalSink = mOutputSink;
2902 break;
2903 case FastMixer_Always:
2904 mNormalSink = mPipeSink;
2905 break;
2906 case FastMixer_Static:
2907 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2908 break;
2909 }
2910}
2911
2912AudioFlinger::MixerThread::~MixerThread()
2913{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07002914 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002915 FastMixerStateQueue *sq = mFastMixer->sq();
2916 FastMixerState *state = sq->begin();
2917 if (state->mCommand == FastMixerState::COLD_IDLE) {
2918 int32_t old = android_atomic_inc(&mFastMixerFutex);
2919 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07002920 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08002921 }
2922 }
2923 state->mCommand = FastMixerState::EXIT;
2924 sq->end();
2925 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2926 mFastMixer->join();
2927 // Though the fast mixer thread has exited, it's state queue is still valid.
2928 // We'll use that extract the final state which contains one remaining fast track
2929 // corresponding to our sub-mix.
2930 state = sq->begin();
2931 ALOG_ASSERT(state->mTrackMask == 1);
2932 FastTrack *fastTrack = &state->mFastTracks[0];
2933 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2934 delete fastTrack->mBufferProvider;
2935 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07002936 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08002937#ifdef AUDIO_WATCHDOG
2938 if (mAudioWatchdog != 0) {
2939 mAudioWatchdog->requestExit();
2940 mAudioWatchdog->requestExitAndWait();
2941 mAudioWatchdog.clear();
2942 }
2943#endif
2944 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08002945 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08002946 delete mAudioMixer;
2947}
2948
2949
2950uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
2951{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07002952 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002953 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2954 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
2955 }
2956 return latency;
2957}
2958
2959
2960void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2961{
2962 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
2963}
2964
Eric Laurentbfb1b832013-01-07 09:53:42 -08002965ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002966{
2967 // FIXME we should only do one push per cycle; confirm this is true
2968 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07002969 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002970 FastMixerStateQueue *sq = mFastMixer->sq();
2971 FastMixerState *state = sq->begin();
2972 if (state->mCommand != FastMixerState::MIX_WRITE &&
2973 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
2974 if (state->mCommand == FastMixerState::COLD_IDLE) {
2975 int32_t old = android_atomic_inc(&mFastMixerFutex);
2976 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07002977 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08002978 }
2979#ifdef AUDIO_WATCHDOG
2980 if (mAudioWatchdog != 0) {
2981 mAudioWatchdog->resume();
2982 }
2983#endif
2984 }
2985 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002986 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
2987 FastMixerDumpState::kSamplingNforLowRamDevice : FastMixerDumpState::kSamplingN);
Eric Laurent81784c32012-11-19 14:55:58 -08002988 sq->end();
2989 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2990 if (kUseFastMixer == FastMixer_Dynamic) {
2991 mNormalSink = mPipeSink;
2992 }
2993 } else {
2994 sq->end(false /*didModify*/);
2995 }
2996 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002997 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08002998}
2999
3000void AudioFlinger::MixerThread::threadLoop_standby()
3001{
3002 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003003 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003004 FastMixerStateQueue *sq = mFastMixer->sq();
3005 FastMixerState *state = sq->begin();
3006 if (!(state->mCommand & FastMixerState::IDLE)) {
3007 state->mCommand = FastMixerState::COLD_IDLE;
3008 state->mColdFutexAddr = &mFastMixerFutex;
3009 state->mColdGen++;
3010 mFastMixerFutex = 0;
3011 sq->end();
3012 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3013 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3014 if (kUseFastMixer == FastMixer_Dynamic) {
3015 mNormalSink = mOutputSink;
3016 }
3017#ifdef AUDIO_WATCHDOG
3018 if (mAudioWatchdog != 0) {
3019 mAudioWatchdog->pause();
3020 }
3021#endif
3022 } else {
3023 sq->end(false /*didModify*/);
3024 }
3025 }
3026 PlaybackThread::threadLoop_standby();
3027}
3028
Eric Laurentbfb1b832013-01-07 09:53:42 -08003029bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3030{
3031 return false;
3032}
3033
3034bool AudioFlinger::PlaybackThread::shouldStandby_l()
3035{
3036 return !mStandby;
3037}
3038
3039bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3040{
3041 Mutex::Autolock _l(mLock);
3042 return waitingAsyncCallback_l();
3043}
3044
Eric Laurent81784c32012-11-19 14:55:58 -08003045// shared by MIXER and DIRECT, overridden by DUPLICATING
3046void AudioFlinger::PlaybackThread::threadLoop_standby()
3047{
3048 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
3049 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003050 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003051 // discard any pending drain or write ack by incrementing sequence
3052 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3053 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003054 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003055 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3056 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003057 }
Eric Laurent81784c32012-11-19 14:55:58 -08003058}
3059
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003060void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3061{
3062 ALOGV("signal playback thread");
3063 broadcast_l();
3064}
3065
Eric Laurent81784c32012-11-19 14:55:58 -08003066void AudioFlinger::MixerThread::threadLoop_mix()
3067{
3068 // obtain the presentation timestamp of the next output buffer
3069 int64_t pts;
3070 status_t status = INVALID_OPERATION;
3071
3072 if (mNormalSink != 0) {
3073 status = mNormalSink->getNextWriteTimestamp(&pts);
3074 } else {
3075 status = mOutputSink->getNextWriteTimestamp(&pts);
3076 }
3077
3078 if (status != NO_ERROR) {
3079 pts = AudioBufferProvider::kInvalidPTS;
3080 }
3081
3082 // mix buffers...
3083 mAudioMixer->process(pts);
Andy Hung25c2dac2014-02-27 14:56:00 -08003084 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003085 // increase sleep time progressively when application underrun condition clears.
3086 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3087 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3088 // such that we would underrun the audio HAL.
3089 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
3090 sleepTimeShift--;
3091 }
3092 sleepTime = 0;
3093 standbyTime = systemTime() + standbyDelay;
3094 //TODO: delay standby when effects have a tail
3095}
3096
3097void AudioFlinger::MixerThread::threadLoop_sleepTime()
3098{
3099 // If no tracks are ready, sleep once for the duration of an output
3100 // buffer size, then write 0s to the output
3101 if (sleepTime == 0) {
3102 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3103 sleepTime = activeSleepTime >> sleepTimeShift;
3104 if (sleepTime < kMinThreadSleepTimeUs) {
3105 sleepTime = kMinThreadSleepTimeUs;
3106 }
3107 // reduce sleep time in case of consecutive application underruns to avoid
3108 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3109 // duration we would end up writing less data than needed by the audio HAL if
3110 // the condition persists.
3111 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3112 sleepTimeShift++;
3113 }
3114 } else {
3115 sleepTime = idleSleepTime;
3116 }
3117 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003118 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3119 // before effects processing or output.
3120 if (mMixerBufferValid) {
3121 memset(mMixerBuffer, 0, mMixerBufferSize);
3122 } else {
3123 memset(mSinkBuffer, 0, mSinkBufferSize);
3124 }
Eric Laurent81784c32012-11-19 14:55:58 -08003125 sleepTime = 0;
3126 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3127 "anticipated start");
3128 }
3129 // TODO add standby time extension fct of effect tail
3130}
3131
3132// prepareTracks_l() must be called with ThreadBase::mLock held
3133AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3134 Vector< sp<Track> > *tracksToRemove)
3135{
3136
3137 mixer_state mixerStatus = MIXER_IDLE;
3138 // find out which tracks need to be processed
3139 size_t count = mActiveTracks.size();
3140 size_t mixedTracks = 0;
3141 size_t tracksWithEffect = 0;
3142 // counts only _active_ fast tracks
3143 size_t fastTracks = 0;
3144 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
3145
3146 float masterVolume = mMasterVolume;
3147 bool masterMute = mMasterMute;
3148
3149 if (masterMute) {
3150 masterVolume = 0;
3151 }
3152 // Delegate master volume control to effect in output mix effect chain if needed
3153 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3154 if (chain != 0) {
3155 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
3156 chain->setVolume_l(&v, &v);
3157 masterVolume = (float)((v + (1 << 23)) >> 24);
3158 chain.clear();
3159 }
3160
3161 // prepare a new state to push
3162 FastMixerStateQueue *sq = NULL;
3163 FastMixerState *state = NULL;
3164 bool didModify = false;
3165 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003166 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003167 sq = mFastMixer->sq();
3168 state = sq->begin();
3169 }
3170
Andy Hung69aed5f2014-02-25 17:24:40 -08003171 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08003172 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08003173
Eric Laurent81784c32012-11-19 14:55:58 -08003174 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003175 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003176 if (t == 0) {
3177 continue;
3178 }
3179
3180 // this const just means the local variable doesn't change
3181 Track* const track = t.get();
3182
3183 // process fast tracks
3184 if (track->isFastTrack()) {
3185
3186 // It's theoretically possible (though unlikely) for a fast track to be created
3187 // and then removed within the same normal mix cycle. This is not a problem, as
3188 // the track never becomes active so it's fast mixer slot is never touched.
3189 // The converse, of removing an (active) track and then creating a new track
3190 // at the identical fast mixer slot within the same normal mix cycle,
3191 // is impossible because the slot isn't marked available until the end of each cycle.
3192 int j = track->mFastIndex;
3193 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
3194 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
3195 FastTrack *fastTrack = &state->mFastTracks[j];
3196
3197 // Determine whether the track is currently in underrun condition,
3198 // and whether it had a recent underrun.
3199 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
3200 FastTrackUnderruns underruns = ftDump->mUnderruns;
3201 uint32_t recentFull = (underruns.mBitFields.mFull -
3202 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
3203 uint32_t recentPartial = (underruns.mBitFields.mPartial -
3204 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
3205 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
3206 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
3207 uint32_t recentUnderruns = recentPartial + recentEmpty;
3208 track->mObservedUnderruns = underruns;
3209 // don't count underruns that occur while stopping or pausing
3210 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07003211 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
3212 recentUnderruns > 0) {
3213 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
3214 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003215 }
3216
3217 // This is similar to the state machine for normal tracks,
3218 // with a few modifications for fast tracks.
3219 bool isActive = true;
3220 switch (track->mState) {
3221 case TrackBase::STOPPING_1:
3222 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08003223 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003224 track->mState = TrackBase::STOPPING_2;
3225 }
3226 break;
3227 case TrackBase::PAUSING:
3228 // ramp down is not yet implemented
3229 track->setPaused();
3230 break;
3231 case TrackBase::RESUMING:
3232 // ramp up is not yet implemented
3233 track->mState = TrackBase::ACTIVE;
3234 break;
3235 case TrackBase::ACTIVE:
3236 if (recentFull > 0 || recentPartial > 0) {
3237 // track has provided at least some frames recently: reset retry count
3238 track->mRetryCount = kMaxTrackRetries;
3239 }
3240 if (recentUnderruns == 0) {
3241 // no recent underruns: stay active
3242 break;
3243 }
3244 // there has recently been an underrun of some kind
3245 if (track->sharedBuffer() == 0) {
3246 // were any of the recent underruns "empty" (no frames available)?
3247 if (recentEmpty == 0) {
3248 // no, then ignore the partial underruns as they are allowed indefinitely
3249 break;
3250 }
3251 // there has recently been an "empty" underrun: decrement the retry counter
3252 if (--(track->mRetryCount) > 0) {
3253 break;
3254 }
3255 // indicate to client process that the track was disabled because of underrun;
3256 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003257 android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003258 // remove from active list, but state remains ACTIVE [confusing but true]
3259 isActive = false;
3260 break;
3261 }
3262 // fall through
3263 case TrackBase::STOPPING_2:
3264 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003265 case TrackBase::STOPPED:
3266 case TrackBase::FLUSHED: // flush() while active
3267 // Check for presentation complete if track is inactive
3268 // We have consumed all the buffers of this track.
3269 // This would be incomplete if we auto-paused on underrun
3270 {
3271 size_t audioHALFrames =
3272 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3273 size_t framesWritten = mBytesWritten / mFrameSize;
3274 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
3275 // track stays in active list until presentation is complete
3276 break;
3277 }
3278 }
3279 if (track->isStopping_2()) {
3280 track->mState = TrackBase::STOPPED;
3281 }
3282 if (track->isStopped()) {
3283 // Can't reset directly, as fast mixer is still polling this track
3284 // track->reset();
3285 // So instead mark this track as needing to be reset after push with ack
3286 resetMask |= 1 << i;
3287 }
3288 isActive = false;
3289 break;
3290 case TrackBase::IDLE:
3291 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08003292 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08003293 }
3294
3295 if (isActive) {
3296 // was it previously inactive?
3297 if (!(state->mTrackMask & (1 << j))) {
3298 ExtendedAudioBufferProvider *eabp = track;
3299 VolumeProvider *vp = track;
3300 fastTrack->mBufferProvider = eabp;
3301 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08003302 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003303 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08003304 fastTrack->mGeneration++;
3305 state->mTrackMask |= 1 << j;
3306 didModify = true;
3307 // no acknowledgement required for newly active tracks
3308 }
3309 // cache the combined master volume and stream type volume for fast mixer; this
3310 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08003311 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08003312 ++fastTracks;
3313 } else {
3314 // was it previously active?
3315 if (state->mTrackMask & (1 << j)) {
3316 fastTrack->mBufferProvider = NULL;
3317 fastTrack->mGeneration++;
3318 state->mTrackMask &= ~(1 << j);
3319 didModify = true;
3320 // If any fast tracks were removed, we must wait for acknowledgement
3321 // because we're about to decrement the last sp<> on those tracks.
3322 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3323 } else {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003324 LOG_ALWAYS_FATAL("fast track %d should have been active", j);
Eric Laurent81784c32012-11-19 14:55:58 -08003325 }
3326 tracksToRemove->add(track);
3327 // Avoids a misleading display in dumpsys
3328 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
3329 }
3330 continue;
3331 }
3332
3333 { // local variable scope to avoid goto warning
3334
3335 audio_track_cblk_t* cblk = track->cblk();
3336
3337 // The first time a track is added we wait
3338 // for all its buffers to be filled before processing it
3339 int name = track->name();
3340 // make sure that we have enough frames to mix one full buffer.
3341 // enforce this condition only once to enable draining the buffer in case the client
3342 // app does not call stop() and relies on underrun to stop:
3343 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
3344 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003345 size_t desiredFrames;
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003346 uint32_t sr = track->sampleRate();
3347 if (sr == mSampleRate) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003348 desiredFrames = mNormalFrameCount;
3349 } else {
3350 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003351 desiredFrames = (mNormalFrameCount * sr) / mSampleRate + 1 + 1;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003352 // add frames already consumed but not yet released by the resampler
Glenn Kasten2fc14732013-08-05 14:58:14 -07003353 // because mAudioTrackServerProxy->framesReady() will include these frames
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003354 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
Glenn Kasten74935e42013-12-19 08:56:45 -08003355#if 0
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003356 // the minimum track buffer size is normally twice the number of frames necessary
3357 // to fill one buffer and the resampler should not leave more than one buffer worth
3358 // of unreleased frames after each pass, but just in case...
3359 ALOG_ASSERT(desiredFrames <= cblk->frameCount_);
Glenn Kasten74935e42013-12-19 08:56:45 -08003360#endif
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003361 }
Eric Laurent81784c32012-11-19 14:55:58 -08003362 uint32_t minFrames = 1;
3363 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
3364 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003365 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08003366 }
Eric Laurent13e4c962013-12-20 17:36:01 -08003367
3368 size_t framesReady = track->framesReady();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003369 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08003370 !track->isPaused() && !track->isTerminated())
3371 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003372 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003373
3374 mixedTracks++;
3375
Andy Hung69aed5f2014-02-25 17:24:40 -08003376 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
3377 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08003378 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08003379 if (track->mainBuffer() != mSinkBuffer &&
3380 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08003381 if (mEffectBufferEnabled) {
3382 mEffectBufferValid = true; // Later can set directly.
3383 }
Eric Laurent81784c32012-11-19 14:55:58 -08003384 chain = getEffectChain_l(track->sessionId());
3385 // Delegate volume control to effect in track effect chain if needed
3386 if (chain != 0) {
3387 tracksWithEffect++;
3388 } else {
3389 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
3390 "session %d",
3391 name, track->sessionId());
3392 }
3393 }
3394
3395
3396 int param = AudioMixer::VOLUME;
3397 if (track->mFillingUpStatus == Track::FS_FILLED) {
3398 // no ramp for the first volume setting
3399 track->mFillingUpStatus = Track::FS_ACTIVE;
3400 if (track->mState == TrackBase::RESUMING) {
3401 track->mState = TrackBase::ACTIVE;
3402 param = AudioMixer::RAMP_VOLUME;
3403 }
3404 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003405 // FIXME should not make a decision based on mServer
3406 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003407 // If the track is stopped before the first frame was mixed,
3408 // do not apply ramp
3409 param = AudioMixer::RAMP_VOLUME;
3410 }
3411
3412 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07003413 uint32_t vl, vr; // in U8.24 integer format
3414 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08003415 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07003416 vl = vr = 0;
3417 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08003418 if (track->isPausing()) {
3419 track->setPaused();
3420 }
3421 } else {
3422
3423 // read original volumes with volume control
3424 float typeVolume = mStreamTypes[track->streamType()].volume;
3425 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003426 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07003427 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07003428 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
3429 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08003430 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07003431 if (vlf > GAIN_FLOAT_UNITY) {
3432 ALOGV("Track left volume out of range: %.3g", vlf);
3433 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003434 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07003435 if (vrf > GAIN_FLOAT_UNITY) {
3436 ALOGV("Track right volume out of range: %.3g", vrf);
3437 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003438 }
3439 // now apply the master volume and stream type volume
Andy Hung6be49402014-05-30 10:42:03 -07003440 vlf *= v;
3441 vrf *= v;
Eric Laurent81784c32012-11-19 14:55:58 -08003442 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07003443 // then derive vl and vr as U8.24 versions for the effect chain
3444 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
3445 vl = (uint32_t) (scaleto8_24 * vlf);
3446 vr = (uint32_t) (scaleto8_24 * vrf);
3447 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08003448 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08003449 // send level comes from shared memory and so may be corrupt
3450 if (sendLevel > MAX_GAIN_INT) {
3451 ALOGV("Track send level out of range: %04X", sendLevel);
3452 sendLevel = MAX_GAIN_INT;
3453 }
Andy Hung6be49402014-05-30 10:42:03 -07003454 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
3455 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08003456 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003457
Eric Laurent81784c32012-11-19 14:55:58 -08003458 // Delegate volume control to effect in track effect chain if needed
3459 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3460 // Do not ramp volume if volume is controlled by effect
3461 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08003462 // Update remaining floating point volume levels
3463 vlf = (float)vl / (1 << 24);
3464 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08003465 track->mHasVolumeController = true;
3466 } else {
3467 // force no volume ramp when volume controller was just disabled or removed
3468 // from effect chain to avoid volume spike
3469 if (track->mHasVolumeController) {
3470 param = AudioMixer::VOLUME;
3471 }
3472 track->mHasVolumeController = false;
3473 }
3474
Eric Laurent81784c32012-11-19 14:55:58 -08003475 // XXX: these things DON'T need to be done each time
3476 mAudioMixer->setBufferProvider(name, track);
3477 mAudioMixer->enable(name);
3478
Andy Hung6be49402014-05-30 10:42:03 -07003479 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
3480 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
3481 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08003482 mAudioMixer->setParameter(
3483 name,
3484 AudioMixer::TRACK,
3485 AudioMixer::FORMAT, (void *)track->format());
3486 mAudioMixer->setParameter(
3487 name,
3488 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003489 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07003490 mAudioMixer->setParameter(
3491 name,
3492 AudioMixer::TRACK,
3493 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08003494 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07003495 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003496 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08003497 if (reqSampleRate == 0) {
3498 reqSampleRate = mSampleRate;
3499 } else if (reqSampleRate > maxSampleRate) {
3500 reqSampleRate = maxSampleRate;
3501 }
Eric Laurent81784c32012-11-19 14:55:58 -08003502 mAudioMixer->setParameter(
3503 name,
3504 AudioMixer::RESAMPLE,
3505 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003506 (void *)(uintptr_t)reqSampleRate);
Andy Hung69aed5f2014-02-25 17:24:40 -08003507 /*
3508 * Select the appropriate output buffer for the track.
3509 *
Andy Hung98ef9782014-03-04 14:46:50 -08003510 * Tracks with effects go into their own effects chain buffer
3511 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08003512 *
3513 * Other tracks can use mMixerBuffer for higher precision
3514 * channel accumulation. If this buffer is enabled
3515 * (mMixerBufferEnabled true), then selected tracks will accumulate
3516 * into it.
3517 *
3518 */
3519 if (mMixerBufferEnabled
3520 && (track->mainBuffer() == mSinkBuffer
3521 || track->mainBuffer() == mMixerBuffer)) {
3522 mAudioMixer->setParameter(
3523 name,
3524 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08003525 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08003526 mAudioMixer->setParameter(
3527 name,
3528 AudioMixer::TRACK,
3529 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
3530 // TODO: override track->mainBuffer()?
3531 mMixerBufferValid = true;
3532 } else {
3533 mAudioMixer->setParameter(
3534 name,
3535 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08003536 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08003537 mAudioMixer->setParameter(
3538 name,
3539 AudioMixer::TRACK,
3540 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3541 }
Eric Laurent81784c32012-11-19 14:55:58 -08003542 mAudioMixer->setParameter(
3543 name,
3544 AudioMixer::TRACK,
3545 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3546
3547 // reset retry count
3548 track->mRetryCount = kMaxTrackRetries;
3549
3550 // If one track is ready, set the mixer ready if:
3551 // - the mixer was not ready during previous round OR
3552 // - no other track is not ready
3553 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
3554 mixerStatus != MIXER_TRACKS_ENABLED) {
3555 mixerStatus = MIXER_TRACKS_READY;
3556 }
3557 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003558 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Glenn Kasten82aaf942013-07-17 16:05:07 -07003559 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003560 }
Eric Laurent81784c32012-11-19 14:55:58 -08003561 // clear effect chain input buffer if an active track underruns to avoid sending
3562 // previous audio buffer again to effects
3563 chain = getEffectChain_l(track->sessionId());
3564 if (chain != 0) {
3565 chain->clearInputBuffer();
3566 }
3567
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003568 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003569 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3570 track->isStopped() || track->isPaused()) {
3571 // We have consumed all the buffers of this track.
3572 // Remove it from the list of active tracks.
3573 // TODO: use actual buffer filling status instead of latency when available from
3574 // audio HAL
3575 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3576 size_t framesWritten = mBytesWritten / mFrameSize;
3577 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
3578 if (track->isStopped()) {
3579 track->reset();
3580 }
3581 tracksToRemove->add(track);
3582 }
3583 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08003584 // No buffers for this track. Give it a few chances to
3585 // fill a buffer, then remove it from active list.
3586 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08003587 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003588 tracksToRemove->add(track);
3589 // indicate to client process that the track was disabled because of underrun;
3590 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003591 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003592 // If one track is not ready, mark the mixer also not ready if:
3593 // - the mixer was ready during previous round OR
3594 // - no other track is ready
3595 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
3596 mixerStatus != MIXER_TRACKS_READY) {
3597 mixerStatus = MIXER_TRACKS_ENABLED;
3598 }
3599 }
3600 mAudioMixer->disable(name);
3601 }
3602
3603 } // local variable scope to avoid goto warning
3604track_is_ready: ;
3605
3606 }
3607
3608 // Push the new FastMixer state if necessary
3609 bool pauseAudioWatchdog = false;
3610 if (didModify) {
3611 state->mFastTracksGen++;
3612 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3613 if (kUseFastMixer == FastMixer_Dynamic &&
3614 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3615 state->mCommand = FastMixerState::COLD_IDLE;
3616 state->mColdFutexAddr = &mFastMixerFutex;
3617 state->mColdGen++;
3618 mFastMixerFutex = 0;
3619 if (kUseFastMixer == FastMixer_Dynamic) {
3620 mNormalSink = mOutputSink;
3621 }
3622 // If we go into cold idle, need to wait for acknowledgement
3623 // so that fast mixer stops doing I/O.
3624 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3625 pauseAudioWatchdog = true;
3626 }
Eric Laurent81784c32012-11-19 14:55:58 -08003627 }
3628 if (sq != NULL) {
3629 sq->end(didModify);
3630 sq->push(block);
3631 }
3632#ifdef AUDIO_WATCHDOG
3633 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3634 mAudioWatchdog->pause();
3635 }
3636#endif
3637
3638 // Now perform the deferred reset on fast tracks that have stopped
3639 while (resetMask != 0) {
3640 size_t i = __builtin_ctz(resetMask);
3641 ALOG_ASSERT(i < count);
3642 resetMask &= ~(1 << i);
3643 sp<Track> t = mActiveTracks[i].promote();
3644 if (t == 0) {
3645 continue;
3646 }
3647 Track* track = t.get();
3648 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3649 track->reset();
3650 }
3651
3652 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08003653 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08003654
Eric Laurent97d547d2014-09-02 14:45:53 -07003655 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
3656 mEffectBufferValid = true;
3657 }
3658
Andy Hung69aed5f2014-02-25 17:24:40 -08003659 // sink or mix buffer must be cleared if all tracks are connected to an
3660 // effect chain as in this case the mixer will not write to the sink or mix buffer
3661 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08003662 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3663 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08003664 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08003665 if (mMixerBufferValid) {
3666 memset(mMixerBuffer, 0, mMixerBufferSize);
3667 // TODO: In testing, mSinkBuffer below need not be cleared because
3668 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
3669 // after mixing.
3670 //
3671 // To enforce this guarantee:
3672 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3673 // (mixedTracks == 0 && fastTracks > 0))
3674 // must imply MIXER_TRACKS_READY.
3675 // Later, we may clear buffers regardless, and skip much of this logic.
3676 }
Andy Hung98ef9782014-03-04 14:46:50 -08003677 // TODO - either mEffectBuffer or mSinkBuffer needs to be cleared.
3678 if (mEffectBufferValid) {
3679 memset(mEffectBuffer, 0, mEffectBufferSize);
3680 }
3681 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07003682 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003683 }
3684
3685 // if any fast tracks, then status is ready
3686 mMixerStatusIgnoringFastTracks = mixerStatus;
3687 if (fastTracks > 0) {
3688 mixerStatus = MIXER_TRACKS_READY;
3689 }
3690 return mixerStatus;
3691}
3692
3693// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07003694int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
3695 audio_format_t format, int sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08003696{
Andy Hunge8a1ced2014-05-09 15:02:21 -07003697 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08003698}
3699
3700// deleteTrackName_l() must be called with ThreadBase::mLock held
3701void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3702{
3703 ALOGV("remove track (%d) and delete from mixer", name);
3704 mAudioMixer->deleteTrackName(name);
3705}
3706
Eric Laurent10351942014-05-08 18:49:52 -07003707// checkForNewParameter_l() must be called with ThreadBase::mLock held
3708bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
3709 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08003710{
Eric Laurent81784c32012-11-19 14:55:58 -08003711 bool reconfig = false;
3712
Eric Laurent10351942014-05-08 18:49:52 -07003713 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08003714
Eric Laurent10351942014-05-08 18:49:52 -07003715 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3716 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003717 if (mFastMixer != 0) {
Eric Laurent10351942014-05-08 18:49:52 -07003718 FastMixerStateQueue *sq = mFastMixer->sq();
3719 FastMixerState *state = sq->begin();
3720 if (!(state->mCommand & FastMixerState::IDLE)) {
3721 previousCommand = state->mCommand;
3722 state->mCommand = FastMixerState::HOT_IDLE;
3723 sq->end();
3724 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3725 } else {
3726 sq->end(false /*didModify*/);
Eric Laurent81784c32012-11-19 14:55:58 -08003727 }
Eric Laurent10351942014-05-08 18:49:52 -07003728 }
Eric Laurent81784c32012-11-19 14:55:58 -08003729
Eric Laurent10351942014-05-08 18:49:52 -07003730 AudioParameter param = AudioParameter(keyValuePair);
3731 int value;
3732 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3733 reconfig = true;
3734 }
3735 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07003736 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07003737 status = BAD_VALUE;
3738 } else {
3739 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08003740 reconfig = true;
3741 }
Eric Laurent10351942014-05-08 18:49:52 -07003742 }
3743 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07003744 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07003745 status = BAD_VALUE;
3746 } else {
3747 // no need to save value, since it's constant
3748 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003749 }
Eric Laurent10351942014-05-08 18:49:52 -07003750 }
3751 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3752 // do not accept frame count changes if tracks are open as the track buffer
3753 // size depends on frame count and correct behavior would not be guaranteed
3754 // if frame count is changed after track creation
3755 if (!mTracks.isEmpty()) {
3756 status = INVALID_OPERATION;
3757 } else {
3758 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003759 }
Eric Laurent10351942014-05-08 18:49:52 -07003760 }
3761 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08003762#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07003763 // when changing the audio output device, call addBatteryData to notify
3764 // the change
3765 if (mOutDevice != value) {
3766 uint32_t params = 0;
3767 // check whether speaker is on
3768 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
3769 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08003770 }
Eric Laurent10351942014-05-08 18:49:52 -07003771
3772 audio_devices_t deviceWithoutSpeaker
3773 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3774 // check if any other device (except speaker) is on
3775 if (value & deviceWithoutSpeaker ) {
3776 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3777 }
3778
3779 if (params != 0) {
3780 addBatteryData(params);
3781 }
3782 }
Eric Laurent81784c32012-11-19 14:55:58 -08003783#endif
3784
Eric Laurent10351942014-05-08 18:49:52 -07003785 // forward device change to effects that have requested to be
3786 // aware of attached audio device.
3787 if (value != AUDIO_DEVICE_NONE) {
3788 mOutDevice = value;
3789 for (size_t i = 0; i < mEffectChains.size(); i++) {
3790 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08003791 }
3792 }
Eric Laurent10351942014-05-08 18:49:52 -07003793 }
Eric Laurent81784c32012-11-19 14:55:58 -08003794
Eric Laurent10351942014-05-08 18:49:52 -07003795 if (status == NO_ERROR) {
3796 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3797 keyValuePair.string());
3798 if (!mStandby && status == INVALID_OPERATION) {
3799 mOutput->stream->common.standby(&mOutput->stream->common);
3800 mStandby = true;
3801 mBytesWritten = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003802 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Eric Laurent10351942014-05-08 18:49:52 -07003803 keyValuePair.string());
Eric Laurent81784c32012-11-19 14:55:58 -08003804 }
Eric Laurent10351942014-05-08 18:49:52 -07003805 if (status == NO_ERROR && reconfig) {
3806 readOutputParameters_l();
3807 delete mAudioMixer;
3808 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3809 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07003810 int name = getTrackName_l(mTracks[i]->mChannelMask,
3811 mTracks[i]->mFormat, mTracks[i]->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07003812 if (name < 0) {
3813 break;
3814 }
3815 mTracks[i]->mName = name;
3816 }
3817 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3818 }
Eric Laurent81784c32012-11-19 14:55:58 -08003819 }
3820
3821 if (!(previousCommand & FastMixerState::IDLE)) {
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003822 ALOG_ASSERT(mFastMixer != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08003823 FastMixerStateQueue *sq = mFastMixer->sq();
3824 FastMixerState *state = sq->begin();
3825 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3826 state->mCommand = previousCommand;
3827 sq->end();
3828 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3829 }
3830
3831 return reconfig;
3832}
3833
3834
3835void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
3836{
3837 const size_t SIZE = 256;
3838 char buffer[SIZE];
3839 String8 result;
3840
3841 PlaybackThread::dumpInternals(fd, args);
3842
Elliott Hughes87cebad2014-05-22 10:14:43 -07003843 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Eric Laurent81784c32012-11-19 14:55:58 -08003844
3845 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003846 const FastMixerDumpState copy(mFastMixerDumpState);
Eric Laurent81784c32012-11-19 14:55:58 -08003847 copy.dump(fd);
3848
3849#ifdef STATE_QUEUE_DUMP
3850 // Similar for state queue
3851 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
3852 observerCopy.dump(fd);
3853 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
3854 mutatorCopy.dump(fd);
3855#endif
3856
Glenn Kasten46909e72013-02-26 09:20:22 -08003857#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003858 // Write the tee output to a .wav file
3859 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08003860#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003861
3862#ifdef AUDIO_WATCHDOG
3863 if (mAudioWatchdog != 0) {
3864 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
3865 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
3866 wdCopy.dump(fd);
3867 }
3868#endif
3869}
3870
3871uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
3872{
3873 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
3874}
3875
3876uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
3877{
3878 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3879}
3880
3881void AudioFlinger::MixerThread::cacheParameters_l()
3882{
3883 PlaybackThread::cacheParameters_l();
3884
3885 // FIXME: Relaxed timing because of a certain device that can't meet latency
3886 // Should be reduced to 2x after the vendor fixes the driver issue
3887 // increase threshold again due to low power audio mode. The way this warning
3888 // threshold is calculated and its usefulness should be reconsidered anyway.
3889 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
3890}
3891
3892// ----------------------------------------------------------------------------
3893
3894AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3895 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
3896 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
3897 // mLeftVolFloat, mRightVolFloat
3898{
3899}
3900
Eric Laurentbfb1b832013-01-07 09:53:42 -08003901AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3902 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
3903 ThreadBase::type_t type)
3904 : PlaybackThread(audioFlinger, output, id, device, type)
3905 // mLeftVolFloat, mRightVolFloat
3906{
3907}
3908
Eric Laurent81784c32012-11-19 14:55:58 -08003909AudioFlinger::DirectOutputThread::~DirectOutputThread()
3910{
3911}
3912
Eric Laurentbfb1b832013-01-07 09:53:42 -08003913void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
3914{
3915 audio_track_cblk_t* cblk = track->cblk();
3916 float left, right;
3917
3918 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
3919 left = right = 0;
3920 } else {
3921 float typeVolume = mStreamTypes[track->streamType()].volume;
3922 float v = mMasterVolume * typeVolume;
3923 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07003924 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
3925 left = float_from_gain(gain_minifloat_unpack_left(vlr));
3926 if (left > GAIN_FLOAT_UNITY) {
3927 left = GAIN_FLOAT_UNITY;
3928 }
3929 left *= v;
3930 right = float_from_gain(gain_minifloat_unpack_right(vlr));
3931 if (right > GAIN_FLOAT_UNITY) {
3932 right = GAIN_FLOAT_UNITY;
3933 }
3934 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003935 }
3936
3937 if (lastTrack) {
3938 if (left != mLeftVolFloat || right != mRightVolFloat) {
3939 mLeftVolFloat = left;
3940 mRightVolFloat = right;
3941
3942 // Convert volumes from float to 8.24
3943 uint32_t vl = (uint32_t)(left * (1 << 24));
3944 uint32_t vr = (uint32_t)(right * (1 << 24));
3945
3946 // Delegate volume control to effect in track effect chain if needed
3947 // only one effect chain can be present on DirectOutputThread, so if
3948 // there is one, the track is connected to it
3949 if (!mEffectChains.isEmpty()) {
3950 mEffectChains[0]->setVolume_l(&vl, &vr);
3951 left = (float)vl / (1 << 24);
3952 right = (float)vr / (1 << 24);
3953 }
3954 if (mOutput->stream->set_volume) {
3955 mOutput->stream->set_volume(mOutput->stream, left, right);
3956 }
3957 }
3958 }
3959}
3960
3961
Eric Laurent81784c32012-11-19 14:55:58 -08003962AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
3963 Vector< sp<Track> > *tracksToRemove
3964)
3965{
Eric Laurentd595b7c2013-04-03 17:27:56 -07003966 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08003967 mixer_state mixerStatus = MIXER_IDLE;
3968
3969 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07003970 for (size_t i = 0; i < count; i++) {
3971 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003972 // The track died recently
3973 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003974 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08003975 }
3976
3977 Track* const track = t.get();
3978 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07003979 // Only consider last track started for volume and mixer state control.
3980 // In theory an older track could underrun and restart after the new one starts
3981 // but as we only care about the transition phase between two tracks on a
3982 // direct output, it is not a problem to ignore the underrun case.
3983 sp<Track> l = mLatestActiveTrack.promote();
3984 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08003985
3986 // The first time a track is added we wait
3987 // for all its buffers to be filled before processing it
3988 uint32_t minFrames;
Eric Laurentab5cdba2014-06-09 17:22:27 -07003989 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003990 minFrames = mNormalFrameCount;
3991 } else {
3992 minFrames = 1;
3993 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003994
Eric Laurentab5cdba2014-06-09 17:22:27 -07003995 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
3996 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08003997 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003998 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08003999
4000 if (track->mFillingUpStatus == Track::FS_FILLED) {
4001 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004002 // make sure processVolume_l() will apply new volume even if 0
4003 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurent81784c32012-11-19 14:55:58 -08004004 if (track->mState == TrackBase::RESUMING) {
4005 track->mState = TrackBase::ACTIVE;
4006 }
4007 }
4008
4009 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004010 processVolume_l(track, last);
4011 if (last) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004012 // reset retry count
4013 track->mRetryCount = kMaxTrackRetriesDirect;
4014 mActiveTrack = t;
4015 mixerStatus = MIXER_TRACKS_READY;
4016 }
Eric Laurent81784c32012-11-19 14:55:58 -08004017 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004018 // clear effect chain input buffer if the last active track started underruns
4019 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07004020 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004021 mEffectChains[0]->clearInputBuffer();
4022 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004023 if (track->isStopping_1()) {
4024 track->mState = TrackBase::STOPPING_2;
4025 }
4026 if ((track->sharedBuffer() != 0) || track->isStopped() ||
4027 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004028 // We have consumed all the buffers of this track.
4029 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07004030 size_t audioHALFrames;
4031 if (audio_is_linear_pcm(mFormat)) {
4032 audioHALFrames = (latency_l() * mSampleRate) / 1000;
4033 } else {
4034 audioHALFrames = 0;
4035 }
4036
Eric Laurent81784c32012-11-19 14:55:58 -08004037 size_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07004038 if (mStandby || !last ||
4039 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004040 if (track->isStopping_2()) {
4041 track->mState = TrackBase::STOPPED;
4042 }
Eric Laurent81784c32012-11-19 14:55:58 -08004043 if (track->isStopped()) {
4044 track->reset();
4045 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004046 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08004047 }
4048 } else {
4049 // No buffers for this track. Give it a few chances to
4050 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07004051 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08004052 if (--(track->mRetryCount) <= 0) {
4053 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07004054 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004055 // indicate to client process that the track was disabled because of underrun;
4056 // it will then automatically call start() when data is available
4057 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004058 } else if (last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004059 mixerStatus = MIXER_TRACKS_ENABLED;
4060 }
4061 }
4062 }
4063 }
4064
Eric Laurent81784c32012-11-19 14:55:58 -08004065 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004066 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004067
4068 return mixerStatus;
4069}
4070
4071void AudioFlinger::DirectOutputThread::threadLoop_mix()
4072{
Eric Laurent81784c32012-11-19 14:55:58 -08004073 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08004074 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004075 // output audio to hardware
4076 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07004077 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004078 buffer.frameCount = frameCount;
4079 mActiveTrack->getNextBuffer(&buffer);
Glenn Kastenfa319e62013-07-29 17:17:38 -07004080 if (buffer.raw == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08004081 memset(curBuf, 0, frameCount * mFrameSize);
4082 break;
4083 }
4084 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
4085 frameCount -= buffer.frameCount;
4086 curBuf += buffer.frameCount * mFrameSize;
4087 mActiveTrack->releaseBuffer(&buffer);
4088 }
Andy Hung2098f272014-02-27 14:00:06 -08004089 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004090 sleepTime = 0;
4091 standbyTime = systemTime() + standbyDelay;
4092 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004093}
4094
4095void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
4096{
4097 if (sleepTime == 0) {
4098 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4099 sleepTime = activeSleepTime;
4100 } else {
4101 sleepTime = idleSleepTime;
4102 }
4103 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08004104 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004105 sleepTime = 0;
4106 }
4107}
4108
4109// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004110int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Andy Hunge8a1ced2014-05-09 15:02:21 -07004111 audio_format_t format __unused, int sessionId __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004112{
4113 return 0;
4114}
4115
4116// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004117void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004118{
4119}
4120
Eric Laurent10351942014-05-08 18:49:52 -07004121// checkForNewParameter_l() must be called with ThreadBase::mLock held
4122bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
4123 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004124{
4125 bool reconfig = false;
4126
Eric Laurent10351942014-05-08 18:49:52 -07004127 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004128
Eric Laurent10351942014-05-08 18:49:52 -07004129 AudioParameter param = AudioParameter(keyValuePair);
4130 int value;
4131 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4132 // forward device change to effects that have requested to be
4133 // aware of attached audio device.
4134 if (value != AUDIO_DEVICE_NONE) {
4135 mOutDevice = value;
4136 for (size_t i = 0; i < mEffectChains.size(); i++) {
4137 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07004138 }
4139 }
Eric Laurent81784c32012-11-19 14:55:58 -08004140 }
Eric Laurent10351942014-05-08 18:49:52 -07004141 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4142 // do not accept frame count changes if tracks are open as the track buffer
4143 // size depends on frame count and correct behavior would not be garantied
4144 // if frame count is changed after track creation
4145 if (!mTracks.isEmpty()) {
4146 status = INVALID_OPERATION;
4147 } else {
4148 reconfig = true;
4149 }
4150 }
4151 if (status == NO_ERROR) {
4152 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4153 keyValuePair.string());
4154 if (!mStandby && status == INVALID_OPERATION) {
4155 mOutput->stream->common.standby(&mOutput->stream->common);
4156 mStandby = true;
4157 mBytesWritten = 0;
4158 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4159 keyValuePair.string());
4160 }
4161 if (status == NO_ERROR && reconfig) {
4162 readOutputParameters_l();
4163 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
4164 }
4165 }
4166
Eric Laurent81784c32012-11-19 14:55:58 -08004167 return reconfig;
4168}
4169
4170uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
4171{
4172 uint32_t time;
4173 if (audio_is_linear_pcm(mFormat)) {
4174 time = PlaybackThread::activeSleepTimeUs();
4175 } else {
4176 time = 10000;
4177 }
4178 return time;
4179}
4180
4181uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
4182{
4183 uint32_t time;
4184 if (audio_is_linear_pcm(mFormat)) {
4185 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
4186 } else {
4187 time = 10000;
4188 }
4189 return time;
4190}
4191
4192uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
4193{
4194 uint32_t time;
4195 if (audio_is_linear_pcm(mFormat)) {
4196 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
4197 } else {
4198 time = 10000;
4199 }
4200 return time;
4201}
4202
4203void AudioFlinger::DirectOutputThread::cacheParameters_l()
4204{
4205 PlaybackThread::cacheParameters_l();
4206
4207 // use shorter standby delay as on normal output to release
4208 // hardware resources as soon as possible
Eric Laurent972a1732013-09-04 09:42:59 -07004209 if (audio_is_linear_pcm(mFormat)) {
4210 standbyDelay = microseconds(activeSleepTime*2);
4211 } else {
4212 standbyDelay = kOffloadStandbyDelayNs;
4213 }
Eric Laurent81784c32012-11-19 14:55:58 -08004214}
4215
4216// ----------------------------------------------------------------------------
4217
Eric Laurentbfb1b832013-01-07 09:53:42 -08004218AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07004219 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004220 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07004221 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07004222 mWriteAckSequence(0),
4223 mDrainSequence(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004224{
4225}
4226
4227AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
4228{
4229}
4230
4231void AudioFlinger::AsyncCallbackThread::onFirstRef()
4232{
4233 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
4234}
4235
4236bool AudioFlinger::AsyncCallbackThread::threadLoop()
4237{
4238 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004239 uint32_t writeAckSequence;
4240 uint32_t drainSequence;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004241
4242 {
4243 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08004244 while (!((mWriteAckSequence & 1) ||
4245 (mDrainSequence & 1) ||
4246 exitPending())) {
4247 mWaitWorkCV.wait(mLock);
4248 }
4249
Eric Laurentbfb1b832013-01-07 09:53:42 -08004250 if (exitPending()) {
4251 break;
4252 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004253 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
4254 mWriteAckSequence, mDrainSequence);
4255 writeAckSequence = mWriteAckSequence;
4256 mWriteAckSequence &= ~1;
4257 drainSequence = mDrainSequence;
4258 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004259 }
4260 {
Eric Laurent4de95592013-09-26 15:28:21 -07004261 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
4262 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004263 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004264 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004265 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004266 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004267 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004268 }
4269 }
4270 }
4271 }
4272 return false;
4273}
4274
4275void AudioFlinger::AsyncCallbackThread::exit()
4276{
4277 ALOGV("AsyncCallbackThread::exit");
4278 Mutex::Autolock _l(mLock);
4279 requestExit();
4280 mWaitWorkCV.broadcast();
4281}
4282
Eric Laurent3b4529e2013-09-05 18:09:19 -07004283void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004284{
4285 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004286 // bit 0 is cleared
4287 mWriteAckSequence = sequence << 1;
4288}
4289
4290void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
4291{
4292 Mutex::Autolock _l(mLock);
4293 // ignore unexpected callbacks
4294 if (mWriteAckSequence & 2) {
4295 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004296 mWaitWorkCV.signal();
4297 }
4298}
4299
Eric Laurent3b4529e2013-09-05 18:09:19 -07004300void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004301{
4302 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004303 // bit 0 is cleared
4304 mDrainSequence = sequence << 1;
4305}
4306
4307void AudioFlinger::AsyncCallbackThread::resetDraining()
4308{
4309 Mutex::Autolock _l(mLock);
4310 // ignore unexpected callbacks
4311 if (mDrainSequence & 2) {
4312 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004313 mWaitWorkCV.signal();
4314 }
4315}
4316
4317
4318// ----------------------------------------------------------------------------
4319AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
4320 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
4321 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD),
4322 mHwPaused(false),
Eric Laurentea0fade2013-10-04 16:23:48 -07004323 mFlushPending(false),
Eric Laurentd7e59222013-11-15 12:02:28 -08004324 mPausedBytesRemaining(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004325{
Eric Laurentfd477972013-10-25 18:10:40 -07004326 //FIXME: mStandby should be set to true by ThreadBase constructor
4327 mStandby = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004328}
4329
Eric Laurentbfb1b832013-01-07 09:53:42 -08004330void AudioFlinger::OffloadThread::threadLoop_exit()
4331{
4332 if (mFlushPending || mHwPaused) {
4333 // If a flush is pending or track was paused, just discard buffered data
4334 flushHw_l();
4335 } else {
4336 mMixerStatus = MIXER_DRAIN_ALL;
4337 threadLoop_drain();
4338 }
Uday Gupta56604aa2014-05-13 11:19:17 -07004339 if (mUseAsyncWrite) {
4340 ALOG_ASSERT(mCallbackThread != 0);
4341 mCallbackThread->exit();
4342 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004343 PlaybackThread::threadLoop_exit();
4344}
4345
4346AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
4347 Vector< sp<Track> > *tracksToRemove
4348)
4349{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004350 size_t count = mActiveTracks.size();
4351
4352 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07004353 bool doHwPause = false;
4354 bool doHwResume = false;
4355
Eric Laurentede6c3b2013-09-19 14:37:46 -07004356 ALOGV("OffloadThread::prepareTracks_l active tracks %d", count);
4357
Eric Laurentbfb1b832013-01-07 09:53:42 -08004358 // find out which tracks need to be processed
4359 for (size_t i = 0; i < count; i++) {
4360 sp<Track> t = mActiveTracks[i].promote();
4361 // The track died recently
4362 if (t == 0) {
4363 continue;
4364 }
4365 Track* const track = t.get();
4366 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07004367 // Only consider last track started for volume and mixer state control.
4368 // In theory an older track could underrun and restart after the new one starts
4369 // but as we only care about the transition phase between two tracks on a
4370 // direct output, it is not a problem to ignore the underrun case.
4371 sp<Track> l = mLatestActiveTrack.promote();
4372 bool last = l.get() == track;
4373
Haynes Mathew George7844f672014-01-15 12:32:55 -08004374 if (track->isInvalid()) {
4375 ALOGW("An invalidated track shouldn't be in active list");
4376 tracksToRemove->add(track);
4377 continue;
4378 }
4379
4380 if (track->mState == TrackBase::IDLE) {
4381 ALOGW("An idle track shouldn't be in active list");
4382 continue;
4383 }
4384
Eric Laurentbfb1b832013-01-07 09:53:42 -08004385 if (track->isPausing()) {
4386 track->setPaused();
4387 if (last) {
4388 if (!mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07004389 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004390 mHwPaused = true;
4391 }
4392 // If we were part way through writing the mixbuffer to
4393 // the HAL we must save this until we resume
4394 // BUG - this will be wrong if a different track is made active,
4395 // in that case we want to discard the pending data in the
4396 // mixbuffer and tell the client to present it again when the
4397 // track is resumed
4398 mPausedWriteLength = mCurrentWriteLength;
4399 mPausedBytesRemaining = mBytesRemaining;
4400 mBytesRemaining = 0; // stop writing
4401 }
4402 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08004403 } else if (track->isFlushPending()) {
4404 track->flushAck();
4405 if (last) {
4406 mFlushPending = true;
4407 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08004408 } else if (track->isResumePending()){
4409 track->resumeAck();
4410 if (last) {
4411 if (mPausedBytesRemaining) {
4412 // Need to continue write that was interrupted
4413 mCurrentWriteLength = mPausedWriteLength;
4414 mBytesRemaining = mPausedBytesRemaining;
4415 mPausedBytesRemaining = 0;
4416 }
4417 if (mHwPaused) {
4418 doHwResume = true;
4419 mHwPaused = false;
4420 // threadLoop_mix() will handle the case that we need to
4421 // resume an interrupted write
4422 }
4423 // enable write to audio HAL
4424 sleepTime = 0;
4425
4426 // Do not handle new data in this iteration even if track->framesReady()
4427 mixerStatus = MIXER_TRACKS_ENABLED;
4428 }
4429 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07004430 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004431 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004432 if (track->mFillingUpStatus == Track::FS_FILLED) {
4433 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004434 // make sure processVolume_l() will apply new volume even if 0
4435 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004436 }
4437
4438 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08004439 sp<Track> previousTrack = mPreviousTrack.promote();
4440 if (previousTrack != 0) {
4441 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08004442 // Flush any data still being written from last track
4443 mBytesRemaining = 0;
4444 if (mPausedBytesRemaining) {
4445 // Last track was paused so we also need to flush saved
4446 // mixbuffer state and invalidate track so that it will
4447 // re-submit that unwritten data when it is next resumed
4448 mPausedBytesRemaining = 0;
4449 // Invalidate is a bit drastic - would be more efficient
4450 // to have a flag to tell client that some of the
4451 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08004452 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004453 }
4454 // flush data already sent to the DSP if changing audio session as audio
4455 // comes from a different source. Also invalidate previous track to force a
4456 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08004457 if (previousTrack->sessionId() != track->sessionId()) {
4458 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004459 }
4460 }
4461 }
4462 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004463 // reset retry count
4464 track->mRetryCount = kMaxTrackRetriesOffload;
4465 mActiveTrack = t;
4466 mixerStatus = MIXER_TRACKS_READY;
4467 }
4468 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004469 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004470 if (track->isStopping_1()) {
4471 // Hardware buffer can hold a large amount of audio so we must
4472 // wait for all current track's data to drain before we say
4473 // that the track is stopped.
4474 if (mBytesRemaining == 0) {
4475 // Only start draining when all data in mixbuffer
4476 // has been written
4477 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
4478 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004479 // do not drain if no data was ever sent to HAL (mStandby == true)
4480 if (last && !mStandby) {
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004481 // do not modify drain sequence if we are already draining. This happens
4482 // when resuming from pause after drain.
4483 if ((mDrainSequence & 1) == 0) {
4484 sleepTime = 0;
4485 standbyTime = systemTime() + standbyDelay;
4486 mixerStatus = MIXER_DRAIN_TRACK;
4487 mDrainSequence += 2;
4488 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004489 if (mHwPaused) {
4490 // It is possible to move from PAUSED to STOPPING_1 without
4491 // a resume so we must ensure hardware is running
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004492 doHwResume = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004493 mHwPaused = false;
4494 }
4495 }
4496 }
4497 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004498 // Drain has completed or we are in standby, signal presentation complete
4499 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004500 track->mState = TrackBase::STOPPED;
4501 size_t audioHALFrames =
4502 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
4503 size_t framesWritten =
Eric Laurent665470b2014-07-03 16:37:08 -07004504 mBytesWritten / audio_stream_out_frame_size(mOutput->stream);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004505 track->presentationComplete(framesWritten, audioHALFrames);
4506 track->reset();
4507 tracksToRemove->add(track);
4508 }
4509 } else {
4510 // No buffers for this track. Give it a few chances to
4511 // fill a buffer, then remove it from active list.
4512 if (--(track->mRetryCount) <= 0) {
4513 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
4514 track->name());
4515 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004516 // indicate to client process that the track was disabled because of underrun;
4517 // it will then automatically call start() when data is available
4518 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004519 } else if (last){
4520 mixerStatus = MIXER_TRACKS_ENABLED;
4521 }
4522 }
4523 }
4524 // compute volume for this track
4525 processVolume_l(track, last);
4526 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004527
Eric Laurentea0fade2013-10-04 16:23:48 -07004528 // make sure the pause/flush/resume sequence is executed in the right order.
4529 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4530 // before flush and then resume HW. This can happen in case of pause/flush/resume
4531 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07004532 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurent972a1732013-09-04 09:42:59 -07004533 mOutput->stream->pause(mOutput->stream);
4534 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004535 if (mFlushPending) {
4536 flushHw_l();
4537 mFlushPending = false;
4538 }
Eric Laurentfd477972013-10-25 18:10:40 -07004539 if (!mStandby && doHwResume) {
Eric Laurent972a1732013-09-04 09:42:59 -07004540 mOutput->stream->resume(mOutput->stream);
4541 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004542
Eric Laurentbfb1b832013-01-07 09:53:42 -08004543 // remove all the tracks that need to be...
4544 removeTracks_l(*tracksToRemove);
4545
4546 return mixerStatus;
4547}
4548
Eric Laurentbfb1b832013-01-07 09:53:42 -08004549// must be called with thread mutex locked
4550bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
4551{
Eric Laurent3b4529e2013-09-05 18:09:19 -07004552 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
4553 mWriteAckSequence, mDrainSequence);
4554 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004555 return true;
4556 }
4557 return false;
4558}
4559
4560// must be called with thread mutex locked
4561bool AudioFlinger::OffloadThread::shouldStandby_l()
4562{
Glenn Kastene6f35b12013-08-19 09:58:50 -07004563 bool trackPaused = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004564
4565 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4566 // after a timeout and we will enter standby then.
4567 if (mTracks.size() > 0) {
Glenn Kastene6f35b12013-08-19 09:58:50 -07004568 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004569 }
4570
Glenn Kastene6f35b12013-08-19 09:58:50 -07004571 return !mStandby && !trackPaused;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004572}
4573
4574
4575bool AudioFlinger::OffloadThread::waitingAsyncCallback()
4576{
4577 Mutex::Autolock _l(mLock);
4578 return waitingAsyncCallback_l();
4579}
4580
4581void AudioFlinger::OffloadThread::flushHw_l()
4582{
4583 mOutput->stream->flush(mOutput->stream);
4584 // Flush anything still waiting in the mixbuffer
4585 mCurrentWriteLength = 0;
4586 mBytesRemaining = 0;
4587 mPausedWriteLength = 0;
4588 mPausedBytesRemaining = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08004589 mHwPaused = false;
4590
Eric Laurentbfb1b832013-01-07 09:53:42 -08004591 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004592 // discard any pending drain or write ack by incrementing sequence
4593 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4594 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004595 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004596 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4597 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004598 }
4599}
4600
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08004601void AudioFlinger::OffloadThread::onAddNewTrack_l()
4602{
4603 sp<Track> previousTrack = mPreviousTrack.promote();
4604 sp<Track> latestTrack = mLatestActiveTrack.promote();
4605
4606 if (previousTrack != 0 && latestTrack != 0 &&
4607 (previousTrack->sessionId() != latestTrack->sessionId())) {
4608 mFlushPending = true;
4609 }
4610 PlaybackThread::onAddNewTrack_l();
4611}
4612
Eric Laurentbfb1b832013-01-07 09:53:42 -08004613// ----------------------------------------------------------------------------
4614
Eric Laurent81784c32012-11-19 14:55:58 -08004615AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
4616 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
4617 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
4618 DUPLICATING),
4619 mWaitTimeMs(UINT_MAX)
4620{
4621 addOutputTrack(mainThread);
4622}
4623
4624AudioFlinger::DuplicatingThread::~DuplicatingThread()
4625{
4626 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4627 mOutputTracks[i]->destroy();
4628 }
4629}
4630
4631void AudioFlinger::DuplicatingThread::threadLoop_mix()
4632{
4633 // mix buffers...
4634 if (outputsReady(outputTracks)) {
4635 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
4636 } else {
Andy Hung25c2dac2014-02-27 14:56:00 -08004637 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004638 }
4639 sleepTime = 0;
4640 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08004641 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004642 standbyTime = systemTime() + standbyDelay;
4643}
4644
4645void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
4646{
4647 if (sleepTime == 0) {
4648 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4649 sleepTime = activeSleepTime;
4650 } else {
4651 sleepTime = idleSleepTime;
4652 }
4653 } else if (mBytesWritten != 0) {
4654 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4655 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08004656 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004657 } else {
4658 // flush remaining overflow buffers in output tracks
4659 writeFrames = 0;
4660 }
4661 sleepTime = 0;
4662 }
4663}
4664
Eric Laurentbfb1b832013-01-07 09:53:42 -08004665ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004666{
4667 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung010a1a12014-03-13 13:57:33 -07004668 // We convert the duplicating thread format to AUDIO_FORMAT_PCM_16_BIT
4669 // for delivery downstream as needed. This in-place conversion is safe as
4670 // AUDIO_FORMAT_PCM_16_BIT is smaller than any other supported format
4671 // (AUDIO_FORMAT_PCM_8_BIT is not allowed here).
4672 if (mFormat != AUDIO_FORMAT_PCM_16_BIT) {
4673 memcpy_by_audio_format(mSinkBuffer, AUDIO_FORMAT_PCM_16_BIT,
4674 mSinkBuffer, mFormat, writeFrames * mChannelCount);
4675 }
4676 outputTracks[i]->write(reinterpret_cast<int16_t*>(mSinkBuffer), writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08004677 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07004678 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08004679 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004680}
4681
4682void AudioFlinger::DuplicatingThread::threadLoop_standby()
4683{
4684 // DuplicatingThread implements standby by stopping all tracks
4685 for (size_t i = 0; i < outputTracks.size(); i++) {
4686 outputTracks[i]->stop();
4687 }
4688}
4689
4690void AudioFlinger::DuplicatingThread::saveOutputTracks()
4691{
4692 outputTracks = mOutputTracks;
4693}
4694
4695void AudioFlinger::DuplicatingThread::clearOutputTracks()
4696{
4697 outputTracks.clear();
4698}
4699
4700void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
4701{
4702 Mutex::Autolock _l(mLock);
4703 // FIXME explain this formula
4704 size_t frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
Andy Hung010a1a12014-03-13 13:57:33 -07004705 // OutputTrack is forced to AUDIO_FORMAT_PCM_16_BIT regardless of mFormat
4706 // due to current usage case and restrictions on the AudioBufferProvider.
4707 // Actual buffer conversion is done in threadLoop_write().
4708 //
4709 // TODO: This may change in the future, depending on multichannel
4710 // (and non int16_t*) support on AF::PlaybackThread::OutputTrack
Eric Laurent81784c32012-11-19 14:55:58 -08004711 OutputTrack *outputTrack = new OutputTrack(thread,
4712 this,
4713 mSampleRate,
Andy Hung010a1a12014-03-13 13:57:33 -07004714 AUDIO_FORMAT_PCM_16_BIT,
Eric Laurent81784c32012-11-19 14:55:58 -08004715 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004716 frameCount,
4717 IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08004718 if (outputTrack->cblk() != NULL) {
4719 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
4720 mOutputTracks.add(outputTrack);
4721 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
4722 updateWaitTime_l();
4723 }
4724}
4725
4726void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
4727{
4728 Mutex::Autolock _l(mLock);
4729 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4730 if (mOutputTracks[i]->thread() == thread) {
4731 mOutputTracks[i]->destroy();
4732 mOutputTracks.removeAt(i);
4733 updateWaitTime_l();
4734 return;
4735 }
4736 }
4737 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
4738}
4739
4740// caller must hold mLock
4741void AudioFlinger::DuplicatingThread::updateWaitTime_l()
4742{
4743 mWaitTimeMs = UINT_MAX;
4744 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4745 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
4746 if (strong != 0) {
4747 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4748 if (waitTimeMs < mWaitTimeMs) {
4749 mWaitTimeMs = waitTimeMs;
4750 }
4751 }
4752 }
4753}
4754
4755
4756bool AudioFlinger::DuplicatingThread::outputsReady(
4757 const SortedVector< sp<OutputTrack> > &outputTracks)
4758{
4759 for (size_t i = 0; i < outputTracks.size(); i++) {
4760 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
4761 if (thread == 0) {
4762 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
4763 outputTracks[i].get());
4764 return false;
4765 }
4766 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4767 // see note at standby() declaration
4768 if (playbackThread->standby() && !playbackThread->isSuspended()) {
4769 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
4770 thread.get());
4771 return false;
4772 }
4773 }
4774 return true;
4775}
4776
4777uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
4778{
4779 return (mWaitTimeMs * 1000) / 2;
4780}
4781
4782void AudioFlinger::DuplicatingThread::cacheParameters_l()
4783{
4784 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
4785 updateWaitTime_l();
4786
4787 MixerThread::cacheParameters_l();
4788}
4789
4790// ----------------------------------------------------------------------------
4791// Record
4792// ----------------------------------------------------------------------------
4793
4794AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4795 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08004796 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08004797 audio_devices_t outDevice,
Glenn Kasten46909e72013-02-26 09:20:22 -08004798 audio_devices_t inDevice
4799#ifdef TEE_SINK
4800 , const sp<NBAIO_Sink>& teeSink
4801#endif
4802 ) :
Eric Laurentd3922f72013-02-01 17:57:04 -08004803 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD),
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004804 mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
Glenn Kastendeca2ae2014-02-07 10:25:56 -08004805 // mRsmpInFrames and mRsmpInFramesP2 are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08004806 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08004807#ifdef TEE_SINK
4808 , mTeeSink(teeSink)
4809#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07004810 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
4811 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07004812 // mFastCapture below
4813 , mFastCaptureFutex(0)
4814 // mInputSource
4815 // mPipeSink
4816 // mPipeSource
4817 , mPipeFramesP2(0)
4818 // mPipeMemory
4819 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07004820 , mFastTrackAvail(false)
Eric Laurent81784c32012-11-19 14:55:58 -08004821{
4822 snprintf(mName, kNameLength, "AudioIn_%X", id);
Glenn Kasten481fb672013-09-30 14:39:28 -07004823 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mName);
Eric Laurent81784c32012-11-19 14:55:58 -08004824
Glenn Kastendeca2ae2014-02-07 10:25:56 -08004825 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07004826
4827 // create an NBAIO source for the HAL input stream, and negotiate
4828 mInputSource = new AudioStreamInSource(input->stream);
4829 size_t numCounterOffers = 0;
4830 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
4831 ssize_t index = mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
4832 ALOG_ASSERT(index == 0);
4833
4834 // initialize fast capture depending on configuration
4835 bool initFastCapture;
4836 switch (kUseFastCapture) {
4837 case FastCapture_Never:
4838 initFastCapture = false;
4839 break;
4840 case FastCapture_Always:
4841 initFastCapture = true;
4842 break;
4843 case FastCapture_Static:
4844 uint32_t primaryOutputSampleRate;
4845 {
4846 AutoMutex _l(audioFlinger->mHardwareLock);
4847 primaryOutputSampleRate = audioFlinger->mPrimaryOutputSampleRate;
4848 }
4849 initFastCapture =
4850 // either capture sample rate is same as (a reasonable) primary output sample rate
4851 (((primaryOutputSampleRate == 44100 || primaryOutputSampleRate == 48000) &&
4852 (mSampleRate == primaryOutputSampleRate)) ||
4853 // or primary output sample rate is unknown, and capture sample rate is reasonable
4854 ((primaryOutputSampleRate == 0) &&
4855 ((mSampleRate == 44100 || mSampleRate == 48000)))) &&
Glenn Kasten9f81de32014-07-27 15:02:23 -07004856 // and the buffer size is < 12 ms
4857 (mFrameCount * 1000) / mSampleRate < 12;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07004858 break;
4859 // case FastCapture_Dynamic:
4860 }
4861
4862 if (initFastCapture) {
4863 // create a Pipe for FastMixer to write to, and for us and fast tracks to read from
4864 NBAIO_Format format = mInputSource->format();
Glenn Kasten49d00ad2014-07-21 11:22:03 -07004865 size_t pipeFramesP2 = roundup(mSampleRate / 25); // double-buffering of 20 ms each
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07004866 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
4867 void *pipeBuffer;
4868 const sp<MemoryDealer> roHeap(readOnlyHeap());
4869 sp<IMemory> pipeMemory;
4870 if ((roHeap == 0) ||
4871 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
4872 (pipeBuffer = pipeMemory->pointer()) == NULL) {
4873 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
4874 goto failed;
4875 }
4876 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
4877 memset(pipeBuffer, 0, pipeSize);
4878 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
4879 const NBAIO_Format offers[1] = {format};
4880 size_t numCounterOffers = 0;
4881 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
4882 ALOG_ASSERT(index == 0);
4883 mPipeSink = pipe;
4884 PipeReader *pipeReader = new PipeReader(*pipe);
4885 numCounterOffers = 0;
4886 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
4887 ALOG_ASSERT(index == 0);
4888 mPipeSource = pipeReader;
4889 mPipeFramesP2 = pipeFramesP2;
4890 mPipeMemory = pipeMemory;
4891
4892 // create fast capture
4893 mFastCapture = new FastCapture();
4894 FastCaptureStateQueue *sq = mFastCapture->sq();
4895#ifdef STATE_QUEUE_DUMP
4896 // FIXME
4897#endif
4898 FastCaptureState *state = sq->begin();
4899 state->mCblk = NULL;
4900 state->mInputSource = mInputSource.get();
4901 state->mInputSourceGen++;
4902 state->mPipeSink = pipe;
4903 state->mPipeSinkGen++;
4904 state->mFrameCount = mFrameCount;
4905 state->mCommand = FastCaptureState::COLD_IDLE;
4906 // already done in constructor initialization list
4907 //mFastCaptureFutex = 0;
4908 state->mColdFutexAddr = &mFastCaptureFutex;
4909 state->mColdGen++;
4910 state->mDumpState = &mFastCaptureDumpState;
4911#ifdef TEE_SINK
4912 // FIXME
4913#endif
4914 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
4915 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
4916 sq->end();
4917 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
4918
4919 // start the fast capture
4920 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
4921 pid_t tid = mFastCapture->getTid();
4922 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
4923 if (err != 0) {
4924 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
4925 kPriorityFastCapture, getpid_cached, tid, err);
4926 }
4927
4928#ifdef AUDIO_WATCHDOG
4929 // FIXME
4930#endif
4931
Glenn Kasten6e6704c2014-07-03 10:20:00 -07004932 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07004933 }
4934failed: ;
4935
4936 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08004937}
4938
4939
4940AudioFlinger::RecordThread::~RecordThread()
4941{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07004942 if (mFastCapture != 0) {
4943 FastCaptureStateQueue *sq = mFastCapture->sq();
4944 FastCaptureState *state = sq->begin();
4945 if (state->mCommand == FastCaptureState::COLD_IDLE) {
4946 int32_t old = android_atomic_inc(&mFastCaptureFutex);
4947 if (old == -1) {
4948 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
4949 }
4950 }
4951 state->mCommand = FastCaptureState::EXIT;
4952 sq->end();
4953 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
4954 mFastCapture->join();
4955 mFastCapture.clear();
4956 }
4957 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07004958 mAudioFlinger->unregisterWriter(mNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08004959 delete[] mRsmpInBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004960}
4961
4962void AudioFlinger::RecordThread::onFirstRef()
4963{
4964 run(mName, PRIORITY_URGENT_AUDIO);
4965}
4966
Eric Laurent81784c32012-11-19 14:55:58 -08004967bool AudioFlinger::RecordThread::threadLoop()
4968{
Eric Laurent81784c32012-11-19 14:55:58 -08004969 nsecs_t lastWarning = 0;
4970
4971 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08004972
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004973reacquire_wakelock:
4974 sp<RecordTrack> activeTrack;
Glenn Kasten2b806402013-11-20 16:37:38 -08004975 int activeTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004976 {
4977 Mutex::Autolock _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08004978 size_t size = mActiveTracks.size();
4979 activeTracksGen = mActiveTracksGen;
4980 if (size > 0) {
4981 // FIXME an arbitrary choice
4982 activeTrack = mActiveTracks[0];
4983 acquireWakeLock_l(activeTrack->uid());
4984 if (size > 1) {
4985 SortedVector<int> tmp;
4986 for (size_t i = 0; i < size; i++) {
4987 tmp.add(mActiveTracks[i]->uid());
4988 }
4989 updateWakeLockUids_l(tmp);
4990 }
4991 } else {
4992 acquireWakeLock_l(-1);
4993 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004994 }
4995
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004996 // used to request a deferred sleep, to be executed later while mutex is unlocked
4997 uint32_t sleepUs = 0;
4998
4999 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005000 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005001 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07005002
Glenn Kasten5edadd42013-08-14 16:30:49 -07005003 // sleep with mutex unlocked
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005004 if (sleepUs > 0) {
5005 usleep(sleepUs);
5006 sleepUs = 0;
Glenn Kasten5edadd42013-08-14 16:30:49 -07005007 }
5008
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005009 // activeTracks accumulates a copy of a subset of mActiveTracks
5010 Vector< sp<RecordTrack> > activeTracks;
5011
Glenn Kasten735f45f2014-08-18 15:51:59 -07005012 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005013 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07005014
Glenn Kasten735f45f2014-08-18 15:51:59 -07005015 // reference to a fast track which is about to be removed
5016 sp<RecordTrack> fastTrackToRemove;
5017
Eric Laurent81784c32012-11-19 14:55:58 -08005018 { // scope for mLock
5019 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08005020
Eric Laurent021cf962014-05-13 10:18:14 -07005021 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005022
Eric Laurent000a4192014-01-29 15:17:32 -08005023 // check exitPending here because checkForNewParameters_l() and
5024 // checkForNewParameters_l() can temporarily release mLock
5025 if (exitPending()) {
5026 break;
5027 }
5028
Glenn Kasten2b806402013-11-20 16:37:38 -08005029 // if no active track(s), then standby and release wakelock
5030 size_t size = mActiveTracks.size();
5031 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07005032 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005033 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08005034 releaseWakeLock_l();
5035 ALOGV("RecordThread: loop stopping");
5036 // go to sleep
5037 mWaitWorkCV.wait(mLock);
5038 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005039 goto reacquire_wakelock;
5040 }
5041
Glenn Kasten2b806402013-11-20 16:37:38 -08005042 if (mActiveTracksGen != activeTracksGen) {
5043 activeTracksGen = mActiveTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005044 SortedVector<int> tmp;
Glenn Kasten2b806402013-11-20 16:37:38 -08005045 for (size_t i = 0; i < size; i++) {
5046 tmp.add(mActiveTracks[i]->uid());
5047 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005048 updateWakeLockUids_l(tmp);
Eric Laurent81784c32012-11-19 14:55:58 -08005049 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005050
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005051 bool doBroadcast = false;
5052 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07005053
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005054 activeTrack = mActiveTracks[i];
5055 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07005056 if (activeTrack->isFastTrack()) {
5057 ALOG_ASSERT(fastTrackToRemove == 0);
5058 fastTrackToRemove = activeTrack;
5059 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005060 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08005061 mActiveTracks.remove(activeTrack);
5062 mActiveTracksGen++;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005063 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07005064 continue;
5065 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005066
5067 TrackBase::track_state activeTrackState = activeTrack->mState;
5068 switch (activeTrackState) {
5069
5070 case TrackBase::PAUSING:
5071 mActiveTracks.remove(activeTrack);
5072 mActiveTracksGen++;
5073 doBroadcast = true;
5074 size--;
5075 continue;
5076
5077 case TrackBase::STARTING_1:
5078 sleepUs = 10000;
5079 i++;
5080 continue;
5081
5082 case TrackBase::STARTING_2:
5083 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005084 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07005085 activeTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005086 break;
5087
5088 case TrackBase::ACTIVE:
5089 break;
5090
5091 case TrackBase::IDLE:
5092 i++;
5093 continue;
5094
5095 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08005096 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07005097 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005098
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005099 activeTracks.add(activeTrack);
5100 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07005101
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005102 if (activeTrack->isFastTrack()) {
5103 ALOG_ASSERT(!mFastTrackAvail);
5104 ALOG_ASSERT(fastTrack == 0);
5105 fastTrack = activeTrack;
5106 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005107 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005108 if (doBroadcast) {
5109 mStartStopCond.broadcast();
5110 }
5111
5112 // sleep if there are no active tracks to process
5113 if (activeTracks.size() == 0) {
5114 if (sleepUs == 0) {
5115 sleepUs = kRecordThreadSleepUs;
5116 }
5117 continue;
5118 }
5119 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07005120
Eric Laurent81784c32012-11-19 14:55:58 -08005121 lockEffectChains_l(effectChains);
5122 }
5123
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005124 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07005125
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005126 size_t size = effectChains.size();
5127 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005128 // thread mutex is not locked, but effect chain is locked
5129 effectChains[i]->process_l();
5130 }
5131
Glenn Kasten735f45f2014-08-18 15:51:59 -07005132 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005133 if (mFastCapture != 0) {
5134 FastCaptureStateQueue *sq = mFastCapture->sq();
5135 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07005136 bool didModify = false;
5137 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005138 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
5139 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
5140 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5141 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5142 if (old == -1) {
5143 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5144 }
5145 }
5146 state->mCommand = FastCaptureState::READ_WRITE;
5147#if 0 // FIXME
5148 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
5149 FastCaptureDumpState::kSamplingNforLowRamDevice : FastMixerDumpState::kSamplingN);
5150#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07005151 didModify = true;
5152 }
5153 audio_track_cblk_t *cblkOld = state->mCblk;
5154 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
5155 if (cblkNew != cblkOld) {
5156 state->mCblk = cblkNew;
5157 // block until acked if removing a fast track
5158 if (cblkOld != NULL) {
5159 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
5160 }
5161 didModify = true;
5162 }
5163 sq->end(didModify);
5164 if (didModify) {
5165 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005166#if 0
5167 if (kUseFastCapture == FastCapture_Dynamic) {
5168 mNormalSource = mPipeSource;
5169 }
5170#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005171 }
5172 }
5173
Glenn Kasten735f45f2014-08-18 15:51:59 -07005174 // now run the fast track destructor with thread mutex unlocked
5175 fastTrackToRemove.clear();
5176
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005177 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
5178 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
5179 // slow, then this RecordThread will overrun by not calling HAL read often enough.
5180 // If destination is non-contiguous, first read past the nominal end of buffer, then
5181 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005182
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005183 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005184 ssize_t framesRead;
5185
5186 // If an NBAIO source is present, use it to read the normal capture's data
5187 if (mPipeSource != 0) {
5188 size_t framesToRead = mBufferSize / mFrameSize;
5189 framesRead = mPipeSource->read(&mRsmpInBuffer[rear * mChannelCount],
5190 framesToRead, AudioBufferProvider::kInvalidPTS);
5191 if (framesRead == 0) {
5192 // since pipe is non-blocking, simulate blocking input
5193 sleepUs = (framesToRead * 1000000LL) / mSampleRate;
5194 }
5195 // otherwise use the HAL / AudioStreamIn directly
5196 } else {
5197 ssize_t bytesRead = mInput->stream->read(mInput->stream,
5198 &mRsmpInBuffer[rear * mChannelCount], mBufferSize);
5199 if (bytesRead < 0) {
5200 framesRead = bytesRead;
5201 } else {
5202 framesRead = bytesRead / mFrameSize;
5203 }
5204 }
5205
5206 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
5207 ALOGE("read failed: framesRead=%d", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005208 // Force input into standby so that it tries to recover at next read attempt
5209 inputStandBy();
5210 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005211 }
5212 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005213 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005214 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005215 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005216
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005217 if (mTeeSink != 0) {
5218 (void) mTeeSink->write(&mRsmpInBuffer[rear * mChannelCount], framesRead);
5219 }
5220 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005221 {
5222 size_t part1 = mRsmpInFramesP2 - rear;
5223 if ((size_t) framesRead > part1) {
5224 memcpy(mRsmpInBuffer, &mRsmpInBuffer[mRsmpInFramesP2 * mChannelCount],
5225 (framesRead - part1) * mFrameSize);
5226 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005227 }
5228 rear = mRsmpInRear += framesRead;
5229
5230 size = activeTracks.size();
5231 // loop over each active track
5232 for (size_t i = 0; i < size; i++) {
5233 activeTrack = activeTracks[i];
5234
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005235 // skip fast tracks, as those are handled directly by FastCapture
5236 if (activeTrack->isFastTrack()) {
5237 continue;
5238 }
5239
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005240 enum {
5241 OVERRUN_UNKNOWN,
5242 OVERRUN_TRUE,
5243 OVERRUN_FALSE
5244 } overrun = OVERRUN_UNKNOWN;
5245
5246 // loop over getNextBuffer to handle circular sink
5247 for (;;) {
5248
5249 activeTrack->mSink.frameCount = ~0;
5250 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
5251 size_t framesOut = activeTrack->mSink.frameCount;
5252 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
5253
5254 int32_t front = activeTrack->mRsmpInFront;
5255 ssize_t filled = rear - front;
5256 size_t framesIn;
5257
5258 if (filled < 0) {
5259 // should not happen, but treat like a massive overrun and re-sync
5260 framesIn = 0;
5261 activeTrack->mRsmpInFront = rear;
5262 overrun = OVERRUN_TRUE;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005263 } else if ((size_t) filled <= mRsmpInFrames) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005264 framesIn = (size_t) filled;
5265 } else {
5266 // client is not keeping up with server, but give it latest data
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005267 framesIn = mRsmpInFrames;
5268 activeTrack->mRsmpInFront = front = rear - framesIn;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005269 overrun = OVERRUN_TRUE;
5270 }
5271
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005272 if (framesOut == 0 || framesIn == 0) {
5273 break;
5274 }
5275
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005276 if (activeTrack->mResampler == NULL) {
5277 // no resampling
5278 if (framesIn > framesOut) {
5279 framesIn = framesOut;
5280 } else {
5281 framesOut = framesIn;
5282 }
5283 int8_t *dst = activeTrack->mSink.i8;
5284 while (framesIn > 0) {
5285 front &= mRsmpInFramesP2 - 1;
5286 size_t part1 = mRsmpInFramesP2 - front;
5287 if (part1 > framesIn) {
5288 part1 = framesIn;
5289 }
5290 int8_t *src = (int8_t *)mRsmpInBuffer + (front * mFrameSize);
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005291 if (mChannelCount == activeTrack->mChannelCount) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005292 memcpy(dst, src, part1 * mFrameSize);
5293 } else if (mChannelCount == 1) {
Glenn Kastencd704212014-07-14 17:26:36 -07005294 upmix_to_stereo_i16_from_mono_i16((int16_t *)dst, (const int16_t *)src,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005295 part1);
5296 } else {
Glenn Kastencd704212014-07-14 17:26:36 -07005297 downmix_to_mono_i16_from_stereo_i16((int16_t *)dst, (const int16_t *)src,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005298 part1);
5299 }
5300 dst += part1 * activeTrack->mFrameSize;
5301 front += part1;
5302 framesIn -= part1;
5303 }
5304 activeTrack->mRsmpInFront += framesOut;
5305
5306 } else {
5307 // resampling
5308 // FIXME framesInNeeded should really be part of resampler API, and should
5309 // depend on the SRC ratio
5310 // to keep mRsmpInBuffer full so resampler always has sufficient input
5311 size_t framesInNeeded;
5312 // FIXME only re-calculate when it changes, and optimize for common ratios
Andy Hung8661aaf2014-07-28 14:38:41 -07005313 // Do not precompute in/out because floating point is not associative
5314 // e.g. a*b/c != a*(b/c).
5315 const double in(mSampleRate);
5316 const double out(activeTrack->mSampleRate);
5317 framesInNeeded = ceil(framesOut * in / out) + 1;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005318 ALOGV("need %u frames in to produce %u out given in/out ratio of %.4g",
Andy Hung8661aaf2014-07-28 14:38:41 -07005319 framesInNeeded, framesOut, in / out);
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005320 // Although we theoretically have framesIn in circular buffer, some of those are
5321 // unreleased frames, and thus must be discounted for purpose of budgeting.
5322 size_t unreleased = activeTrack->mRsmpInUnrel;
5323 framesIn = framesIn > unreleased ? framesIn - unreleased : 0;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005324 if (framesIn < framesInNeeded) {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005325 ALOGV("not enough to resample: have %u frames in but need %u in to "
5326 "produce %u out given in/out ratio of %.4g",
Andy Hung8661aaf2014-07-28 14:38:41 -07005327 framesIn, framesInNeeded, framesOut, in / out);
5328 size_t newFramesOut = framesIn > 0 ? floor((framesIn - 1) * out / in) : 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005329 LOG_ALWAYS_FATAL_IF(newFramesOut >= framesOut);
5330 if (newFramesOut == 0) {
5331 break;
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005332 }
Andy Hung8661aaf2014-07-28 14:38:41 -07005333 framesInNeeded = ceil(newFramesOut * in / out) + 1;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005334 ALOGV("now need %u frames in to produce %u out given out/in ratio of %.4g",
Andy Hung8661aaf2014-07-28 14:38:41 -07005335 framesInNeeded, newFramesOut, out / in);
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005336 LOG_ALWAYS_FATAL_IF(framesIn < framesInNeeded);
5337 ALOGV("success 2: have %u frames in and need %u in to produce %u out "
5338 "given in/out ratio of %.4g",
Andy Hung8661aaf2014-07-28 14:38:41 -07005339 framesIn, framesInNeeded, newFramesOut, in / out);
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005340 framesOut = newFramesOut;
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005341 } else {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005342 ALOGV("success 1: have %u in and need %u in to produce %u out "
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005343 "given in/out ratio of %.4g",
Andy Hung8661aaf2014-07-28 14:38:41 -07005344 framesIn, framesInNeeded, framesOut, in / out);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005345 }
5346
5347 // reallocate mRsmpOutBuffer as needed; we will grow but never shrink
5348 if (activeTrack->mRsmpOutFrameCount < framesOut) {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005349 // FIXME why does each track need it's own mRsmpOutBuffer? can't they share?
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005350 delete[] activeTrack->mRsmpOutBuffer;
5351 // resampler always outputs stereo
5352 activeTrack->mRsmpOutBuffer = new int32_t[framesOut * FCC_2];
5353 activeTrack->mRsmpOutFrameCount = framesOut;
5354 }
5355
5356 // resampler accumulates, but we only have one source track
5357 memset(activeTrack->mRsmpOutBuffer, 0, framesOut * FCC_2 * sizeof(int32_t));
5358 activeTrack->mResampler->resample(activeTrack->mRsmpOutBuffer, framesOut,
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005359 // FIXME how about having activeTrack implement this interface itself?
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005360 activeTrack->mResamplerBufferProvider
5361 /*this*/ /* AudioBufferProvider* */);
5362 // ditherAndClamp() works as long as all buffers returned by
5363 // activeTrack->getNextBuffer() are 32 bit aligned which should be always true.
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005364 if (activeTrack->mChannelCount == 1) {
Andy Hung84a0c6e2014-04-02 11:24:53 -07005365 // temporarily type pun mRsmpOutBuffer from Q4.27 to int16_t
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005366 ditherAndClamp(activeTrack->mRsmpOutBuffer, activeTrack->mRsmpOutBuffer,
5367 framesOut);
5368 // the resampler always outputs stereo samples:
5369 // do post stereo to mono conversion
5370 downmix_to_mono_i16_from_stereo_i16(activeTrack->mSink.i16,
Glenn Kastencd704212014-07-14 17:26:36 -07005371 (const int16_t *)activeTrack->mRsmpOutBuffer, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005372 } else {
5373 ditherAndClamp((int32_t *)activeTrack->mSink.raw,
5374 activeTrack->mRsmpOutBuffer, framesOut);
5375 }
5376 // now done with mRsmpOutBuffer
5377
5378 }
5379
5380 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
5381 overrun = OVERRUN_FALSE;
5382 }
5383
5384 if (activeTrack->mFramesToDrop == 0) {
5385 if (framesOut > 0) {
5386 activeTrack->mSink.frameCount = framesOut;
5387 activeTrack->releaseBuffer(&activeTrack->mSink);
5388 }
5389 } else {
5390 // FIXME could do a partial drop of framesOut
5391 if (activeTrack->mFramesToDrop > 0) {
5392 activeTrack->mFramesToDrop -= framesOut;
5393 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005394 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005395 }
5396 } else {
5397 activeTrack->mFramesToDrop += framesOut;
5398 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
5399 activeTrack->mSyncStartEvent->isCancelled()) {
5400 ALOGW("Synced record %s, session %d, trigger session %d",
5401 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
5402 activeTrack->sessionId(),
5403 (activeTrack->mSyncStartEvent != 0) ?
5404 activeTrack->mSyncStartEvent->triggerSession() : 0);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005405 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005406 }
5407 }
5408 }
5409
5410 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005411 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005412 }
5413 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005414
5415 switch (overrun) {
5416 case OVERRUN_TRUE:
5417 // client isn't retrieving buffers fast enough
5418 if (!activeTrack->setOverflow()) {
5419 nsecs_t now = systemTime();
5420 // FIXME should lastWarning per track?
5421 if ((now - lastWarning) > kWarningThrottleNs) {
5422 ALOGW("RecordThread: buffer overflow");
5423 lastWarning = now;
5424 }
5425 }
5426 break;
5427 case OVERRUN_FALSE:
5428 activeTrack->clearOverflow();
5429 break;
5430 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005431 break;
5432 }
5433
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005434 }
5435
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005436unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08005437 // enable changes in effect chain
5438 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005439 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08005440 }
5441
Glenn Kasten93e471f2013-08-19 08:40:07 -07005442 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08005443
5444 {
5445 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07005446 for (size_t i = 0; i < mTracks.size(); i++) {
5447 sp<RecordTrack> track = mTracks[i];
5448 track->invalidate();
5449 }
Glenn Kasten2b806402013-11-20 16:37:38 -08005450 mActiveTracks.clear();
5451 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08005452 mStartStopCond.broadcast();
5453 }
5454
5455 releaseWakeLock();
5456
5457 ALOGV("RecordThread %p exiting", this);
5458 return false;
5459}
5460
Glenn Kasten93e471f2013-08-19 08:40:07 -07005461void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08005462{
5463 if (!mStandby) {
5464 inputStandBy();
5465 mStandby = true;
5466 }
5467}
5468
5469void AudioFlinger::RecordThread::inputStandBy()
5470{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005471 // Idle the fast capture if it's currently running
5472 if (mFastCapture != 0) {
5473 FastCaptureStateQueue *sq = mFastCapture->sq();
5474 FastCaptureState *state = sq->begin();
5475 if (!(state->mCommand & FastCaptureState::IDLE)) {
5476 state->mCommand = FastCaptureState::COLD_IDLE;
5477 state->mColdFutexAddr = &mFastCaptureFutex;
5478 state->mColdGen++;
5479 mFastCaptureFutex = 0;
5480 sq->end();
5481 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
5482 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
5483#if 0
5484 if (kUseFastCapture == FastCapture_Dynamic) {
5485 // FIXME
5486 }
5487#endif
5488#ifdef AUDIO_WATCHDOG
5489 // FIXME
5490#endif
5491 } else {
5492 sq->end(false /*didModify*/);
5493 }
5494 }
Eric Laurent81784c32012-11-19 14:55:58 -08005495 mInput->stream->common.standby(&mInput->stream->common);
5496}
5497
Glenn Kasten05997e22014-03-13 15:08:33 -07005498// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07005499sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08005500 const sp<AudioFlinger::Client>& client,
5501 uint32_t sampleRate,
5502 audio_format_t format,
5503 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08005504 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08005505 int sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07005506 size_t *notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005507 int uid,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07005508 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08005509 pid_t tid,
5510 status_t *status)
5511{
Glenn Kasten74935e42013-12-19 08:56:45 -08005512 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005513 sp<RecordTrack> track;
5514 status_t lStatus;
5515
Glenn Kasten90e58b12013-07-31 16:16:02 -07005516 // client expresses a preference for FAST, but we get the final say
5517 if (*flags & IAudioFlinger::TRACK_FAST) {
5518 if (
Glenn Kasten74105912014-07-03 12:28:53 -07005519 // use case: callback handler
5520 (tid != -1) &&
5521 // frame count is not specified, or is exactly the pipe depth
5522 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005523 // PCM data
5524 audio_is_linear_pcm(format) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005525 // native format
5526 (format == mFormat) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005527 // native channel mask
5528 (channelMask == mChannelMask) &&
5529 // native hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07005530 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005531 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005532 hasFastCapture() &&
5533 // there are sufficient fast track slots available
5534 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07005535 ) {
Glenn Kasten74105912014-07-03 12:28:53 -07005536 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%u mFrameCount=%u",
Glenn Kasten90e58b12013-07-31 16:16:02 -07005537 frameCount, mFrameCount);
5538 } else {
Glenn Kasten74105912014-07-03 12:28:53 -07005539 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%u mFrameCount=%u mPipeFramesP2=%u "
5540 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005541 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Glenn Kasten74105912014-07-03 12:28:53 -07005542 frameCount, mFrameCount, mPipeFramesP2,
5543 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
5544 hasFastCapture(), tid, mFastTrackAvail);
Glenn Kasten90e58b12013-07-31 16:16:02 -07005545 *flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kasten74105912014-07-03 12:28:53 -07005546 }
5547 }
5548
5549 // compute track buffer size in frames, and suggest the notification frame count
5550 if (*flags & IAudioFlinger::TRACK_FAST) {
5551 // fast track: frame count is exactly the pipe depth
5552 frameCount = mPipeFramesP2;
5553 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
5554 *notificationFrames = mFrameCount;
5555 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07005556 // not fast track: max notification period is resampled equivalent of one HAL buffer time
5557 // or 20 ms if there is a fast capture
5558 // TODO This could be a roundupRatio inline, and const
5559 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
5560 * sampleRate + mSampleRate - 1) / mSampleRate;
5561 // minimum number of notification periods is at least kMinNotifications,
5562 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
5563 static const size_t kMinNotifications = 3;
5564 static const uint32_t kMinMs = 30;
5565 // TODO This could be a roundupRatio inline
5566 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
5567 // TODO This could be a roundupRatio inline
5568 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
5569 maxNotificationFrames;
5570 const size_t minFrameCount = maxNotificationFrames *
5571 max(kMinNotifications, minNotificationsByMs);
5572 frameCount = max(frameCount, minFrameCount);
5573 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
5574 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07005575 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07005576 }
Glenn Kasten74935e42013-12-19 08:56:45 -08005577 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07005578
Glenn Kasten15e57982013-09-24 11:52:37 -07005579 lStatus = initCheck();
5580 if (lStatus != NO_ERROR) {
5581 ALOGE("createRecordTrack_l() audio driver not initialized");
5582 goto Exit;
5583 }
Eric Laurent81784c32012-11-19 14:55:58 -08005584
5585 { // scope for mLock
5586 Mutex::Autolock _l(mLock);
5587
5588 track = new RecordTrack(this, client, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07005589 format, channelMask, frameCount, NULL, sessionId, uid,
5590 *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08005591
Glenn Kasten03003332013-08-06 15:40:54 -07005592 lStatus = track->initCheck();
5593 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07005594 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08005595 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08005596 goto Exit;
5597 }
5598 mTracks.add(track);
5599
5600 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5601 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
5602 mAudioFlinger->btNrecIsOff();
5603 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
5604 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07005605
5606 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
5607 pid_t callingPid = IPCThreadState::self()->getCallingPid();
5608 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
5609 // so ask activity manager to do this on our behalf
5610 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
5611 }
Eric Laurent81784c32012-11-19 14:55:58 -08005612 }
Glenn Kasten05997e22014-03-13 15:08:33 -07005613
Eric Laurent81784c32012-11-19 14:55:58 -08005614 lStatus = NO_ERROR;
5615
5616Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07005617 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08005618 return track;
5619}
5620
5621status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
5622 AudioSystem::sync_event_t event,
5623 int triggerSession)
5624{
5625 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
5626 sp<ThreadBase> strongMe = this;
5627 status_t status = NO_ERROR;
5628
5629 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005630 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08005631 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005632 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08005633 triggerSession,
5634 recordTrack->sessionId(),
5635 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005636 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08005637 // Sync event can be cancelled by the trigger session if the track is not in a
5638 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005639 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005640 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08005641 } else {
5642 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005643 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005644 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08005645 }
5646 }
5647
5648 {
Glenn Kasten47c20702013-08-13 15:37:35 -07005649 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08005650 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005651 if (mActiveTracks.indexOf(recordTrack) >= 0) {
5652 if (recordTrack->mState == TrackBase::PAUSING) {
5653 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005654 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005655 } else {
5656 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08005657 }
5658 return status;
5659 }
5660
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005661 // TODO consider other ways of handling this, such as changing the state to :STARTING and
5662 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
5663 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005664 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08005665 mActiveTracks.add(recordTrack);
5666 mActiveTracksGen++;
Eric Laurent83b88082014-06-20 18:31:16 -07005667 status_t status = NO_ERROR;
5668 if (recordTrack->isExternalTrack()) {
5669 mLock.unlock();
Eric Laurent4dc68062014-07-28 17:26:49 -07005670 status = AudioSystem::startInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07005671 mLock.lock();
5672 // FIXME should verify that recordTrack is still in mActiveTracks
5673 if (status != NO_ERROR) {
5674 mActiveTracks.remove(recordTrack);
5675 mActiveTracksGen++;
5676 recordTrack->clearSyncStartEvent();
5677 ALOGV("RecordThread::start error %d", status);
5678 return status;
5679 }
Eric Laurent81784c32012-11-19 14:55:58 -08005680 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005681 // Catch up with current buffer indices if thread is already running.
5682 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
5683 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
5684 // see previously buffered data before it called start(), but with greater risk of overrun.
5685
5686 recordTrack->mRsmpInFront = mRsmpInRear;
5687 recordTrack->mRsmpInUnrel = 0;
5688 // FIXME why reset?
5689 if (recordTrack->mResampler != NULL) {
5690 recordTrack->mResampler->reset();
Eric Laurent81784c32012-11-19 14:55:58 -08005691 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005692 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08005693 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08005694 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08005695 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005696 ALOGV("Record failed to start");
5697 status = BAD_VALUE;
5698 goto startError;
5699 }
Eric Laurent81784c32012-11-19 14:55:58 -08005700 return status;
5701 }
Glenn Kasten7c027242012-12-26 14:43:16 -08005702
Eric Laurent81784c32012-11-19 14:55:58 -08005703startError:
Eric Laurent83b88082014-06-20 18:31:16 -07005704 if (recordTrack->isExternalTrack()) {
Eric Laurent4dc68062014-07-28 17:26:49 -07005705 AudioSystem::stopInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07005706 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005707 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005708 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08005709 return status;
5710}
5711
Eric Laurent81784c32012-11-19 14:55:58 -08005712void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
5713{
5714 sp<SyncEvent> strongEvent = event.promote();
5715
5716 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08005717 sp<RefBase> ptr = strongEvent->cookie().promote();
5718 if (ptr != 0) {
5719 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
5720 recordTrack->handleSyncStartEvent(strongEvent);
5721 }
Eric Laurent81784c32012-11-19 14:55:58 -08005722 }
5723}
5724
Glenn Kastena8356f62013-07-25 14:37:52 -07005725bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08005726 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07005727 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005728 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08005729 return false;
5730 }
Glenn Kasten47c20702013-08-13 15:37:35 -07005731 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08005732 recordTrack->mState = TrackBase::PAUSING;
5733 // do not wait for mStartStopCond if exiting
5734 if (exitPending()) {
5735 return true;
5736 }
Glenn Kasten47c20702013-08-13 15:37:35 -07005737 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08005738 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005739 // if we have been restarted, recordTrack is in mActiveTracks here
5740 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005741 ALOGV("Record stopped OK");
5742 return true;
5743 }
5744 return false;
5745}
5746
Glenn Kasten0f11b512014-01-31 16:18:54 -08005747bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08005748{
5749 return false;
5750}
5751
Glenn Kasten0f11b512014-01-31 16:18:54 -08005752status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005753{
5754#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
5755 if (!isValidSyncEvent(event)) {
5756 return BAD_VALUE;
5757 }
5758
5759 int eventSession = event->triggerSession();
5760 status_t ret = NAME_NOT_FOUND;
5761
5762 Mutex::Autolock _l(mLock);
5763
5764 for (size_t i = 0; i < mTracks.size(); i++) {
5765 sp<RecordTrack> track = mTracks[i];
5766 if (eventSession == track->sessionId()) {
5767 (void) track->setSyncEvent(event);
5768 ret = NO_ERROR;
5769 }
5770 }
5771 return ret;
5772#else
5773 return BAD_VALUE;
5774#endif
5775}
5776
5777// destroyTrack_l() must be called with ThreadBase::mLock held
5778void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
5779{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005780 track->terminate();
5781 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08005782 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08005783 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005784 removeTrack_l(track);
5785 }
5786}
5787
5788void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
5789{
5790 mTracks.remove(track);
5791 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005792 if (track->isFastTrack()) {
5793 ALOG_ASSERT(!mFastTrackAvail);
5794 mFastTrackAvail = true;
5795 }
Eric Laurent81784c32012-11-19 14:55:58 -08005796}
5797
5798void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
5799{
5800 dumpInternals(fd, args);
5801 dumpTracks(fd, args);
5802 dumpEffectChains(fd, args);
5803}
5804
5805void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
5806{
Elliott Hughes87cebad2014-05-22 10:14:43 -07005807 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08005808
Glenn Kasten2b806402013-11-20 16:37:38 -08005809 if (mActiveTracks.size() > 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07005810 dprintf(fd, " Buffer size: %zu bytes\n", mBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005811 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07005812 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08005813 }
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005814 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005815 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Eric Laurent81784c32012-11-19 14:55:58 -08005816
Eric Laurent81784c32012-11-19 14:55:58 -08005817 dumpBase(fd, args);
5818}
5819
Glenn Kasten0f11b512014-01-31 16:18:54 -08005820void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005821{
5822 const size_t SIZE = 256;
5823 char buffer[SIZE];
5824 String8 result;
5825
Marco Nelissenb2208842014-02-07 14:00:50 -08005826 size_t numtracks = mTracks.size();
5827 size_t numactive = mActiveTracks.size();
5828 size_t numactiveseen = 0;
Elliott Hughes87cebad2014-05-22 10:14:43 -07005829 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08005830 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07005831 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08005832 RecordTrack::appendDumpHeader(result);
5833 for (size_t i = 0; i < numtracks ; ++i) {
5834 sp<RecordTrack> track = mTracks[i];
5835 if (track != 0) {
5836 bool active = mActiveTracks.indexOf(track) >= 0;
5837 if (active) {
5838 numactiveseen++;
5839 }
5840 track->dump(buffer, SIZE, active);
5841 result.append(buffer);
5842 }
Eric Laurent81784c32012-11-19 14:55:58 -08005843 }
Marco Nelissenb2208842014-02-07 14:00:50 -08005844 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07005845 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08005846 }
5847
Marco Nelissenb2208842014-02-07 14:00:50 -08005848 if (numactiveseen != numactive) {
5849 snprintf(buffer, SIZE, " The following tracks are in the active list but"
5850 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08005851 result.append(buffer);
5852 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08005853 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08005854 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08005855 if (mTracks.indexOf(track) < 0) {
5856 track->dump(buffer, SIZE, true);
5857 result.append(buffer);
5858 }
Glenn Kasten2b806402013-11-20 16:37:38 -08005859 }
Eric Laurent81784c32012-11-19 14:55:58 -08005860
5861 }
5862 write(fd, result.string(), result.size());
5863}
5864
5865// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005866status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
5867 AudioBufferProvider::Buffer* buffer, int64_t pts __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005868{
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005869 RecordTrack *activeTrack = mRecordTrack;
5870 sp<ThreadBase> threadBase = activeTrack->mThread.promote();
5871 if (threadBase == 0) {
5872 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005873 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005874 return NOT_ENOUGH_DATA;
5875 }
5876 RecordThread *recordThread = (RecordThread *) threadBase.get();
5877 int32_t rear = recordThread->mRsmpInRear;
5878 int32_t front = activeTrack->mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07005879 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005880 // FIXME should not be P2 (don't want to increase latency)
5881 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005882 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07005883 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005884 front &= recordThread->mRsmpInFramesP2 - 1;
5885 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07005886 if (part1 > (size_t) filled) {
5887 part1 = filled;
5888 }
5889 size_t ask = buffer->frameCount;
5890 ALOG_ASSERT(ask > 0);
5891 if (part1 > ask) {
5892 part1 = ask;
5893 }
5894 if (part1 == 0) {
5895 // Higher-level should keep mRsmpInBuffer full, and not call resampler if empty
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005896 LOG_ALWAYS_FATAL("RecordThread::getNextBuffer() starved");
Glenn Kasten85948432013-08-19 12:09:05 -07005897 buffer->raw = NULL;
5898 buffer->frameCount = 0;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005899 activeTrack->mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07005900 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08005901 }
5902
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005903 buffer->raw = recordThread->mRsmpInBuffer + front * recordThread->mChannelCount;
Glenn Kasten85948432013-08-19 12:09:05 -07005904 buffer->frameCount = part1;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005905 activeTrack->mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08005906 return NO_ERROR;
5907}
5908
5909// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005910void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
5911 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08005912{
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005913 RecordTrack *activeTrack = mRecordTrack;
Glenn Kasten85948432013-08-19 12:09:05 -07005914 size_t stepCount = buffer->frameCount;
5915 if (stepCount == 0) {
5916 return;
5917 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005918 ALOG_ASSERT(stepCount <= activeTrack->mRsmpInUnrel);
5919 activeTrack->mRsmpInUnrel -= stepCount;
5920 activeTrack->mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07005921 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08005922 buffer->frameCount = 0;
5923}
5924
Eric Laurent10351942014-05-08 18:49:52 -07005925bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
5926 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005927{
5928 bool reconfig = false;
5929
Eric Laurent10351942014-05-08 18:49:52 -07005930 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005931
Eric Laurent10351942014-05-08 18:49:52 -07005932 audio_format_t reqFormat = mFormat;
5933 uint32_t samplingRate = mSampleRate;
5934 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
5935
5936 AudioParameter param = AudioParameter(keyValuePair);
5937 int value;
5938 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
5939 // channel count change can be requested. Do we mandate the first client defines the
5940 // HAL sampling rate and channel count or do we allow changes on the fly?
5941 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5942 samplingRate = value;
5943 reconfig = true;
5944 }
5945 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
5946 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
5947 status = BAD_VALUE;
5948 } else {
5949 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08005950 reconfig = true;
5951 }
Eric Laurent10351942014-05-08 18:49:52 -07005952 }
5953 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
5954 audio_channel_mask_t mask = (audio_channel_mask_t) value;
5955 if (mask != AUDIO_CHANNEL_IN_MONO && mask != AUDIO_CHANNEL_IN_STEREO) {
5956 status = BAD_VALUE;
5957 } else {
5958 channelMask = mask;
5959 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005960 }
Eric Laurent10351942014-05-08 18:49:52 -07005961 }
5962 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5963 // do not accept frame count changes if tracks are open as the track buffer
5964 // size depends on frame count and correct behavior would not be guaranteed
5965 // if frame count is changed after track creation
5966 if (mActiveTracks.size() > 0) {
5967 status = INVALID_OPERATION;
5968 } else {
5969 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005970 }
Eric Laurent10351942014-05-08 18:49:52 -07005971 }
5972 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5973 // forward device change to effects that have requested to be
5974 // aware of attached audio device.
5975 for (size_t i = 0; i < mEffectChains.size(); i++) {
5976 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08005977 }
Eric Laurent81784c32012-11-19 14:55:58 -08005978
Eric Laurent10351942014-05-08 18:49:52 -07005979 // store input device and output device but do not forward output device to audio HAL.
5980 // Note that status is ignored by the caller for output device
5981 // (see AudioFlinger::setParameters()
5982 if (audio_is_output_devices(value)) {
5983 mOutDevice = value;
5984 status = BAD_VALUE;
5985 } else {
5986 mInDevice = value;
5987 // disable AEC and NS if the device is a BT SCO headset supporting those
5988 // pre processings
5989 if (mTracks.size() > 0) {
5990 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
5991 mAudioFlinger->btNrecIsOff();
5992 for (size_t i = 0; i < mTracks.size(); i++) {
5993 sp<RecordTrack> track = mTracks[i];
5994 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
5995 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08005996 }
5997 }
5998 }
Eric Laurent10351942014-05-08 18:49:52 -07005999 }
6000 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
6001 mAudioSource != (audio_source_t)value) {
6002 // forward device change to effects that have requested to be
6003 // aware of attached audio device.
6004 for (size_t i = 0; i < mEffectChains.size(); i++) {
6005 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08006006 }
Eric Laurent10351942014-05-08 18:49:52 -07006007 mAudioSource = (audio_source_t)value;
6008 }
Glenn Kastene198c362013-08-13 09:13:36 -07006009
Eric Laurent10351942014-05-08 18:49:52 -07006010 if (status == NO_ERROR) {
6011 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6012 keyValuePair.string());
6013 if (status == INVALID_OPERATION) {
6014 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006015 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6016 keyValuePair.string());
Eric Laurent10351942014-05-08 18:49:52 -07006017 }
6018 if (reconfig) {
6019 if (status == BAD_VALUE &&
6020 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
6021 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
6022 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
6023 <= (2 * samplingRate)) &&
Andy Hunge5412692014-05-16 11:25:07 -07006024 audio_channel_count_from_in_mask(
6025 mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
Eric Laurent10351942014-05-08 18:49:52 -07006026 (channelMask == AUDIO_CHANNEL_IN_MONO ||
6027 channelMask == AUDIO_CHANNEL_IN_STEREO)) {
6028 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006029 }
Eric Laurent10351942014-05-08 18:49:52 -07006030 if (status == NO_ERROR) {
6031 readInputParameters_l();
6032 sendIoConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08006033 }
6034 }
Eric Laurent81784c32012-11-19 14:55:58 -08006035 }
Eric Laurent10351942014-05-08 18:49:52 -07006036
Eric Laurent81784c32012-11-19 14:55:58 -08006037 return reconfig;
6038}
6039
6040String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6041{
Eric Laurent81784c32012-11-19 14:55:58 -08006042 Mutex::Autolock _l(mLock);
6043 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07006044 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08006045 }
6046
Glenn Kastend8ea6992013-07-16 14:17:15 -07006047 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
6048 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08006049 free(s);
6050 return out_s8;
6051}
6052
Eric Laurent021cf962014-05-13 10:18:14 -07006053void AudioFlinger::RecordThread::audioConfigChanged(int event, int param __unused) {
Eric Laurent81784c32012-11-19 14:55:58 -08006054 AudioSystem::OutputDescriptor desc;
Glenn Kastenb2737d02013-08-19 12:03:11 -07006055 const void *param2 = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006056
6057 switch (event) {
6058 case AudioSystem::INPUT_OPENED:
6059 case AudioSystem::INPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07006060 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08006061 desc.samplingRate = mSampleRate;
6062 desc.format = mFormat;
6063 desc.frameCount = mFrameCount;
6064 desc.latency = 0;
6065 param2 = &desc;
6066 break;
6067
6068 case AudioSystem::INPUT_CLOSED:
6069 default:
6070 break;
6071 }
Eric Laurent021cf962014-05-13 10:18:14 -07006072 mAudioFlinger->audioConfigChanged(event, mId, param2);
Eric Laurent81784c32012-11-19 14:55:58 -08006073}
6074
Glenn Kastendeca2ae2014-02-07 10:25:56 -08006075void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006076{
Eric Laurent81784c32012-11-19 14:55:58 -08006077 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
6078 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Andy Hunge5412692014-05-16 11:25:07 -07006079 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Andy Hung463be252014-07-10 16:56:07 -07006080 mHALFormat = mInput->stream->common.get_format(&mInput->stream->common);
6081 mFormat = mHALFormat;
Glenn Kasten291bb6d2013-07-16 17:23:39 -07006082 if (mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08006083 ALOGE("HAL format %#x not supported; must be AUDIO_FORMAT_PCM_16_BIT", mFormat);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07006084 }
Eric Laurent665470b2014-07-03 16:37:08 -07006085 mFrameSize = audio_stream_in_frame_size(mInput->stream);
Glenn Kasten548efc92012-11-29 08:48:51 -08006086 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
6087 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006088 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08006089 // 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 -07006090 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08006091 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006092 // A larger value should allow more old data to be read after a track calls start(),
6093 // without increasing latency.
Glenn Kastene8426142014-02-28 16:45:03 -08006094 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07006095 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006096 delete[] mRsmpInBuffer;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006097
6098 // TODO optimize audio capture buffer sizes ...
6099 // Here we calculate the size of the sliding buffer used as a source
6100 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
6101 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
6102 // be better to have it derived from the pipe depth in the long term.
6103 // The current value is higher than necessary. However it should not add to latency.
6104
Glenn Kasten85948432013-08-19 12:09:05 -07006105 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
6106 mRsmpInBuffer = new int16_t[(mRsmpInFramesP2 + mFrameCount - 1) * mChannelCount];
Eric Laurent81784c32012-11-19 14:55:58 -08006107
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006108 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
6109 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08006110}
6111
Glenn Kasten5f972c02014-01-13 09:59:31 -08006112uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08006113{
6114 Mutex::Autolock _l(mLock);
6115 if (initCheck() != NO_ERROR) {
6116 return 0;
6117 }
6118
6119 return mInput->stream->get_input_frames_lost(mInput->stream);
6120}
6121
6122uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
6123{
6124 Mutex::Autolock _l(mLock);
6125 uint32_t result = 0;
6126 if (getEffectChain_l(sessionId) != 0) {
6127 result = EFFECT_SESSION;
6128 }
6129
6130 for (size_t i = 0; i < mTracks.size(); ++i) {
6131 if (sessionId == mTracks[i]->sessionId()) {
6132 result |= TRACK_SESSION;
6133 break;
6134 }
6135 }
6136
6137 return result;
6138}
6139
6140KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
6141{
6142 KeyedVector<int, bool> ids;
6143 Mutex::Autolock _l(mLock);
6144 for (size_t j = 0; j < mTracks.size(); ++j) {
6145 sp<RecordThread::RecordTrack> track = mTracks[j];
6146 int sessionId = track->sessionId();
6147 if (ids.indexOfKey(sessionId) < 0) {
6148 ids.add(sessionId, true);
6149 }
6150 }
6151 return ids;
6152}
6153
6154AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
6155{
6156 Mutex::Autolock _l(mLock);
6157 AudioStreamIn *input = mInput;
6158 mInput = NULL;
6159 return input;
6160}
6161
6162// this method must always be called either with ThreadBase mLock held or inside the thread loop
6163audio_stream_t* AudioFlinger::RecordThread::stream() const
6164{
6165 if (mInput == NULL) {
6166 return NULL;
6167 }
6168 return &mInput->stream->common;
6169}
6170
6171status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6172{
6173 // only one chain per input thread
6174 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07006175 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08006176 return INVALID_OPERATION;
6177 }
6178 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07006179 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08006180 chain->setInBuffer(NULL);
6181 chain->setOutBuffer(NULL);
6182
6183 checkSuspendOnAddEffectChain_l(chain);
6184
6185 mEffectChains.add(chain);
6186
6187 return NO_ERROR;
6188}
6189
6190size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6191{
6192 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
6193 ALOGW_IF(mEffectChains.size() != 1,
6194 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6195 chain.get(), mEffectChains.size(), this);
6196 if (mEffectChains.size() == 1) {
6197 mEffectChains.removeAt(0);
6198 }
6199 return 0;
6200}
6201
Eric Laurent1c333e22014-05-20 10:48:17 -07006202status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
6203 audio_patch_handle_t *handle)
6204{
6205 status_t status = NO_ERROR;
6206 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
6207 // store new device and send to effects
6208 mInDevice = patch->sources[0].ext.device.type;
6209 for (size_t i = 0; i < mEffectChains.size(); i++) {
6210 mEffectChains[i]->setDevice_l(mInDevice);
6211 }
6212
6213 // disable AEC and NS if the device is a BT SCO headset supporting those
6214 // pre processings
6215 if (mTracks.size() > 0) {
6216 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6217 mAudioFlinger->btNrecIsOff();
6218 for (size_t i = 0; i < mTracks.size(); i++) {
6219 sp<RecordTrack> track = mTracks[i];
6220 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
6221 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
6222 }
6223 }
6224
6225 // store new source and send to effects
6226 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
6227 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
6228 for (size_t i = 0; i < mEffectChains.size(); i++) {
6229 mEffectChains[i]->setAudioSource_l(mAudioSource);
6230 }
6231 }
6232
6233 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
6234 status = hwDevice->create_audio_patch(hwDevice,
6235 patch->num_sources,
6236 patch->sources,
6237 patch->num_sinks,
6238 patch->sinks,
6239 handle);
6240 } else {
6241 ALOG_ASSERT(false, "createAudioPatch_l() called on a pre 3.0 HAL");
6242 }
6243 return status;
6244}
6245
6246status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
6247{
6248 status_t status = NO_ERROR;
6249 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
6250 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
6251 status = hwDevice->release_audio_patch(hwDevice, handle);
6252 } else {
6253 ALOG_ASSERT(false, "releaseAudioPatch_l() called on a pre 3.0 HAL");
6254 }
6255 return status;
6256}
6257
Eric Laurent83b88082014-06-20 18:31:16 -07006258void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
6259{
6260 Mutex::Autolock _l(mLock);
6261 mTracks.add(record);
6262}
6263
6264void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
6265{
6266 Mutex::Autolock _l(mLock);
6267 destroyTrack_l(record);
6268}
6269
6270void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
6271{
6272 ThreadBase::getAudioPortConfig(config);
6273 config->role = AUDIO_PORT_ROLE_SINK;
6274 config->ext.mix.hw_module = mInput->audioHwDev->handle();
6275 config->ext.mix.usecase.source = mAudioSource;
6276}
Eric Laurent1c333e22014-05-20 10:48:17 -07006277
Eric Laurent81784c32012-11-19 14:55:58 -08006278}; // namespace android