blob: 40ab0af47ed0a0b8b5a9bbb5a3a3ee440f05e14e [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>
Glenn Kastenad8510a2015-02-17 16:24:07 -080026#include <linux/futex.h>
Eric Laurent81784c32012-11-19 14:55:58 -080027#include <sys/stat.h>
Glenn Kastenad8510a2015-02-17 16:24:07 -080028#include <sys/syscall.h>
Eric Laurent81784c32012-11-19 14:55:58 -080029#include <cutils/properties.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070030#include <media/AudioParameter.h>
Andy Hungcd044842014-08-07 11:04:34 -070031#include <media/AudioResamplerPublic.h>
Eric Laurent81784c32012-11-19 14:55:58 -080032#include <utils/Log.h>
Alex Ray371eb972012-11-30 11:11:54 -080033#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080034
35#include <private/media/AudioTrackShared.h>
36#include <hardware/audio.h>
37#include <audio_effects/effect_ns.h>
38#include <audio_effects/effect_aec.h>
39#include <audio_utils/primitives.h>
Andy Hung98ef9782014-03-04 14:46:50 -080040#include <audio_utils/format.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070041#include <audio_utils/minifloat.h>
Eric Laurent81784c32012-11-19 14:55:58 -080042
43// NBAIO implementations
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070044#include <media/nbaio/AudioStreamInSource.h>
Eric Laurent81784c32012-11-19 14:55:58 -080045#include <media/nbaio/AudioStreamOutSink.h>
46#include <media/nbaio/MonoPipe.h>
47#include <media/nbaio/MonoPipeReader.h>
48#include <media/nbaio/Pipe.h>
49#include <media/nbaio/PipeReader.h>
50#include <media/nbaio/SourceAudioBufferProvider.h>
51
52#include <powermanager/PowerManager.h>
53
54#include <common_time/cc_helper.h>
55#include <common_time/local_clock.h>
56
57#include "AudioFlinger.h"
58#include "AudioMixer.h"
59#include "FastMixer.h"
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070060#include "FastCapture.h"
Eric Laurent81784c32012-11-19 14:55:58 -080061#include "ServiceUtilities.h"
62#include "SchedulingPolicyService.h"
63
Eric Laurent81784c32012-11-19 14:55:58 -080064#ifdef ADD_BATTERY_DATA
65#include <media/IMediaPlayerService.h>
66#include <media/IMediaDeathNotifier.h>
67#endif
68
Eric Laurent81784c32012-11-19 14:55:58 -080069#ifdef DEBUG_CPU_USAGE
70#include <cpustats/CentralTendencyStatistics.h>
71#include <cpustats/ThreadCpuUsage.h>
72#endif
73
74// ----------------------------------------------------------------------------
75
76// Note: the following macro is used for extremely verbose logging message. In
77// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
78// 0; but one side effect of this is to turn all LOGV's as well. Some messages
79// are so verbose that we want to suppress them even when we have ALOG_ASSERT
80// turned on. Do not uncomment the #def below unless you really know what you
81// are doing and want to see all of the extremely verbose messages.
82//#define VERY_VERY_VERBOSE_LOGGING
83#ifdef VERY_VERY_VERBOSE_LOGGING
84#define ALOGVV ALOGV
85#else
86#define ALOGVV(a...) do { } while(0)
87#endif
88
Glenn Kasten49d00ad2014-07-21 11:22:03 -070089#define max(a, b) ((a) > (b) ? (a) : (b))
90
Eric Laurent81784c32012-11-19 14:55:58 -080091namespace android {
92
93// retry counts for buffer fill timeout
94// 50 * ~20msecs = 1 second
95static const int8_t kMaxTrackRetries = 50;
96static const int8_t kMaxTrackStartupRetries = 50;
97// allow less retry attempts on direct output thread.
98// direct outputs can be a scarce resource in audio hardware and should
99// be released as quickly as possible.
100static const int8_t kMaxTrackRetriesDirect = 2;
101
102// don't warn about blocked writes or record buffer overflows more often than this
103static const nsecs_t kWarningThrottleNs = seconds(5);
104
105// RecordThread loop sleep time upon application overrun or audio HAL read error
106static const int kRecordThreadSleepUs = 5000;
107
Eric Laurent10351942014-05-08 18:49:52 -0700108// maximum time to wait in sendConfigEvent_l() for a status to be received
109static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800110
111// minimum sleep time for the mixer thread loop when tracks are active but in underrun
112static const uint32_t kMinThreadSleepTimeUs = 5000;
113// maximum divider applied to the active sleep time in the mixer thread loop
114static const uint32_t kMaxThreadSleepTimeShift = 2;
115
Andy Hung09a50072014-02-27 14:30:47 -0800116// minimum normal sink buffer size, expressed in milliseconds rather than frames
117static const uint32_t kMinNormalSinkBufferSizeMs = 20;
118// maximum normal sink buffer size
119static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800120
Eric Laurent972a1732013-09-04 09:42:59 -0700121// Offloaded output thread standby delay: allows track transition without going to standby
122static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
123
Eric Laurent81784c32012-11-19 14:55:58 -0800124// Whether to use fast mixer
125static const enum {
126 FastMixer_Never, // never initialize or use: for debugging only
127 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
128 // normal mixer multiplier is 1
129 FastMixer_Static, // initialize if needed, then use all the time if initialized,
130 // multiplier is calculated based on min & max normal mixer buffer size
131 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
132 // multiplier is calculated based on min & max normal mixer buffer size
133 // FIXME for FastMixer_Dynamic:
134 // Supporting this option will require fixing HALs that can't handle large writes.
135 // For example, one HAL implementation returns an error from a large write,
136 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
137 // We could either fix the HAL implementations, or provide a wrapper that breaks
138 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
139} kUseFastMixer = FastMixer_Static;
140
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700141// Whether to use fast capture
142static const enum {
143 FastCapture_Never, // never initialize or use: for debugging only
144 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
145 FastCapture_Static, // initialize if needed, then use all the time if initialized
146} kUseFastCapture = FastCapture_Static;
147
Eric Laurent81784c32012-11-19 14:55:58 -0800148// Priorities for requestPriority
149static const int kPriorityAudioApp = 2;
150static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700151static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800152
153// IAudioFlinger::createTrack() reports back to client the total size of shared memory area
154// for the track. The client then sub-divides this into smaller buffers for its use.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800155// Currently the client uses N-buffering by default, but doesn't tell us about the value of N.
156// So for now we just assume that client is double-buffered for fast tracks.
157// FIXME It would be better for client to tell AudioFlinger the value of N,
158// so AudioFlinger could allocate the right amount of memory.
Eric Laurent81784c32012-11-19 14:55:58 -0800159// See the client's minBufCount and mNotificationFramesAct calculations for details.
Glenn Kasten03490092014-05-27 12:30:54 -0700160
161// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800162static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800163
Glenn Kasten03490092014-05-27 12:30:54 -0700164// The minimum and maximum allowed values
165static const int kFastTrackMultiplierMin = 1;
166static const int kFastTrackMultiplierMax = 2;
167
168// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
169static int sFastTrackMultiplier = kFastTrackMultiplier;
170
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700171// See Thread::readOnlyHeap().
172// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
173// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
174// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Glenn Kasten9f81de32014-07-27 15:02:23 -0700175static const size_t kRecordThreadReadOnlyHeapSize = 0x2000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700176
Eric Laurent81784c32012-11-19 14:55:58 -0800177// ----------------------------------------------------------------------------
178
Glenn Kasten03490092014-05-27 12:30:54 -0700179static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
180
181static void sFastTrackMultiplierInit()
182{
183 char value[PROPERTY_VALUE_MAX];
184 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
185 char *endptr;
186 unsigned long ul = strtoul(value, &endptr, 0);
187 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
188 sFastTrackMultiplier = (int) ul;
189 }
190 }
191}
192
193// ----------------------------------------------------------------------------
194
Eric Laurent81784c32012-11-19 14:55:58 -0800195#ifdef ADD_BATTERY_DATA
196// To collect the amplifier usage
197static void addBatteryData(uint32_t params) {
198 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
199 if (service == NULL) {
200 // it already logged
201 return;
202 }
203
204 service->addBatteryData(params);
205}
206#endif
207
208
209// ----------------------------------------------------------------------------
210// CPU Stats
211// ----------------------------------------------------------------------------
212
213class CpuStats {
214public:
215 CpuStats();
216 void sample(const String8 &title);
217#ifdef DEBUG_CPU_USAGE
218private:
219 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
220 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
221
222 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
223
224 int mCpuNum; // thread's current CPU number
225 int mCpukHz; // frequency of thread's current CPU in kHz
226#endif
227};
228
229CpuStats::CpuStats()
230#ifdef DEBUG_CPU_USAGE
231 : mCpuNum(-1), mCpukHz(-1)
232#endif
233{
234}
235
Glenn Kasten0f11b512014-01-31 16:18:54 -0800236void CpuStats::sample(const String8 &title
237#ifndef DEBUG_CPU_USAGE
238 __unused
239#endif
240 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800241#ifdef DEBUG_CPU_USAGE
242 // get current thread's delta CPU time in wall clock ns
243 double wcNs;
244 bool valid = mCpuUsage.sampleAndEnable(wcNs);
245
246 // record sample for wall clock statistics
247 if (valid) {
248 mWcStats.sample(wcNs);
249 }
250
251 // get the current CPU number
252 int cpuNum = sched_getcpu();
253
254 // get the current CPU frequency in kHz
255 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
256
257 // check if either CPU number or frequency changed
258 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
259 mCpuNum = cpuNum;
260 mCpukHz = cpukHz;
261 // ignore sample for purposes of cycles
262 valid = false;
263 }
264
265 // if no change in CPU number or frequency, then record sample for cycle statistics
266 if (valid && mCpukHz > 0) {
267 double cycles = wcNs * cpukHz * 0.000001;
268 mHzStats.sample(cycles);
269 }
270
271 unsigned n = mWcStats.n();
272 // mCpuUsage.elapsed() is expensive, so don't call it every loop
273 if ((n & 127) == 1) {
274 long long elapsed = mCpuUsage.elapsed();
275 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
276 double perLoop = elapsed / (double) n;
277 double perLoop100 = perLoop * 0.01;
278 double perLoop1k = perLoop * 0.001;
279 double mean = mWcStats.mean();
280 double stddev = mWcStats.stddev();
281 double minimum = mWcStats.minimum();
282 double maximum = mWcStats.maximum();
283 double meanCycles = mHzStats.mean();
284 double stddevCycles = mHzStats.stddev();
285 double minCycles = mHzStats.minimum();
286 double maxCycles = mHzStats.maximum();
287 mCpuUsage.resetElapsed();
288 mWcStats.reset();
289 mHzStats.reset();
290 ALOGD("CPU usage for %s over past %.1f secs\n"
291 " (%u mixer loops at %.1f mean ms per loop):\n"
292 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
293 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
294 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
295 title.string(),
296 elapsed * .000000001, n, perLoop * .000001,
297 mean * .001,
298 stddev * .001,
299 minimum * .001,
300 maximum * .001,
301 mean / perLoop100,
302 stddev / perLoop100,
303 minimum / perLoop100,
304 maximum / perLoop100,
305 meanCycles / perLoop1k,
306 stddevCycles / perLoop1k,
307 minCycles / perLoop1k,
308 maxCycles / perLoop1k);
309
310 }
311 }
312#endif
313};
314
315// ----------------------------------------------------------------------------
316// ThreadBase
317// ----------------------------------------------------------------------------
318
Glenn Kasten97b7b752014-09-28 13:04:24 -0700319// static
320const char *AudioFlinger::ThreadBase::threadTypeToString(AudioFlinger::ThreadBase::type_t type)
321{
322 switch (type) {
323 case MIXER:
324 return "MIXER";
325 case DIRECT:
326 return "DIRECT";
327 case DUPLICATING:
328 return "DUPLICATING";
329 case RECORD:
330 return "RECORD";
331 case OFFLOAD:
332 return "OFFLOAD";
333 default:
334 return "unknown";
335 }
336}
337
338static String8 outputFlagsToString(audio_output_flags_t flags)
339{
340 static const struct mapping {
341 audio_output_flags_t mFlag;
342 const char * mString;
343 } mappings[] = {
344 AUDIO_OUTPUT_FLAG_DIRECT, "DIRECT",
345 AUDIO_OUTPUT_FLAG_PRIMARY, "PRIMARY",
346 AUDIO_OUTPUT_FLAG_FAST, "FAST",
347 AUDIO_OUTPUT_FLAG_DEEP_BUFFER, "DEEP_BUFFER",
348 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD, "COMPRESS_OFFLOAAD",
349 AUDIO_OUTPUT_FLAG_NON_BLOCKING, "NON_BLOCKING",
350 AUDIO_OUTPUT_FLAG_HW_AV_SYNC, "HW_AV_SYNC",
351 AUDIO_OUTPUT_FLAG_NONE, "NONE", // must be last
352 };
353 String8 result;
354 audio_output_flags_t allFlags = AUDIO_OUTPUT_FLAG_NONE;
355 const mapping *entry;
356 for (entry = mappings; entry->mFlag != AUDIO_OUTPUT_FLAG_NONE; entry++) {
357 allFlags = (audio_output_flags_t) (allFlags | entry->mFlag);
358 if (flags & entry->mFlag) {
359 if (!result.isEmpty()) {
360 result.append("|");
361 }
362 result.append(entry->mString);
363 }
364 }
365 if (flags & ~allFlags) {
366 if (!result.isEmpty()) {
367 result.append("|");
368 }
369 result.appendFormat("0x%X", flags & ~allFlags);
370 }
371 if (result.isEmpty()) {
372 result.append(entry->mString);
373 }
374 return result;
375}
376
Eric Laurent81784c32012-11-19 14:55:58 -0800377AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
378 audio_devices_t outDevice, audio_devices_t inDevice, type_t type)
379 : Thread(false /*canCallJava*/),
380 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700381 mAudioFlinger(audioFlinger),
Glenn Kasten70949c42013-08-06 07:40:12 -0700382 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800383 // are set by PlaybackThread::readOutputParameters_l() or
384 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700385 //FIXME: mStandby should be true here. Is this some kind of hack?
Eric Laurent81784c32012-11-19 14:55:58 -0800386 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
387 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
388 // mName will be set by concrete (non-virtual) subclass
389 mDeathRecipient(new PMDeathRecipient(this))
390{
391}
392
393AudioFlinger::ThreadBase::~ThreadBase()
394{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700395 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700396 mConfigEvents.clear();
397
Eric Laurent81784c32012-11-19 14:55:58 -0800398 // do not lock the mutex in destructor
399 releaseWakeLock_l();
400 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800401 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800402 binder->unlinkToDeath(mDeathRecipient);
403 }
404}
405
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700406status_t AudioFlinger::ThreadBase::readyToRun()
407{
408 status_t status = initCheck();
409 if (status == NO_ERROR) {
410 ALOGI("AudioFlinger's thread %p ready to run", this);
411 } else {
412 ALOGE("No working audio driver found.");
413 }
414 return status;
415}
416
Eric Laurent81784c32012-11-19 14:55:58 -0800417void AudioFlinger::ThreadBase::exit()
418{
419 ALOGV("ThreadBase::exit");
420 // do any cleanup required for exit to succeed
421 preExit();
422 {
423 // This lock prevents the following race in thread (uniprocessor for illustration):
424 // if (!exitPending()) {
425 // // context switch from here to exit()
426 // // exit() calls requestExit(), what exitPending() observes
427 // // exit() calls signal(), which is dropped since no waiters
428 // // context switch back from exit() to here
429 // mWaitWorkCV.wait(...);
430 // // now thread is hung
431 // }
432 AutoMutex lock(mLock);
433 requestExit();
434 mWaitWorkCV.broadcast();
435 }
436 // When Thread::requestExitAndWait is made virtual and this method is renamed to
437 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
438 requestExitAndWait();
439}
440
441status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
442{
443 status_t status;
444
445 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
446 Mutex::Autolock _l(mLock);
447
Eric Laurent10351942014-05-08 18:49:52 -0700448 return sendSetParameterConfigEvent_l(keyValuePairs);
449}
450
451// sendConfigEvent_l() must be called with ThreadBase::mLock held
452// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
453status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
454{
455 status_t status = NO_ERROR;
456
457 mConfigEvents.add(event);
458 ALOGV("sendConfigEvent_l() num events %d event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800459 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700460 mLock.unlock();
461 {
462 Mutex::Autolock _l(event->mLock);
463 while (event->mWaitStatus) {
464 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
465 event->mStatus = TIMED_OUT;
466 event->mWaitStatus = false;
467 }
468 }
469 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800470 }
Eric Laurent10351942014-05-08 18:49:52 -0700471 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800472 return status;
473}
474
475void AudioFlinger::ThreadBase::sendIoConfigEvent(int event, int param)
476{
477 Mutex::Autolock _l(mLock);
478 sendIoConfigEvent_l(event, param);
479}
480
481// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
482void AudioFlinger::ThreadBase::sendIoConfigEvent_l(int event, int param)
483{
Eric Laurent10351942014-05-08 18:49:52 -0700484 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, param);
485 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800486}
487
488// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
489void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
490{
Eric Laurent10351942014-05-08 18:49:52 -0700491 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio);
492 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800493}
494
Eric Laurent10351942014-05-08 18:49:52 -0700495// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
496status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800497{
Eric Laurent10351942014-05-08 18:49:52 -0700498 sp<ConfigEvent> configEvent = (ConfigEvent *)new SetParameterConfigEvent(keyValuePair);
499 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700500}
501
Eric Laurent1c333e22014-05-20 10:48:17 -0700502status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
503 const struct audio_patch *patch,
504 audio_patch_handle_t *handle)
505{
506 Mutex::Autolock _l(mLock);
507 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
508 status_t status = sendConfigEvent_l(configEvent);
509 if (status == NO_ERROR) {
510 CreateAudioPatchConfigEventData *data =
511 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
512 *handle = data->mHandle;
513 }
514 return status;
515}
516
517status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
518 const audio_patch_handle_t handle)
519{
520 Mutex::Autolock _l(mLock);
521 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
522 return sendConfigEvent_l(configEvent);
523}
524
525
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700526// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700527void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700528{
Eric Laurent10351942014-05-08 18:49:52 -0700529 bool configChanged = false;
530
Eric Laurent81784c32012-11-19 14:55:58 -0800531 while (!mConfigEvents.isEmpty()) {
Eric Laurent10351942014-05-08 18:49:52 -0700532 ALOGV("processConfigEvents_l() remaining events %d", mConfigEvents.size());
533 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800534 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700535 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700536 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700537 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
538 // FIXME Need to understand why this has to be done asynchronously
539 int err = requestPriority(data->mPid, data->mTid, data->mPrio,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700540 true /*asynchronous*/);
541 if (err != 0) {
542 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700543 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700544 }
545 } break;
546 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700547 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent021cf962014-05-13 10:18:14 -0700548 audioConfigChanged(data->mEvent, data->mParam);
Eric Laurent10351942014-05-08 18:49:52 -0700549 } break;
550 case CFG_EVENT_SET_PARAMETER: {
551 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
552 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
553 configChanged = true;
Glenn Kastend5418eb2013-08-14 13:11:06 -0700554 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700555 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700556 case CFG_EVENT_CREATE_AUDIO_PATCH: {
557 CreateAudioPatchConfigEventData *data =
558 (CreateAudioPatchConfigEventData *)event->mData.get();
559 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
560 } break;
561 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
562 ReleaseAudioPatchConfigEventData *data =
563 (ReleaseAudioPatchConfigEventData *)event->mData.get();
564 event->mStatus = releaseAudioPatch_l(data->mHandle);
565 } break;
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700566 default:
Eric Laurent10351942014-05-08 18:49:52 -0700567 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700568 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800569 }
Eric Laurent10351942014-05-08 18:49:52 -0700570 {
571 Mutex::Autolock _l(event->mLock);
572 if (event->mWaitStatus) {
573 event->mWaitStatus = false;
574 event->mCond.signal();
575 }
576 }
577 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
578 }
579
580 if (configChanged) {
581 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800582 }
Eric Laurent81784c32012-11-19 14:55:58 -0800583}
584
Marco Nelissenb2208842014-02-07 14:00:50 -0800585String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
586 String8 s;
587 if (output) {
588 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
589 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
590 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
591 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
592 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
593 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
594 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
595 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
596 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
597 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
598 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
599 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
600 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
601 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
602 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
603 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
604 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
605 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
606 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
607 } else {
608 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
609 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
610 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
611 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
612 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
613 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
614 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
615 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
616 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
617 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
618 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
619 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
620 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
621 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
622 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
623 }
624 int len = s.length();
625 if (s.length() > 2) {
626 char *str = s.lockBuffer(len);
627 s.unlockBuffer(len - 2);
628 }
629 return s;
630}
631
Glenn Kasten0f11b512014-01-31 16:18:54 -0800632void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800633{
634 const size_t SIZE = 256;
635 char buffer[SIZE];
636 String8 result;
637
638 bool locked = AudioFlinger::dumpTryLock(mLock);
639 if (!locked) {
Glenn Kasten97b7b752014-09-28 13:04:24 -0700640 dprintf(fd, "thread %p may be deadlocked\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -0800641 }
642
Elliott Hughes87cebad2014-05-22 10:14:43 -0700643 dprintf(fd, " I/O handle: %d\n", mId);
644 dprintf(fd, " TID: %d\n", getTid());
645 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700646 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700647 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700648 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat));
Elliott Hughes87cebad2014-05-22 10:14:43 -0700649 dprintf(fd, " HAL buffer size: %u bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700650 dprintf(fd, " Channel count: %u\n", mChannelCount);
651 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800652 channelMaskToString(mChannelMask, mType != RECORD).string());
Glenn Kasten97b7b752014-09-28 13:04:24 -0700653 dprintf(fd, " Format: 0x%x (%s)\n", mFormat, formatToString(mFormat));
654 dprintf(fd, " Frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700655 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800656 size_t numConfig = mConfigEvents.size();
657 if (numConfig) {
658 for (size_t i = 0; i < numConfig; i++) {
659 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700660 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800661 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700662 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800663 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700664 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800665 }
Eric Laurent81784c32012-11-19 14:55:58 -0800666
667 if (locked) {
668 mLock.unlock();
669 }
670}
671
672void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
673{
674 const size_t SIZE = 256;
675 char buffer[SIZE];
676 String8 result;
677
Marco Nelissenb2208842014-02-07 14:00:50 -0800678 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000679 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800680 write(fd, buffer, strlen(buffer));
681
Marco Nelissenb2208842014-02-07 14:00:50 -0800682 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800683 sp<EffectChain> chain = mEffectChains[i];
684 if (chain != 0) {
685 chain->dump(fd, args);
686 }
687 }
688}
689
Marco Nelissene14a5d62013-10-03 08:51:24 -0700690void AudioFlinger::ThreadBase::acquireWakeLock(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800691{
692 Mutex::Autolock _l(mLock);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700693 acquireWakeLock_l(uid);
Eric Laurent81784c32012-11-19 14:55:58 -0800694}
695
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100696String16 AudioFlinger::ThreadBase::getWakeLockTag()
697{
698 switch (mType) {
699 case MIXER:
700 return String16("AudioMix");
701 case DIRECT:
702 return String16("AudioDirectOut");
703 case DUPLICATING:
704 return String16("AudioDup");
705 case RECORD:
706 return String16("AudioIn");
707 case OFFLOAD:
708 return String16("AudioOffload");
709 default:
710 ALOG_ASSERT(false);
711 return String16("AudioUnknown");
712 }
713}
714
Marco Nelissene14a5d62013-10-03 08:51:24 -0700715void AudioFlinger::ThreadBase::acquireWakeLock_l(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800716{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800717 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800718 if (mPowerManager != 0) {
719 sp<IBinder> binder = new BBinder();
Marco Nelissene14a5d62013-10-03 08:51:24 -0700720 status_t status;
721 if (uid >= 0) {
Eric Laurent547789d2013-10-04 11:46:55 -0700722 status = mPowerManager->acquireWakeLockWithUid(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700723 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100724 getWakeLockTag(),
Marco Nelissene14a5d62013-10-03 08:51:24 -0700725 String16("media"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700726 uid,
727 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700728 } else {
Eric Laurent547789d2013-10-04 11:46:55 -0700729 status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700730 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100731 getWakeLockTag(),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700732 String16("media"),
733 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700734 }
Eric Laurent81784c32012-11-19 14:55:58 -0800735 if (status == NO_ERROR) {
736 mWakeLockToken = binder;
737 }
738 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
739 }
740}
741
742void AudioFlinger::ThreadBase::releaseWakeLock()
743{
744 Mutex::Autolock _l(mLock);
745 releaseWakeLock_l();
746}
747
748void AudioFlinger::ThreadBase::releaseWakeLock_l()
749{
750 if (mWakeLockToken != 0) {
751 ALOGV("releaseWakeLock_l() %s", mName);
752 if (mPowerManager != 0) {
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700753 mPowerManager->releaseWakeLock(mWakeLockToken, 0,
754 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800755 }
756 mWakeLockToken.clear();
757 }
758}
759
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800760void AudioFlinger::ThreadBase::updateWakeLockUids(const SortedVector<int> &uids) {
761 Mutex::Autolock _l(mLock);
762 updateWakeLockUids_l(uids);
763}
764
765void AudioFlinger::ThreadBase::getPowerManager_l() {
766
767 if (mPowerManager == 0) {
768 // use checkService() to avoid blocking if power service is not up yet
769 sp<IBinder> binder =
770 defaultServiceManager()->checkService(String16("power"));
771 if (binder == 0) {
772 ALOGW("Thread %s cannot connect to the power manager service", mName);
773 } else {
774 mPowerManager = interface_cast<IPowerManager>(binder);
775 binder->linkToDeath(mDeathRecipient);
776 }
777 }
778}
779
780void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<int> &uids) {
781
782 getPowerManager_l();
783 if (mWakeLockToken == NULL) {
784 ALOGE("no wake lock to update!");
785 return;
786 }
787 if (mPowerManager != 0) {
788 sp<IBinder> binder = new BBinder();
789 status_t status;
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700790 status = mPowerManager->updateWakeLockUids(mWakeLockToken, uids.size(), uids.array(),
791 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800792 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
793 }
794}
795
Eric Laurent81784c32012-11-19 14:55:58 -0800796void AudioFlinger::ThreadBase::clearPowerManager()
797{
798 Mutex::Autolock _l(mLock);
799 releaseWakeLock_l();
800 mPowerManager.clear();
801}
802
Glenn Kasten0f11b512014-01-31 16:18:54 -0800803void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800804{
805 sp<ThreadBase> thread = mThread.promote();
806 if (thread != 0) {
807 thread->clearPowerManager();
808 }
809 ALOGW("power manager service died !!!");
810}
811
812void AudioFlinger::ThreadBase::setEffectSuspended(
813 const effect_uuid_t *type, bool suspend, int sessionId)
814{
815 Mutex::Autolock _l(mLock);
816 setEffectSuspended_l(type, suspend, sessionId);
817}
818
819void AudioFlinger::ThreadBase::setEffectSuspended_l(
820 const effect_uuid_t *type, bool suspend, int sessionId)
821{
822 sp<EffectChain> chain = getEffectChain_l(sessionId);
823 if (chain != 0) {
824 if (type != NULL) {
825 chain->setEffectSuspended_l(type, suspend);
826 } else {
827 chain->setEffectSuspendedAll_l(suspend);
828 }
829 }
830
831 updateSuspendedSessions_l(type, suspend, sessionId);
832}
833
834void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
835{
836 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
837 if (index < 0) {
838 return;
839 }
840
841 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
842 mSuspendedSessions.valueAt(index);
843
844 for (size_t i = 0; i < sessionEffects.size(); i++) {
845 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
846 for (int j = 0; j < desc->mRefCount; j++) {
847 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
848 chain->setEffectSuspendedAll_l(true);
849 } else {
850 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
851 desc->mType.timeLow);
852 chain->setEffectSuspended_l(&desc->mType, true);
853 }
854 }
855 }
856}
857
858void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
859 bool suspend,
860 int sessionId)
861{
862 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
863
864 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
865
866 if (suspend) {
867 if (index >= 0) {
868 sessionEffects = mSuspendedSessions.valueAt(index);
869 } else {
870 mSuspendedSessions.add(sessionId, sessionEffects);
871 }
872 } else {
873 if (index < 0) {
874 return;
875 }
876 sessionEffects = mSuspendedSessions.valueAt(index);
877 }
878
879
880 int key = EffectChain::kKeyForSuspendAll;
881 if (type != NULL) {
882 key = type->timeLow;
883 }
884 index = sessionEffects.indexOfKey(key);
885
886 sp<SuspendedSessionDesc> desc;
887 if (suspend) {
888 if (index >= 0) {
889 desc = sessionEffects.valueAt(index);
890 } else {
891 desc = new SuspendedSessionDesc();
892 if (type != NULL) {
893 desc->mType = *type;
894 }
895 sessionEffects.add(key, desc);
896 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
897 }
898 desc->mRefCount++;
899 } else {
900 if (index < 0) {
901 return;
902 }
903 desc = sessionEffects.valueAt(index);
904 if (--desc->mRefCount == 0) {
905 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
906 sessionEffects.removeItemsAt(index);
907 if (sessionEffects.isEmpty()) {
908 ALOGV("updateSuspendedSessions_l() restore removing session %d",
909 sessionId);
910 mSuspendedSessions.removeItem(sessionId);
911 }
912 }
913 }
914 if (!sessionEffects.isEmpty()) {
915 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
916 }
917}
918
919void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
920 bool enabled,
921 int sessionId)
922{
923 Mutex::Autolock _l(mLock);
924 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
925}
926
927void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
928 bool enabled,
929 int sessionId)
930{
931 if (mType != RECORD) {
932 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
933 // another session. This gives the priority to well behaved effect control panels
934 // and applications not using global effects.
935 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
936 // global effects
937 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
938 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
939 }
940 }
941
942 sp<EffectChain> chain = getEffectChain_l(sessionId);
943 if (chain != 0) {
944 chain->checkSuspendOnEffectEnabled(effect, enabled);
945 }
946}
947
948// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
949sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
950 const sp<AudioFlinger::Client>& client,
951 const sp<IEffectClient>& effectClient,
952 int32_t priority,
953 int sessionId,
954 effect_descriptor_t *desc,
955 int *enabled,
Glenn Kasten9156ef32013-08-06 15:39:08 -0700956 status_t *status)
Eric Laurent81784c32012-11-19 14:55:58 -0800957{
958 sp<EffectModule> effect;
959 sp<EffectHandle> handle;
960 status_t lStatus;
961 sp<EffectChain> chain;
962 bool chainCreated = false;
963 bool effectCreated = false;
964 bool effectRegistered = false;
965
966 lStatus = initCheck();
967 if (lStatus != NO_ERROR) {
968 ALOGW("createEffect_l() Audio driver not initialized.");
969 goto Exit;
970 }
971
Andy Hung98ef9782014-03-04 14:46:50 -0800972 // Reject any effect on Direct output threads for now, since the format of
973 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
974 if (mType == DIRECT) {
975 ALOGW("createEffect_l() Cannot add effect %s on Direct output type thread %s",
976 desc->name, mName);
977 lStatus = BAD_VALUE;
978 goto Exit;
979 }
980
Andy Hung389cfdb2014-08-07 17:49:53 -0700981 // Reject any effect on mixer or duplicating multichannel sinks.
Andy Hung9a592762014-07-21 21:56:01 -0700982 // TODO: fix both format and multichannel issues with effects.
Andy Hung389cfdb2014-08-07 17:49:53 -0700983 if ((mType == MIXER || mType == DUPLICATING) && mChannelCount != FCC_2) {
984 ALOGW("createEffect_l() Cannot add effect %s for multichannel(%d) %s threads",
985 desc->name, mChannelCount, mType == MIXER ? "MIXER" : "DUPLICATING");
Andy Hung9a592762014-07-21 21:56:01 -0700986 lStatus = BAD_VALUE;
987 goto Exit;
988 }
989
Eric Laurent5baf2af2013-09-12 17:37:00 -0700990 // Allow global effects only on offloaded and mixer threads
991 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
992 switch (mType) {
993 case MIXER:
994 case OFFLOAD:
995 break;
996 case DIRECT:
997 case DUPLICATING:
998 case RECORD:
999 default:
1000 ALOGW("createEffect_l() Cannot add global effect %s on thread %s", desc->name, mName);
1001 lStatus = BAD_VALUE;
1002 goto Exit;
1003 }
Eric Laurent81784c32012-11-19 14:55:58 -08001004 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07001005
Eric Laurent81784c32012-11-19 14:55:58 -08001006 // Only Pre processor effects are allowed on input threads and only on input threads
1007 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
1008 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
1009 desc->name, desc->flags, mType);
1010 lStatus = BAD_VALUE;
1011 goto Exit;
1012 }
1013
1014 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1015
1016 { // scope for mLock
1017 Mutex::Autolock _l(mLock);
1018
1019 // check for existing effect chain with the requested audio session
1020 chain = getEffectChain_l(sessionId);
1021 if (chain == 0) {
1022 // create a new chain for this session
1023 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1024 chain = new EffectChain(this, sessionId);
1025 addEffectChain_l(chain);
1026 chain->setStrategy(getStrategyForSession_l(sessionId));
1027 chainCreated = true;
1028 } else {
1029 effect = chain->getEffectFromDesc_l(desc);
1030 }
1031
1032 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1033
1034 if (effect == 0) {
1035 int id = mAudioFlinger->nextUniqueId();
1036 // Check CPU and memory usage
1037 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
1038 if (lStatus != NO_ERROR) {
1039 goto Exit;
1040 }
1041 effectRegistered = true;
1042 // create a new effect module if none present in the chain
1043 effect = new EffectModule(this, chain, desc, id, sessionId);
1044 lStatus = effect->status();
1045 if (lStatus != NO_ERROR) {
1046 goto Exit;
1047 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07001048 effect->setOffloaded(mType == OFFLOAD, mId);
1049
Eric Laurent81784c32012-11-19 14:55:58 -08001050 lStatus = chain->addEffect_l(effect);
1051 if (lStatus != NO_ERROR) {
1052 goto Exit;
1053 }
1054 effectCreated = true;
1055
1056 effect->setDevice(mOutDevice);
1057 effect->setDevice(mInDevice);
1058 effect->setMode(mAudioFlinger->getMode());
1059 effect->setAudioSource(mAudioSource);
1060 }
1061 // create effect handle and connect it to effect module
1062 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001063 lStatus = handle->initCheck();
1064 if (lStatus == OK) {
1065 lStatus = effect->addHandle(handle.get());
1066 }
Eric Laurent81784c32012-11-19 14:55:58 -08001067 if (enabled != NULL) {
1068 *enabled = (int)effect->isEnabled();
1069 }
1070 }
1071
1072Exit:
1073 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1074 Mutex::Autolock _l(mLock);
1075 if (effectCreated) {
1076 chain->removeEffect_l(effect);
1077 }
1078 if (effectRegistered) {
1079 AudioSystem::unregisterEffect(effect->id());
1080 }
1081 if (chainCreated) {
1082 removeEffectChain_l(chain);
1083 }
1084 handle.clear();
1085 }
1086
Glenn Kasten9156ef32013-08-06 15:39:08 -07001087 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001088 return handle;
1089}
1090
1091sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
1092{
1093 Mutex::Autolock _l(mLock);
1094 return getEffect_l(sessionId, effectId);
1095}
1096
1097sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
1098{
1099 sp<EffectChain> chain = getEffectChain_l(sessionId);
1100 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1101}
1102
1103// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1104// PlaybackThread::mLock held
1105status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1106{
1107 // check for existing effect chain with the requested audio session
1108 int sessionId = effect->sessionId();
1109 sp<EffectChain> chain = getEffectChain_l(sessionId);
1110 bool chainCreated = false;
1111
Eric Laurent5baf2af2013-09-12 17:37:00 -07001112 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
1113 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
1114 this, effect->desc().name, effect->desc().flags);
1115
Eric Laurent81784c32012-11-19 14:55:58 -08001116 if (chain == 0) {
1117 // create a new chain for this session
1118 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1119 chain = new EffectChain(this, sessionId);
1120 addEffectChain_l(chain);
1121 chain->setStrategy(getStrategyForSession_l(sessionId));
1122 chainCreated = true;
1123 }
1124 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1125
1126 if (chain->getEffectFromId_l(effect->id()) != 0) {
1127 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1128 this, effect->desc().name, chain.get());
1129 return BAD_VALUE;
1130 }
1131
Eric Laurent5baf2af2013-09-12 17:37:00 -07001132 effect->setOffloaded(mType == OFFLOAD, mId);
1133
Eric Laurent81784c32012-11-19 14:55:58 -08001134 status_t status = chain->addEffect_l(effect);
1135 if (status != NO_ERROR) {
1136 if (chainCreated) {
1137 removeEffectChain_l(chain);
1138 }
1139 return status;
1140 }
1141
1142 effect->setDevice(mOutDevice);
1143 effect->setDevice(mInDevice);
1144 effect->setMode(mAudioFlinger->getMode());
1145 effect->setAudioSource(mAudioSource);
1146 return NO_ERROR;
1147}
1148
1149void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
1150
1151 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
1152 effect_descriptor_t desc = effect->desc();
1153 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1154 detachAuxEffect_l(effect->id());
1155 }
1156
1157 sp<EffectChain> chain = effect->chain().promote();
1158 if (chain != 0) {
1159 // remove effect chain if removing last effect
1160 if (chain->removeEffect_l(effect) == 0) {
1161 removeEffectChain_l(chain);
1162 }
1163 } else {
1164 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1165 }
1166}
1167
1168void AudioFlinger::ThreadBase::lockEffectChains_l(
1169 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1170{
1171 effectChains = mEffectChains;
1172 for (size_t i = 0; i < mEffectChains.size(); i++) {
1173 mEffectChains[i]->lock();
1174 }
1175}
1176
1177void AudioFlinger::ThreadBase::unlockEffectChains(
1178 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1179{
1180 for (size_t i = 0; i < effectChains.size(); i++) {
1181 effectChains[i]->unlock();
1182 }
1183}
1184
1185sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
1186{
1187 Mutex::Autolock _l(mLock);
1188 return getEffectChain_l(sessionId);
1189}
1190
1191sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const
1192{
1193 size_t size = mEffectChains.size();
1194 for (size_t i = 0; i < size; i++) {
1195 if (mEffectChains[i]->sessionId() == sessionId) {
1196 return mEffectChains[i];
1197 }
1198 }
1199 return 0;
1200}
1201
1202void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1203{
1204 Mutex::Autolock _l(mLock);
1205 size_t size = mEffectChains.size();
1206 for (size_t i = 0; i < size; i++) {
1207 mEffectChains[i]->setMode_l(mode);
1208 }
1209}
1210
Eric Laurent83b88082014-06-20 18:31:16 -07001211void AudioFlinger::ThreadBase::getAudioPortConfig(struct audio_port_config *config)
1212{
1213 config->type = AUDIO_PORT_TYPE_MIX;
1214 config->ext.mix.handle = mId;
1215 config->sample_rate = mSampleRate;
1216 config->format = mFormat;
1217 config->channel_mask = mChannelMask;
1218 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1219 AUDIO_PORT_CONFIG_FORMAT;
1220}
1221
1222
Eric Laurent81784c32012-11-19 14:55:58 -08001223// ----------------------------------------------------------------------------
1224// Playback
1225// ----------------------------------------------------------------------------
1226
1227AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1228 AudioStreamOut* output,
1229 audio_io_handle_t id,
1230 audio_devices_t device,
1231 type_t type)
1232 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type),
Andy Hung2098f272014-02-27 14:00:06 -08001233 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001234 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001235 mMixerBuffer(NULL),
1236 mMixerBufferSize(0),
1237 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1238 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001239 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001240 mEffectBuffer(NULL),
1241 mEffectBufferSize(0),
1242 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1243 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001244 mSuspended(0), mBytesWritten(0),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001245 mActiveTracksGeneration(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001246 // mStreamTypes[] initialized in constructor body
1247 mOutput(output),
1248 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
1249 mMixerStatus(MIXER_IDLE),
1250 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
1251 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001252 mBytesRemaining(0),
1253 mCurrentWriteLength(0),
1254 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001255 mWriteAckSequence(0),
1256 mDrainSequence(0),
Eric Laurentede6c3b2013-09-19 14:37:46 -07001257 mSignalPending(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001258 mScreenState(AudioFlinger::mScreenState),
1259 // index 0 is reserved for normal mixer's submix
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001260 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1),
Eric Laurentd1f69b02014-12-15 14:33:13 -08001261 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001262 // mLatchD, mLatchQ,
1263 mLatchDValid(false), mLatchQValid(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001264{
1265 snprintf(mName, kNameLength, "AudioOut_%X", id);
Glenn Kasten9e58b552013-01-18 15:09:48 -08001266 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mName);
Eric Laurent81784c32012-11-19 14:55:58 -08001267
1268 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1269 // it would be safer to explicitly pass initial masterVolume/masterMute as
1270 // parameter.
1271 //
1272 // If the HAL we are using has support for master volume or master mute,
1273 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1274 // and the mute set to false).
1275 mMasterVolume = audioFlinger->masterVolume_l();
1276 mMasterMute = audioFlinger->masterMute_l();
1277 if (mOutput && mOutput->audioHwDev) {
1278 if (mOutput->audioHwDev->canSetMasterVolume()) {
1279 mMasterVolume = 1.0;
1280 }
1281
1282 if (mOutput->audioHwDev->canSetMasterMute()) {
1283 mMasterMute = false;
1284 }
1285 }
1286
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001287 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001288
Eric Laurent223fd5c2014-11-11 13:43:36 -08001289 // ++ operator does not compile
Glenn Kasten66e46352014-01-16 17:44:23 -08001290 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001291 stream = (audio_stream_type_t) (stream + 1)) {
1292 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1293 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1294 }
Eric Laurent81784c32012-11-19 14:55:58 -08001295}
1296
1297AudioFlinger::PlaybackThread::~PlaybackThread()
1298{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001299 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001300 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001301 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001302 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001303}
1304
1305void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1306{
1307 dumpInternals(fd, args);
1308 dumpTracks(fd, args);
1309 dumpEffectChains(fd, args);
1310}
1311
Glenn Kasten0f11b512014-01-31 16:18:54 -08001312void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001313{
1314 const size_t SIZE = 256;
1315 char buffer[SIZE];
1316 String8 result;
1317
Marco Nelissenb2208842014-02-07 14:00:50 -08001318 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001319 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1320 const stream_type_t *st = &mStreamTypes[i];
1321 if (i > 0) {
1322 result.appendFormat(", ");
1323 }
1324 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1325 if (st->mute) {
1326 result.append("M");
1327 }
1328 }
1329 result.append("\n");
1330 write(fd, result.string(), result.length());
1331 result.clear();
1332
Eric Laurent81784c32012-11-19 14:55:58 -08001333 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1334 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001335 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001336 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001337
1338 size_t numtracks = mTracks.size();
1339 size_t numactive = mActiveTracks.size();
Elliott Hughes87cebad2014-05-22 10:14:43 -07001340 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001341 size_t numactiveseen = 0;
1342 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07001343 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08001344 Track::appendDumpHeader(result);
1345 for (size_t i = 0; i < numtracks; ++i) {
1346 sp<Track> track = mTracks[i];
1347 if (track != 0) {
1348 bool active = mActiveTracks.indexOf(track) >= 0;
1349 if (active) {
1350 numactiveseen++;
1351 }
1352 track->dump(buffer, SIZE, active);
1353 result.append(buffer);
1354 }
1355 }
1356 } else {
1357 result.append("\n");
1358 }
1359 if (numactiveseen != numactive) {
1360 // some tracks in the active list were not in the tracks list
1361 snprintf(buffer, SIZE, " The following tracks are in the active list but"
1362 " not in the track list\n");
1363 result.append(buffer);
1364 Track::appendDumpHeader(result);
1365 for (size_t i = 0; i < numactive; ++i) {
1366 sp<Track> track = mActiveTracks[i].promote();
1367 if (track != 0 && mTracks.indexOf(track) < 0) {
1368 track->dump(buffer, SIZE, true);
1369 result.append(buffer);
1370 }
1371 }
1372 }
1373
1374 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001375}
1376
1377void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1378{
Glenn Kasten97b7b752014-09-28 13:04:24 -07001379 dprintf(fd, "\nOutput thread %p type %d (%s):\n", this, type(), threadTypeToString(type()));
Elliott Hughes87cebad2014-05-22 10:14:43 -07001380 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
1381 dprintf(fd, " Last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1382 dprintf(fd, " Total writes: %d\n", mNumWrites);
1383 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1384 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1385 dprintf(fd, " Suspend count: %d\n", mSuspended);
1386 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1387 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1388 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1389 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001390 AudioStreamOut *output = mOutput;
1391 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
1392 String8 flagsAsString = outputFlagsToString(flags);
1393 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n", output, flags, flagsAsString.string());
Eric Laurent81784c32012-11-19 14:55:58 -08001394
1395 dumpBase(fd, args);
1396}
1397
1398// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001399
1400void AudioFlinger::PlaybackThread::onFirstRef()
1401{
1402 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
1403}
1404
1405// ThreadBase virtuals
1406void AudioFlinger::PlaybackThread::preExit()
1407{
1408 ALOGV(" preExit()");
1409 // FIXME this is using hard-coded strings but in the future, this functionality will be
1410 // converted to use audio HAL extensions required to support tunneling
1411 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1412}
1413
1414// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1415sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1416 const sp<AudioFlinger::Client>& client,
1417 audio_stream_type_t streamType,
1418 uint32_t sampleRate,
1419 audio_format_t format,
1420 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001421 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001422 const sp<IMemory>& sharedBuffer,
1423 int sessionId,
1424 IAudioFlinger::track_flags_t *flags,
1425 pid_t tid,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001426 int uid,
Eric Laurent81784c32012-11-19 14:55:58 -08001427 status_t *status)
1428{
Glenn Kasten74935e42013-12-19 08:56:45 -08001429 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001430 sp<Track> track;
1431 status_t lStatus;
1432
1433 bool isTimed = (*flags & IAudioFlinger::TRACK_TIMED) != 0;
1434
1435 // client expresses a preference for FAST, but we get the final say
1436 if (*flags & IAudioFlinger::TRACK_FAST) {
1437 if (
1438 // not timed
1439 (!isTimed) &&
1440 // either of these use cases:
1441 (
1442 // use case 1: shared buffer with any frame count
1443 (
1444 (sharedBuffer != 0)
1445 ) ||
1446 // use case 2: callback handler and frame count is default or at least as large as HAL
1447 (
1448 (tid != -1) &&
1449 ((frameCount == 0) ||
Glenn Kastenb5fed682013-12-03 09:06:43 -08001450 (frameCount >= mFrameCount))
Eric Laurent81784c32012-11-19 14:55:58 -08001451 )
1452 ) &&
1453 // PCM data
1454 audio_is_linear_pcm(format) &&
Andy Hung9a592762014-07-21 21:56:01 -07001455 // identical channel mask to sink, or mono in and stereo sink
1456 (channelMask == mChannelMask ||
1457 (channelMask == AUDIO_CHANNEL_OUT_MONO &&
1458 mChannelMask == AUDIO_CHANNEL_OUT_STEREO)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001459 // hardware sample rate
1460 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001461 // normal mixer has an associated fast mixer
1462 hasFastMixer() &&
1463 // there are sufficient fast track slots available
1464 (mFastTrackAvailMask != 0)
1465 // FIXME test that MixerThread for this fast track has a capable output HAL
1466 // FIXME add a permission test also?
1467 ) {
1468 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1469 if (frameCount == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001470 // read the fast track multiplier property the first time it is needed
1471 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1472 if (ok != 0) {
1473 ALOGE("%s pthread_once failed: %d", __func__, ok);
1474 }
1475 frameCount = mFrameCount * sFastTrackMultiplier;
Eric Laurent81784c32012-11-19 14:55:58 -08001476 }
1477 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
1478 frameCount, mFrameCount);
1479 } else {
1480 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
Andy Hung6146c082014-03-18 11:56:15 -07001481 "mFrameCount=%d format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
1482 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001483 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Andy Hung6146c082014-03-18 11:56:15 -07001484 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001485 audio_is_linear_pcm(format),
1486 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
1487 *flags &= ~IAudioFlinger::TRACK_FAST;
Andy Hung0e48d252015-01-26 11:43:15 -08001488 }
1489 }
1490 // For normal PCM streaming tracks, update minimum frame count.
1491 // For compatibility with AudioTrack calculation, buffer depth is forced
1492 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1493 // This is probably too conservative, but legacy application code may depend on it.
1494 // If you change this calculation, also review the start threshold which is related.
1495 if (!(*flags & IAudioFlinger::TRACK_FAST)
1496 && audio_is_linear_pcm(format) && sharedBuffer == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001497 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1498 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1499 if (minBufCount < 2) {
1500 minBufCount = 2;
1501 }
Andy Hung0e48d252015-01-26 11:43:15 -08001502 size_t minFrameCount =
1503 minBufCount * sourceFramesNeeded(sampleRate, mNormalFrameCount, mSampleRate);
1504 if (frameCount < minFrameCount) { // including frameCount == 0
Eric Laurent81784c32012-11-19 14:55:58 -08001505 frameCount = minFrameCount;
1506 }
Eric Laurent81784c32012-11-19 14:55:58 -08001507 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001508 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001509
Glenn Kastenc3df8382014-03-13 15:05:25 -07001510 switch (mType) {
1511
1512 case DIRECT:
Glenn Kasten993fa062014-05-02 11:14:34 -07001513 if (audio_is_linear_pcm(format)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001514 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001515 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1516 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001517 sampleRate, format, channelMask, mOutput, mFormat);
1518 lStatus = BAD_VALUE;
1519 goto Exit;
1520 }
1521 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001522 break;
1523
1524 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001525 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001526 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1527 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001528 sampleRate, format, channelMask, mOutput, mFormat);
1529 lStatus = BAD_VALUE;
1530 goto Exit;
1531 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001532 break;
1533
1534 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07001535 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001536 ALOGE("createTrack_l() Bad parameter: format %#x \""
1537 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001538 format, mOutput, mFormat);
1539 lStatus = BAD_VALUE;
1540 goto Exit;
1541 }
Andy Hungcd044842014-08-07 11:04:34 -07001542 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08001543 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1544 lStatus = BAD_VALUE;
1545 goto Exit;
1546 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001547 break;
1548
Eric Laurent81784c32012-11-19 14:55:58 -08001549 }
1550
1551 lStatus = initCheck();
1552 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07001553 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08001554 goto Exit;
1555 }
1556
1557 { // scope for mLock
1558 Mutex::Autolock _l(mLock);
1559
1560 // all tracks in same audio session must share the same routing strategy otherwise
1561 // conflicts will happen when tracks are moved from one output to another by audio policy
1562 // manager
1563 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1564 for (size_t i = 0; i < mTracks.size(); ++i) {
1565 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07001566 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001567 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1568 if (sessionId == t->sessionId() && strategy != actual) {
1569 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1570 strategy, actual);
1571 lStatus = BAD_VALUE;
1572 goto Exit;
1573 }
1574 }
1575 }
1576
1577 if (!isTimed) {
1578 track = new Track(this, client, streamType, sampleRate, format,
Eric Laurent83b88082014-06-20 18:31:16 -07001579 channelMask, frameCount, NULL, sharedBuffer,
1580 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08001581 } else {
1582 track = TimedTrack::create(this, client, streamType, sampleRate, format,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001583 channelMask, frameCount, sharedBuffer, sessionId, uid);
Eric Laurent81784c32012-11-19 14:55:58 -08001584 }
Glenn Kasten03003332013-08-06 15:40:54 -07001585
1586 // new Track always returns non-NULL,
1587 // but TimedTrack::create() is a factory that could fail by returning NULL
1588 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
1589 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08001590 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001591 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08001592 goto Exit;
1593 }
1594 mTracks.add(track);
1595
1596 sp<EffectChain> chain = getEffectChain_l(sessionId);
1597 if (chain != 0) {
1598 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1599 track->setMainBuffer(chain->inBuffer());
1600 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1601 chain->incTrackCnt();
1602 }
1603
1604 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1605 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1606 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1607 // so ask activity manager to do this on our behalf
1608 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1609 }
1610 }
1611
1612 lStatus = NO_ERROR;
1613
1614Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001615 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001616 return track;
1617}
1618
1619uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1620{
1621 return latency;
1622}
1623
1624uint32_t AudioFlinger::PlaybackThread::latency() const
1625{
1626 Mutex::Autolock _l(mLock);
1627 return latency_l();
1628}
1629uint32_t AudioFlinger::PlaybackThread::latency_l() const
1630{
1631 if (initCheck() == NO_ERROR) {
1632 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
1633 } else {
1634 return 0;
1635 }
1636}
1637
1638void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1639{
1640 Mutex::Autolock _l(mLock);
1641 // Don't apply master volume in SW if our HAL can do it for us.
1642 if (mOutput && mOutput->audioHwDev &&
1643 mOutput->audioHwDev->canSetMasterVolume()) {
1644 mMasterVolume = 1.0;
1645 } else {
1646 mMasterVolume = value;
1647 }
1648}
1649
1650void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1651{
1652 Mutex::Autolock _l(mLock);
1653 // Don't apply master mute in SW if our HAL can do it for us.
1654 if (mOutput && mOutput->audioHwDev &&
1655 mOutput->audioHwDev->canSetMasterMute()) {
1656 mMasterMute = false;
1657 } else {
1658 mMasterMute = muted;
1659 }
1660}
1661
1662void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
1663{
1664 Mutex::Autolock _l(mLock);
1665 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001666 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001667}
1668
1669void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
1670{
1671 Mutex::Autolock _l(mLock);
1672 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001673 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001674}
1675
1676float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
1677{
1678 Mutex::Autolock _l(mLock);
1679 return mStreamTypes[stream].volume;
1680}
1681
1682// addTrack_l() must be called with ThreadBase::mLock held
1683status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1684{
1685 status_t status = ALREADY_EXISTS;
1686
1687 // set retry count for buffer fill
1688 track->mRetryCount = kMaxTrackStartupRetries;
1689 if (mActiveTracks.indexOf(track) < 0) {
1690 // the track is newly added, make sure it fills up all its
1691 // buffers before playing. This is to ensure the client will
1692 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07001693 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001694 TrackBase::track_state state = track->mState;
1695 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08001696 status = AudioSystem::startOutput(mId, track->streamType(),
1697 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001698 mLock.lock();
1699 // abort track was stopped/paused while we released the lock
1700 if (state != track->mState) {
1701 if (status == NO_ERROR) {
1702 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08001703 AudioSystem::stopOutput(mId, track->streamType(),
1704 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001705 mLock.lock();
1706 }
1707 return INVALID_OPERATION;
1708 }
1709 // abort if start is rejected by audio policy manager
1710 if (status != NO_ERROR) {
1711 return PERMISSION_DENIED;
1712 }
1713#ifdef ADD_BATTERY_DATA
1714 // to track the speaker usage
1715 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
1716#endif
1717 }
1718
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001719 track->mFillingUpStatus = track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent81784c32012-11-19 14:55:58 -08001720 track->mResetDone = false;
1721 track->mPresentationCompleteFrames = 0;
1722 mActiveTracks.add(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001723 mWakeLockUids.add(track->uid());
1724 mActiveTracksGeneration++;
Eric Laurentfd477972013-10-25 18:10:40 -07001725 mLatestActiveTrack = track;
Eric Laurentd0107bc2013-06-11 14:38:48 -07001726 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1727 if (chain != 0) {
1728 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
1729 track->sessionId());
1730 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08001731 }
1732
1733 status = NO_ERROR;
1734 }
1735
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08001736 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001737 return status;
1738}
1739
Eric Laurentbfb1b832013-01-07 09:53:42 -08001740bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08001741{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001742 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08001743 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001744 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
1745 track->mState = TrackBase::STOPPED;
1746 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08001747 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07001748 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001749 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08001750 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001751
1752 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08001753}
1754
1755void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1756{
1757 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
1758 mTracks.remove(track);
1759 deleteTrackName_l(track->name());
1760 // redundant as track is about to be destroyed, for dumpsys only
1761 track->mName = -1;
1762 if (track->isFastTrack()) {
1763 int index = track->mFastIndex;
1764 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
1765 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1766 mFastTrackAvailMask |= 1 << index;
1767 // redundant as track is about to be destroyed, for dumpsys only
1768 track->mFastIndex = -1;
1769 }
1770 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1771 if (chain != 0) {
1772 chain->decTrackCnt();
1773 }
1774}
1775
Eric Laurentede6c3b2013-09-19 14:37:46 -07001776void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001777{
1778 // Thread could be blocked waiting for async
1779 // so signal it to handle state changes immediately
1780 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1781 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1782 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001783 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001784}
1785
Eric Laurent81784c32012-11-19 14:55:58 -08001786String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1787{
Eric Laurent81784c32012-11-19 14:55:58 -08001788 Mutex::Autolock _l(mLock);
1789 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07001790 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08001791 }
1792
Glenn Kastend8ea6992013-07-16 14:17:15 -07001793 char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
1794 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08001795 free(s);
1796 return out_s8;
1797}
1798
Eric Laurent021cf962014-05-13 10:18:14 -07001799void AudioFlinger::PlaybackThread::audioConfigChanged(int event, int param) {
Eric Laurent81784c32012-11-19 14:55:58 -08001800 AudioSystem::OutputDescriptor desc;
1801 void *param2 = NULL;
1802
Eric Laurent021cf962014-05-13 10:18:14 -07001803 ALOGV("PlaybackThread::audioConfigChanged, thread %p, event %d, param %d", this, event,
Eric Laurent81784c32012-11-19 14:55:58 -08001804 param);
1805
1806 switch (event) {
1807 case AudioSystem::OUTPUT_OPENED:
1808 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07001809 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08001810 desc.samplingRate = mSampleRate;
1811 desc.format = mFormat;
1812 desc.frameCount = mNormalFrameCount; // FIXME see
1813 // AudioFlinger::frameCount(audio_io_handle_t)
Eric Laurent10351942014-05-08 18:49:52 -07001814 desc.latency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001815 param2 = &desc;
1816 break;
1817
1818 case AudioSystem::STREAM_CONFIG_CHANGED:
1819 param2 = &param;
1820 case AudioSystem::OUTPUT_CLOSED:
1821 default:
1822 break;
1823 }
Eric Laurent021cf962014-05-13 10:18:14 -07001824 mAudioFlinger->audioConfigChanged(event, mId, param2);
Eric Laurent81784c32012-11-19 14:55:58 -08001825}
1826
Eric Laurentbfb1b832013-01-07 09:53:42 -08001827void AudioFlinger::PlaybackThread::writeCallback()
1828{
1829 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001830 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001831}
1832
1833void AudioFlinger::PlaybackThread::drainCallback()
1834{
1835 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001836 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001837}
1838
Eric Laurent3b4529e2013-09-05 18:09:19 -07001839void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001840{
1841 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001842 // reject out of sequence requests
1843 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
1844 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001845 mWaitWorkCV.signal();
1846 }
1847}
1848
Eric Laurent3b4529e2013-09-05 18:09:19 -07001849void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001850{
1851 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001852 // reject out of sequence requests
1853 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
1854 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001855 mWaitWorkCV.signal();
1856 }
1857}
1858
1859// static
1860int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
Glenn Kasten0f11b512014-01-31 16:18:54 -08001861 void *param __unused,
Eric Laurentbfb1b832013-01-07 09:53:42 -08001862 void *cookie)
1863{
1864 AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
1865 ALOGV("asyncCallback() event %d", event);
1866 switch (event) {
1867 case STREAM_CBK_EVENT_WRITE_READY:
1868 me->writeCallback();
1869 break;
1870 case STREAM_CBK_EVENT_DRAIN_READY:
1871 me->drainCallback();
1872 break;
1873 default:
1874 ALOGW("asyncCallback() unknown event %d", event);
1875 break;
1876 }
1877 return 0;
1878}
1879
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001880void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001881{
Glenn Kastenadad3d72014-02-21 14:51:43 -08001882 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Eric Laurent81784c32012-11-19 14:55:58 -08001883 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
1884 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001885 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08001886 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001887 }
Andy Hung9a592762014-07-21 21:56:01 -07001888 if ((mType == MIXER || mType == DUPLICATING)
1889 && !isValidPcmSinkChannelMask(mChannelMask)) {
1890 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
1891 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001892 }
Andy Hunge5412692014-05-16 11:25:07 -07001893 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Andy Hung463be252014-07-10 16:56:07 -07001894 mHALFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
1895 mFormat = mHALFormat;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001896 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08001897 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001898 }
Andy Hung6146c082014-03-18 11:56:15 -07001899 if ((mType == MIXER || mType == DUPLICATING)
1900 && !isValidPcmSinkFormat(mFormat)) {
1901 LOG_FATAL("HAL format %#x not supported for mixed output",
1902 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001903 }
Eric Laurent665470b2014-07-03 16:37:08 -07001904 mFrameSize = audio_stream_out_frame_size(mOutput->stream);
Glenn Kasten70949c42013-08-06 07:40:12 -07001905 mBufferSize = mOutput->stream->common.get_buffer_size(&mOutput->stream->common);
1906 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08001907 if (mFrameCount & 15) {
1908 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
1909 mFrameCount);
1910 }
1911
Eric Laurentbfb1b832013-01-07 09:53:42 -08001912 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
1913 (mOutput->stream->set_callback != NULL)) {
1914 if (mOutput->stream->set_callback(mOutput->stream,
1915 AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
1916 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07001917 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001918 }
1919 }
1920
Eric Laurentd1f69b02014-12-15 14:33:13 -08001921 mHwSupportsPause = false;
1922 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
1923 if (mOutput->stream->pause != NULL) {
1924 if (mOutput->stream->resume != NULL) {
1925 mHwSupportsPause = true;
1926 } else {
1927 ALOGW("direct output implements pause but not resume");
1928 }
1929 } else if (mOutput->stream->resume != NULL) {
1930 ALOGW("direct output implements resume but not pause");
1931 }
1932 }
1933
Andy Hungfbfc3952015-01-15 13:33:51 -08001934 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
1935 // For best precision, we use float instead of the associated output
1936 // device format (typically PCM 16 bit).
1937
1938 mFormat = AUDIO_FORMAT_PCM_FLOAT;
1939 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
1940 mBufferSize = mFrameSize * mFrameCount;
1941
1942 // TODO: We currently use the associated output device channel mask and sample rate.
1943 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
1944 // (if a valid mask) to avoid premature downmix.
1945 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
1946 // instead of the output device sample rate to avoid loss of high frequency information.
1947 // This may need to be updated as MixerThread/OutputTracks are added and not here.
1948 }
1949
Andy Hung09a50072014-02-27 14:30:47 -08001950 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08001951 double multiplier = 1.0;
1952 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
1953 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08001954 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
1955 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Eric Laurent81784c32012-11-19 14:55:58 -08001956 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
1957 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
1958 maxNormalFrameCount = maxNormalFrameCount & ~15;
1959 if (maxNormalFrameCount < minNormalFrameCount) {
1960 maxNormalFrameCount = minNormalFrameCount;
1961 }
1962 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
1963 if (multiplier <= 1.0) {
1964 multiplier = 1.0;
1965 } else if (multiplier <= 2.0) {
1966 if (2 * mFrameCount <= maxNormalFrameCount) {
1967 multiplier = 2.0;
1968 } else {
1969 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
1970 }
1971 } else {
1972 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
Andy Hung09a50072014-02-27 14:30:47 -08001973 // 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 -08001974 // track, but we sometimes have to do this to satisfy the maximum frame count
1975 // constraint)
1976 // FIXME this rounding up should not be done if no HAL SRC
1977 uint32_t truncMult = (uint32_t) multiplier;
1978 if ((truncMult & 1)) {
1979 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
1980 ++truncMult;
1981 }
1982 }
1983 multiplier = (double) truncMult;
1984 }
1985 }
1986 mNormalFrameCount = multiplier * mFrameCount;
1987 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07001988 if (mType == MIXER || mType == DUPLICATING) {
1989 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
1990 }
Andy Hung09a50072014-02-27 14:30:47 -08001991 ALOGI("HAL output buffer size %u frames, normal sink buffer size %u frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001992 mNormalFrameCount);
1993
Andy Hung010a1a12014-03-13 13:57:33 -07001994 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
1995 // Originally this was int16_t[] array, need to remove legacy implications.
1996 free(mSinkBuffer);
1997 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07001998 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
1999 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2000 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002001 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002002
Andy Hung69aed5f2014-02-25 17:24:40 -08002003 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2004 // drives the output.
2005 free(mMixerBuffer);
2006 mMixerBuffer = NULL;
2007 if (mMixerBufferEnabled) {
2008 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2009 mMixerBufferSize = mNormalFrameCount * mChannelCount
2010 * audio_bytes_per_sample(mMixerBufferFormat);
2011 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2012 }
Andy Hung98ef9782014-03-04 14:46:50 -08002013 free(mEffectBuffer);
2014 mEffectBuffer = NULL;
2015 if (mEffectBufferEnabled) {
2016 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
2017 mEffectBufferSize = mNormalFrameCount * mChannelCount
2018 * audio_bytes_per_sample(mEffectBufferFormat);
2019 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2020 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002021
Eric Laurent81784c32012-11-19 14:55:58 -08002022 // force reconfiguration of effect chains and engines to take new buffer size and audio
2023 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002024 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002025 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2026 // matter.
2027 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2028 Vector< sp<EffectChain> > effectChains = mEffectChains;
2029 for (size_t i = 0; i < effectChains.size(); i ++) {
2030 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2031 }
2032}
2033
2034
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002035status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002036{
2037 if (halFrames == NULL || dspFrames == NULL) {
2038 return BAD_VALUE;
2039 }
2040 Mutex::Autolock _l(mLock);
2041 if (initCheck() != NO_ERROR) {
2042 return INVALID_OPERATION;
2043 }
2044 size_t framesWritten = mBytesWritten / mFrameSize;
2045 *halFrames = framesWritten;
2046
2047 if (isSuspended()) {
2048 // return an estimation of rendered frames when the output is suspended
2049 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
2050 *dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0;
2051 return NO_ERROR;
2052 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002053 status_t status;
2054 uint32_t frames;
2055 status = mOutput->stream->get_render_position(mOutput->stream, &frames);
2056 *dspFrames = (size_t)frames;
2057 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002058 }
2059}
2060
2061uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
2062{
2063 Mutex::Autolock _l(mLock);
2064 uint32_t result = 0;
2065 if (getEffectChain_l(sessionId) != 0) {
2066 result = EFFECT_SESSION;
2067 }
2068
2069 for (size_t i = 0; i < mTracks.size(); ++i) {
2070 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002071 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002072 result |= TRACK_SESSION;
2073 break;
2074 }
2075 }
2076
2077 return result;
2078}
2079
2080uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
2081{
2082 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2083 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2084 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2085 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2086 }
2087 for (size_t i = 0; i < mTracks.size(); i++) {
2088 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002089 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002090 return AudioSystem::getStrategyForStream(track->streamType());
2091 }
2092 }
2093 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2094}
2095
2096
2097AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
2098{
2099 Mutex::Autolock _l(mLock);
2100 return mOutput;
2101}
2102
2103AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
2104{
2105 Mutex::Autolock _l(mLock);
2106 AudioStreamOut *output = mOutput;
2107 mOutput = NULL;
2108 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2109 // must push a NULL and wait for ack
2110 mOutputSink.clear();
2111 mPipeSink.clear();
2112 mNormalSink.clear();
2113 return output;
2114}
2115
2116// this method must always be called either with ThreadBase mLock held or inside the thread loop
2117audio_stream_t* AudioFlinger::PlaybackThread::stream() const
2118{
2119 if (mOutput == NULL) {
2120 return NULL;
2121 }
2122 return &mOutput->stream->common;
2123}
2124
2125uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2126{
2127 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2128}
2129
2130status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2131{
2132 if (!isValidSyncEvent(event)) {
2133 return BAD_VALUE;
2134 }
2135
2136 Mutex::Autolock _l(mLock);
2137
2138 for (size_t i = 0; i < mTracks.size(); ++i) {
2139 sp<Track> track = mTracks[i];
2140 if (event->triggerSession() == track->sessionId()) {
2141 (void) track->setSyncEvent(event);
2142 return NO_ERROR;
2143 }
2144 }
2145
2146 return NAME_NOT_FOUND;
2147}
2148
2149bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2150{
2151 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2152}
2153
2154void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2155 const Vector< sp<Track> >& tracksToRemove)
2156{
2157 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002158 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002159 for (size_t i = 0 ; i < count ; i++) {
2160 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002161 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002162 AudioSystem::stopOutput(mId, track->streamType(),
2163 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002164#ifdef ADD_BATTERY_DATA
2165 // to track the speaker usage
2166 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2167#endif
2168 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002169 AudioSystem::releaseOutput(mId, track->streamType(),
2170 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002171 }
Eric Laurent81784c32012-11-19 14:55:58 -08002172 }
2173 }
2174 }
Eric Laurent81784c32012-11-19 14:55:58 -08002175}
2176
2177void AudioFlinger::PlaybackThread::checkSilentMode_l()
2178{
2179 if (!mMasterMute) {
2180 char value[PROPERTY_VALUE_MAX];
2181 if (property_get("ro.audio.silent", value, "0") > 0) {
2182 char *endptr;
2183 unsigned long ul = strtoul(value, &endptr, 0);
2184 if (*endptr == '\0' && ul != 0) {
2185 ALOGD("Silence is golden");
2186 // The setprop command will not allow a property to be changed after
2187 // the first time it is set, so we don't have to worry about un-muting.
2188 setMasterMute_l(true);
2189 }
2190 }
2191 }
2192}
2193
2194// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002195ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002196{
2197 // FIXME rewrite to reduce number of system calls
2198 mLastWriteTime = systemTime();
2199 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002200 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002201 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002202
2203 // If an NBAIO sink is present, use it to write the normal mixer's submix
2204 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002205
Andy Hung010a1a12014-03-13 13:57:33 -07002206 const size_t count = mBytesRemaining / mFrameSize;
2207
Simon Wilson2d590962012-11-29 15:18:50 -08002208 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002209 // update the setpoint when AudioFlinger::mScreenState changes
2210 uint32_t screenState = AudioFlinger::mScreenState;
2211 if (screenState != mScreenState) {
2212 mScreenState = screenState;
2213 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2214 if (pipe != NULL) {
2215 pipe->setAvgFrames((mScreenState & 1) ?
2216 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2217 }
2218 }
Andy Hung010a1a12014-03-13 13:57:33 -07002219 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002220 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002221 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002222 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002223 } else {
2224 bytesWritten = framesWritten;
2225 }
Glenn Kastenefaa7ab2014-08-20 08:48:54 -07002226 mLatchDValid = false;
Glenn Kasten767094d2013-08-23 13:51:43 -07002227 status_t status = mNormalSink->getTimestamp(mLatchD.mTimestamp);
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002228 if (status == NO_ERROR) {
2229 size_t totalFramesWritten = mNormalSink->framesWritten();
2230 if (totalFramesWritten >= mLatchD.mTimestamp.mPosition) {
2231 mLatchD.mUnpresentedFrames = totalFramesWritten - mLatchD.mTimestamp.mPosition;
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002232 // mLatchD.mFramesReleased is set immediately before D is clocked into Q
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002233 mLatchDValid = true;
2234 }
2235 }
Eric Laurent81784c32012-11-19 14:55:58 -08002236 // otherwise use the HAL / AudioStreamOut directly
2237 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002238 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002239
Eric Laurentbfb1b832013-01-07 09:53:42 -08002240 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002241 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2242 mWriteAckSequence += 2;
2243 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002244 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002245 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002246 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002247 // FIXME We should have an implementation of timestamps for direct output threads.
2248 // They are used e.g for multichannel PCM playback over HDMI.
Eric Laurentbfb1b832013-01-07 09:53:42 -08002249 bytesWritten = mOutput->stream->write(mOutput->stream,
Andy Hung2098f272014-02-27 14:00:06 -08002250 (char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002251 if (mUseAsyncWrite &&
2252 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2253 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002254 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002255 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002256 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002257 }
Eric Laurent81784c32012-11-19 14:55:58 -08002258 }
2259
Eric Laurent81784c32012-11-19 14:55:58 -08002260 mNumWrites++;
2261 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002262 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002263 return bytesWritten;
2264}
2265
2266void AudioFlinger::PlaybackThread::threadLoop_drain()
2267{
2268 if (mOutput->stream->drain) {
2269 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2270 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002271 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2272 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002273 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002274 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002275 }
2276 mOutput->stream->drain(mOutput->stream,
2277 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
2278 : AUDIO_DRAIN_ALL);
2279 }
2280}
2281
2282void AudioFlinger::PlaybackThread::threadLoop_exit()
2283{
Eric Laurent275e8e92014-11-30 15:14:47 -08002284 {
2285 Mutex::Autolock _l(mLock);
2286 for (size_t i = 0; i < mTracks.size(); i++) {
2287 sp<Track> track = mTracks[i];
2288 track->invalidate();
2289 }
2290 }
Eric Laurent81784c32012-11-19 14:55:58 -08002291}
2292
2293/*
2294The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002295 - mSinkBufferSize from frame count * frame size
Eric Laurent81784c32012-11-19 14:55:58 -08002296 - activeSleepTime from activeSleepTimeUs()
2297 - idleSleepTime from idleSleepTimeUs()
2298 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
2299 - maxPeriod from frame count and sample rate (MIXER only)
2300
2301The parameters that affect these derived values are:
2302 - frame count
2303 - frame size
2304 - sample rate
2305 - device type: A2DP or not
2306 - device latency
2307 - format: PCM or not
2308 - active sleep time
2309 - idle sleep time
2310*/
2311
2312void AudioFlinger::PlaybackThread::cacheParameters_l()
2313{
Andy Hung25c2dac2014-02-27 14:56:00 -08002314 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002315 activeSleepTime = activeSleepTimeUs();
2316 idleSleepTime = idleSleepTimeUs();
2317}
2318
2319void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2320{
Glenn Kasten7c027242012-12-26 14:43:16 -08002321 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurent81784c32012-11-19 14:55:58 -08002322 this, streamType, mTracks.size());
2323 Mutex::Autolock _l(mLock);
2324
2325 size_t size = mTracks.size();
2326 for (size_t i = 0; i < size; i++) {
2327 sp<Track> t = mTracks[i];
2328 if (t->streamType() == streamType) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002329 t->invalidate();
Eric Laurent81784c32012-11-19 14:55:58 -08002330 }
2331 }
2332}
2333
2334status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2335{
2336 int session = chain->sessionId();
Andy Hung010a1a12014-03-13 13:57:33 -07002337 int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled
2338 ? mEffectBuffer : mSinkBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002339 bool ownsBuffer = false;
2340
2341 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
2342 if (session > 0) {
2343 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002344 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002345 if (mType != DIRECT) {
2346 size_t numSamples = mNormalFrameCount * mChannelCount;
2347 buffer = new int16_t[numSamples];
2348 memset(buffer, 0, numSamples * sizeof(int16_t));
2349 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2350 ownsBuffer = true;
2351 }
2352
2353 // Attach all tracks with same session ID to this chain.
2354 for (size_t i = 0; i < mTracks.size(); ++i) {
2355 sp<Track> track = mTracks[i];
2356 if (session == track->sessionId()) {
2357 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2358 buffer);
2359 track->setMainBuffer(buffer);
2360 chain->incTrackCnt();
2361 }
2362 }
2363
2364 // indicate all active tracks in the chain
2365 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2366 sp<Track> track = mActiveTracks[i].promote();
2367 if (track == 0) {
2368 continue;
2369 }
2370 if (session == track->sessionId()) {
2371 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2372 chain->incActiveTrackCnt();
2373 }
2374 }
2375 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002376 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08002377 chain->setInBuffer(buffer, ownsBuffer);
Andy Hung010a1a12014-03-13 13:57:33 -07002378 chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled
2379 ? mEffectBuffer : mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002380 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
2381 // chains list in order to be processed last as it contains output stage effects
2382 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2383 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
2384 // after track specific effects and before output stage
2385 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
2386 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
2387 // Effect chain for other sessions are inserted at beginning of effect
2388 // chains list to be processed before output mix effects. Relative order between other
2389 // sessions is not important
2390 size_t size = mEffectChains.size();
2391 size_t i = 0;
2392 for (i = 0; i < size; i++) {
2393 if (mEffectChains[i]->sessionId() < session) {
2394 break;
2395 }
2396 }
2397 mEffectChains.insertAt(chain, i);
2398 checkSuspendOnAddEffectChain_l(chain);
2399
2400 return NO_ERROR;
2401}
2402
2403size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2404{
2405 int session = chain->sessionId();
2406
2407 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2408
2409 for (size_t i = 0; i < mEffectChains.size(); i++) {
2410 if (chain == mEffectChains[i]) {
2411 mEffectChains.removeAt(i);
2412 // detach all active tracks from the chain
2413 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2414 sp<Track> track = mActiveTracks[i].promote();
2415 if (track == 0) {
2416 continue;
2417 }
2418 if (session == track->sessionId()) {
2419 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2420 chain.get(), session);
2421 chain->decActiveTrackCnt();
2422 }
2423 }
2424
2425 // detach all tracks with same session ID from this chain
2426 for (size_t i = 0; i < mTracks.size(); ++i) {
2427 sp<Track> track = mTracks[i];
2428 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002429 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002430 chain->decTrackCnt();
2431 }
2432 }
2433 break;
2434 }
2435 }
2436 return mEffectChains.size();
2437}
2438
2439status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2440 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2441{
2442 Mutex::Autolock _l(mLock);
2443 return attachAuxEffect_l(track, EffectId);
2444}
2445
2446status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2447 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2448{
2449 status_t status = NO_ERROR;
2450
2451 if (EffectId == 0) {
2452 track->setAuxBuffer(0, NULL);
2453 } else {
2454 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2455 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2456 if (effect != 0) {
2457 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2458 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2459 } else {
2460 status = INVALID_OPERATION;
2461 }
2462 } else {
2463 status = BAD_VALUE;
2464 }
2465 }
2466 return status;
2467}
2468
2469void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2470{
2471 for (size_t i = 0; i < mTracks.size(); ++i) {
2472 sp<Track> track = mTracks[i];
2473 if (track->auxEffectId() == effectId) {
2474 attachAuxEffect_l(track, 0);
2475 }
2476 }
2477}
2478
2479bool AudioFlinger::PlaybackThread::threadLoop()
2480{
2481 Vector< sp<Track> > tracksToRemove;
2482
2483 standbyTime = systemTime();
2484
2485 // MIXER
2486 nsecs_t lastWarning = 0;
2487
2488 // DUPLICATING
2489 // FIXME could this be made local to while loop?
2490 writeFrames = 0;
2491
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002492 int lastGeneration = 0;
2493
Eric Laurent81784c32012-11-19 14:55:58 -08002494 cacheParameters_l();
2495 sleepTime = idleSleepTime;
2496
2497 if (mType == MIXER) {
2498 sleepTimeShift = 0;
2499 }
2500
2501 CpuStats cpuStats;
2502 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2503
2504 acquireWakeLock();
2505
Glenn Kasten9e58b552013-01-18 15:09:48 -08002506 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2507 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2508 // and then that string will be logged at the next convenient opportunity.
2509 const char *logString = NULL;
2510
Eric Laurent664539d2013-09-23 18:24:31 -07002511 checkSilentMode_l();
2512
Eric Laurent81784c32012-11-19 14:55:58 -08002513 while (!exitPending())
2514 {
2515 cpuStats.sample(myName);
2516
2517 Vector< sp<EffectChain> > effectChains;
2518
Eric Laurent81784c32012-11-19 14:55:58 -08002519 { // scope for mLock
2520
2521 Mutex::Autolock _l(mLock);
2522
Eric Laurent021cf962014-05-13 10:18:14 -07002523 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07002524
Glenn Kasten9e58b552013-01-18 15:09:48 -08002525 if (logString != NULL) {
2526 mNBLogWriter->logTimestamp();
2527 mNBLogWriter->log(logString);
2528 logString = NULL;
2529 }
2530
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002531 // Gather the framesReleased counters for all active tracks,
2532 // and latch them atomically with the timestamp.
2533 // FIXME We're using raw pointers as indices. A unique track ID would be a better index.
2534 mLatchD.mFramesReleased.clear();
2535 size_t size = mActiveTracks.size();
2536 for (size_t i = 0; i < size; i++) {
2537 sp<Track> t = mActiveTracks[i].promote();
2538 if (t != 0) {
2539 mLatchD.mFramesReleased.add(t.get(),
2540 t->mAudioTrackServerProxy->framesReleased());
2541 }
2542 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002543 if (mLatchDValid) {
2544 mLatchQ = mLatchD;
2545 mLatchDValid = false;
2546 mLatchQValid = true;
2547 }
2548
Eric Laurent81784c32012-11-19 14:55:58 -08002549 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002550 if (mSignalPending) {
2551 // A signal was raised while we were unlocked
2552 mSignalPending = false;
2553 } else if (waitingAsyncCallback_l()) {
2554 if (exitPending()) {
2555 break;
2556 }
2557 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002558 mWakeLockUids.clear();
2559 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002560 ALOGV("wait async completion");
2561 mWaitWorkCV.wait(mLock);
2562 ALOGV("async completion/wake");
2563 acquireWakeLock_l();
Eric Laurent972a1732013-09-04 09:42:59 -07002564 standbyTime = systemTime() + standbyDelay;
2565 sleepTime = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002566
2567 continue;
2568 }
2569 if ((!mActiveTracks.size() && systemTime() > standbyTime) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08002570 isSuspended()) {
2571 // put audio hardware into standby after short delay
2572 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002573
2574 threadLoop_standby();
2575
2576 mStandby = true;
2577 }
2578
2579 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2580 // we're about to wait, flush the binder command buffer
2581 IPCThreadState::self()->flushCommands();
2582
2583 clearOutputTracks();
2584
2585 if (exitPending()) {
2586 break;
2587 }
2588
2589 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002590 mWakeLockUids.clear();
2591 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002592 // wait until we have something to do...
2593 ALOGV("%s going to sleep", myName.string());
2594 mWaitWorkCV.wait(mLock);
2595 ALOGV("%s waking up", myName.string());
2596 acquireWakeLock_l();
2597
2598 mMixerStatus = MIXER_IDLE;
2599 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2600 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002601 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002602 checkSilentMode_l();
2603
2604 standbyTime = systemTime() + standbyDelay;
2605 sleepTime = idleSleepTime;
2606 if (mType == MIXER) {
2607 sleepTimeShift = 0;
2608 }
2609
2610 continue;
2611 }
2612 }
Eric Laurent81784c32012-11-19 14:55:58 -08002613 // mMixerStatusIgnoringFastTracks is also updated internally
2614 mMixerStatus = prepareTracks_l(&tracksToRemove);
2615
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002616 // compare with previously applied list
2617 if (lastGeneration != mActiveTracksGeneration) {
2618 // update wakelock
2619 updateWakeLockUids_l(mWakeLockUids);
2620 lastGeneration = mActiveTracksGeneration;
2621 }
2622
Eric Laurent81784c32012-11-19 14:55:58 -08002623 // prevent any changes in effect chain list and in each effect chain
2624 // during mixing and effect process as the audio buffers could be deleted
2625 // or modified if an effect is created or deleted
2626 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002627 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08002628
Eric Laurentbfb1b832013-01-07 09:53:42 -08002629 if (mBytesRemaining == 0) {
2630 mCurrentWriteLength = 0;
2631 if (mMixerStatus == MIXER_TRACKS_READY) {
2632 // threadLoop_mix() sets mCurrentWriteLength
2633 threadLoop_mix();
2634 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
2635 && (mMixerStatus != MIXER_DRAIN_ALL)) {
2636 // threadLoop_sleepTime sets sleepTime to 0 if data
2637 // must be written to HAL
2638 threadLoop_sleepTime();
2639 if (sleepTime == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08002640 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002641 }
2642 }
Andy Hung98ef9782014-03-04 14:46:50 -08002643 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
2644 // mMixerBuffer with data if mMixerBufferValid is true and sleepTime == 0.
2645 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
2646 // or mSinkBuffer (if there are no effects).
2647 //
2648 // This is done pre-effects computation; if effects change to
2649 // support higher precision, this needs to move.
2650 //
2651 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
2652 // TODO use sleepTime == 0 as an additional condition.
2653 if (mMixerBufferValid) {
2654 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
2655 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
2656
2657 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
2658 mNormalFrameCount * mChannelCount);
2659 }
2660
Eric Laurentbfb1b832013-01-07 09:53:42 -08002661 mBytesRemaining = mCurrentWriteLength;
2662 if (isSuspended()) {
2663 sleepTime = suspendSleepTimeUs();
2664 // simulate write to HAL when suspended
Andy Hung25c2dac2014-02-27 14:56:00 -08002665 mBytesWritten += mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002666 mBytesRemaining = 0;
2667 }
Eric Laurent81784c32012-11-19 14:55:58 -08002668
Eric Laurentbfb1b832013-01-07 09:53:42 -08002669 // only process effects if we're going to write
Eric Laurent59fe0102013-09-27 18:48:26 -07002670 if (sleepTime == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002671 for (size_t i = 0; i < effectChains.size(); i ++) {
2672 effectChains[i]->process_l();
2673 }
Eric Laurent81784c32012-11-19 14:55:58 -08002674 }
2675 }
Eric Laurent59fe0102013-09-27 18:48:26 -07002676 // Process effect chains for offloaded thread even if no audio
2677 // was read from audio track: process only updates effect state
2678 // and thus does have to be synchronized with audio writes but may have
2679 // to be called while waiting for async write callback
2680 if (mType == OFFLOAD) {
2681 for (size_t i = 0; i < effectChains.size(); i ++) {
2682 effectChains[i]->process_l();
2683 }
2684 }
Eric Laurent81784c32012-11-19 14:55:58 -08002685
Andy Hung98ef9782014-03-04 14:46:50 -08002686 // Only if the Effects buffer is enabled and there is data in the
2687 // Effects buffer (buffer valid), we need to
2688 // copy into the sink buffer.
2689 // TODO use sleepTime == 0 as an additional condition.
2690 if (mEffectBufferValid) {
2691 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
2692 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
2693 mNormalFrameCount * mChannelCount);
2694 }
2695
Eric Laurent81784c32012-11-19 14:55:58 -08002696 // enable changes in effect chain
2697 unlockEffectChains(effectChains);
2698
Eric Laurentbfb1b832013-01-07 09:53:42 -08002699 if (!waitingAsyncCallback()) {
2700 // sleepTime == 0 means we must write to audio hardware
2701 if (sleepTime == 0) {
2702 if (mBytesRemaining) {
2703 ssize_t ret = threadLoop_write();
2704 if (ret < 0) {
2705 mBytesRemaining = 0;
2706 } else {
2707 mBytesWritten += ret;
2708 mBytesRemaining -= ret;
2709 }
2710 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
2711 (mMixerStatus == MIXER_DRAIN_ALL)) {
2712 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08002713 }
Glenn Kasten4944acb2013-08-19 08:39:20 -07002714 if (mType == MIXER) {
2715 // write blocked detection
2716 nsecs_t now = systemTime();
2717 nsecs_t delta = now - mLastWriteTime;
2718 if (!mStandby && delta > maxPeriod) {
2719 mNumDelayedWrites++;
2720 if ((now - lastWarning) > kWarningThrottleNs) {
2721 ATRACE_NAME("underrun");
2722 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2723 ns2ms(delta), mNumDelayedWrites, this);
2724 lastWarning = now;
2725 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002726 }
2727 }
Eric Laurent81784c32012-11-19 14:55:58 -08002728
Eric Laurentbfb1b832013-01-07 09:53:42 -08002729 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07002730 ATRACE_BEGIN("sleep");
Eric Laurentbfb1b832013-01-07 09:53:42 -08002731 usleep(sleepTime);
Glenn Kastene7754022014-10-31 12:11:26 -07002732 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002733 }
Eric Laurent81784c32012-11-19 14:55:58 -08002734 }
2735
2736 // Finally let go of removed track(s), without the lock held
2737 // since we can't guarantee the destructors won't acquire that
2738 // same lock. This will also mutate and push a new fast mixer state.
2739 threadLoop_removeTracks(tracksToRemove);
2740 tracksToRemove.clear();
2741
2742 // FIXME I don't understand the need for this here;
2743 // it was in the original code but maybe the
2744 // assignment in saveOutputTracks() makes this unnecessary?
2745 clearOutputTracks();
2746
2747 // Effect chains will be actually deleted here if they were removed from
2748 // mEffectChains list during mixing or effects processing
2749 effectChains.clear();
2750
2751 // FIXME Note that the above .clear() is no longer necessary since effectChains
2752 // is now local to this block, but will keep it for now (at least until merge done).
2753 }
2754
Eric Laurentbfb1b832013-01-07 09:53:42 -08002755 threadLoop_exit();
2756
Eric Laurentcf817a22014-08-04 20:36:31 -07002757 if (!mStandby) {
2758 threadLoop_standby();
2759 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08002760 }
2761
2762 releaseWakeLock();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002763 mWakeLockUids.clear();
2764 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002765
2766 ALOGV("Thread %p type %d exiting", this, mType);
2767 return false;
2768}
2769
Eric Laurentbfb1b832013-01-07 09:53:42 -08002770// removeTracks_l() must be called with ThreadBase::mLock held
2771void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
2772{
2773 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002774 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002775 for (size_t i=0 ; i<count ; i++) {
2776 const sp<Track>& track = tracksToRemove.itemAt(i);
2777 mActiveTracks.remove(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002778 mWakeLockUids.remove(track->uid());
2779 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002780 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
2781 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2782 if (chain != 0) {
2783 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
2784 track->sessionId());
2785 chain->decActiveTrackCnt();
2786 }
2787 if (track->isTerminated()) {
2788 removeTrack_l(track);
2789 }
2790 }
2791 }
2792
2793}
Eric Laurent81784c32012-11-19 14:55:58 -08002794
Eric Laurentaccc1472013-09-20 09:36:34 -07002795status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
2796{
2797 if (mNormalSink != 0) {
2798 return mNormalSink->getTimestamp(timestamp);
2799 }
Andy Hung9a1c8892014-12-03 11:37:42 -08002800 if ((mType == OFFLOAD || mType == DIRECT)
2801 && mOutput != NULL && mOutput->stream->get_presentation_position) {
Eric Laurentaccc1472013-09-20 09:36:34 -07002802 uint64_t position64;
2803 int ret = mOutput->stream->get_presentation_position(
2804 mOutput->stream, &position64, &timestamp.mTime);
2805 if (ret == 0) {
2806 timestamp.mPosition = (uint32_t)position64;
2807 return NO_ERROR;
2808 }
2809 }
2810 return INVALID_OPERATION;
2811}
Eric Laurent1c333e22014-05-20 10:48:17 -07002812
2813status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
2814 audio_patch_handle_t *handle)
2815{
2816 status_t status = NO_ERROR;
2817 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
2818 // store new device and send to effects
2819 audio_devices_t type = AUDIO_DEVICE_NONE;
2820 for (unsigned int i = 0; i < patch->num_sinks; i++) {
2821 type |= patch->sinks[i].ext.device.type;
2822 }
2823 mOutDevice = type;
2824 for (size_t i = 0; i < mEffectChains.size(); i++) {
2825 mEffectChains[i]->setDevice_l(mOutDevice);
2826 }
2827
2828 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
2829 status = hwDevice->create_audio_patch(hwDevice,
2830 patch->num_sources,
2831 patch->sources,
2832 patch->num_sinks,
2833 patch->sinks,
2834 handle);
2835 } else {
2836 ALOG_ASSERT(false, "createAudioPatch_l() called on a pre 3.0 HAL");
2837 }
2838 return status;
2839}
2840
2841status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
2842{
2843 status_t status = NO_ERROR;
2844 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
2845 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
2846 status = hwDevice->release_audio_patch(hwDevice, handle);
2847 } else {
2848 ALOG_ASSERT(false, "releaseAudioPatch_l() called on a pre 3.0 HAL");
2849 }
2850 return status;
2851}
2852
Eric Laurent83b88082014-06-20 18:31:16 -07002853void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
2854{
2855 Mutex::Autolock _l(mLock);
2856 mTracks.add(track);
2857}
2858
2859void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
2860{
2861 Mutex::Autolock _l(mLock);
2862 destroyTrack_l(track);
2863}
2864
2865void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
2866{
2867 ThreadBase::getAudioPortConfig(config);
2868 config->role = AUDIO_PORT_ROLE_SOURCE;
2869 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
2870 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
2871}
2872
Eric Laurent81784c32012-11-19 14:55:58 -08002873// ----------------------------------------------------------------------------
2874
2875AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
2876 audio_io_handle_t id, audio_devices_t device, type_t type)
2877 : PlaybackThread(audioFlinger, output, id, device, type),
2878 // mAudioMixer below
2879 // mFastMixer below
2880 mFastMixerFutex(0)
2881 // mOutputSink below
2882 // mPipeSink below
2883 // mNormalSink below
2884{
2885 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07002886 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, "
Eric Laurent81784c32012-11-19 14:55:58 -08002887 "mFrameCount=%d, mNormalFrameCount=%d",
2888 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2889 mNormalFrameCount);
2890 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2891
Andy Hungfbfc3952015-01-15 13:33:51 -08002892 if (type == DUPLICATING) {
2893 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
2894 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
2895 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
2896 return;
2897 }
Eric Laurent81784c32012-11-19 14:55:58 -08002898 // create an NBAIO sink for the HAL output stream, and negotiate
2899 mOutputSink = new AudioStreamOutSink(output->stream);
2900 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08002901 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Eric Laurent81784c32012-11-19 14:55:58 -08002902 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2903 ALOG_ASSERT(index == 0);
2904
2905 // initialize fast mixer depending on configuration
2906 bool initFastMixer;
2907 switch (kUseFastMixer) {
2908 case FastMixer_Never:
2909 initFastMixer = false;
2910 break;
2911 case FastMixer_Always:
2912 initFastMixer = true;
2913 break;
2914 case FastMixer_Static:
2915 case FastMixer_Dynamic:
2916 initFastMixer = mFrameCount < mNormalFrameCount;
2917 break;
2918 }
2919 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07002920 audio_format_t fastMixerFormat;
2921 if (mMixerBufferEnabled && mEffectBufferEnabled) {
2922 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
2923 } else {
2924 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
2925 }
2926 if (mFormat != fastMixerFormat) {
2927 // change our Sink format to accept our intermediate precision
2928 mFormat = fastMixerFormat;
2929 free(mSinkBuffer);
2930 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2931 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
2932 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
2933 }
Eric Laurent81784c32012-11-19 14:55:58 -08002934
2935 // create a MonoPipe to connect our submix to FastMixer
2936 NBAIO_Format format = mOutputSink->format();
Glenn Kastenba0b34c2014-09-28 13:06:06 -07002937 NBAIO_Format origformat = format;
Andy Hung1258c1a2014-05-23 21:22:17 -07002938 // adjust format to match that of the Fast Mixer
Glenn Kasten97b7b752014-09-28 13:04:24 -07002939 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07002940 format.mFormat = fastMixerFormat;
2941 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
2942
Eric Laurent81784c32012-11-19 14:55:58 -08002943 // This pipe depth compensates for scheduling latency of the normal mixer thread.
2944 // When it wakes up after a maximum latency, it runs a few cycles quickly before
2945 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
2946 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
2947 const NBAIO_Format offers[1] = {format};
2948 size_t numCounterOffers = 0;
2949 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2950 ALOG_ASSERT(index == 0);
2951 monoPipe->setAvgFrames((mScreenState & 1) ?
2952 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2953 mPipeSink = monoPipe;
2954
Glenn Kasten46909e72013-02-26 09:20:22 -08002955#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08002956 if (mTeeSinkOutputEnabled) {
2957 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07002958 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
2959 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08002960 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07002961 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08002962 ALOG_ASSERT(index == 0);
2963 mTeeSink = teeSink;
2964 PipeReader *teeSource = new PipeReader(*teeSink);
2965 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07002966 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08002967 ALOG_ASSERT(index == 0);
2968 mTeeSource = teeSource;
2969 }
Glenn Kasten46909e72013-02-26 09:20:22 -08002970#endif
Eric Laurent81784c32012-11-19 14:55:58 -08002971
2972 // create fast mixer and configure it initially with just one fast track for our submix
2973 mFastMixer = new FastMixer();
2974 FastMixerStateQueue *sq = mFastMixer->sq();
2975#ifdef STATE_QUEUE_DUMP
2976 sq->setObserverDump(&mStateQueueObserverDump);
2977 sq->setMutatorDump(&mStateQueueMutatorDump);
2978#endif
2979 FastMixerState *state = sq->begin();
2980 FastTrack *fastTrack = &state->mFastTracks[0];
2981 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2982 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2983 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07002984 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
2985 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08002986 fastTrack->mGeneration++;
2987 state->mFastTracksGen++;
2988 state->mTrackMask = 1;
2989 // fast mixer will use the HAL output sink
2990 state->mOutputSink = mOutputSink.get();
2991 state->mOutputSinkGen++;
2992 state->mFrameCount = mFrameCount;
2993 state->mCommand = FastMixerState::COLD_IDLE;
2994 // already done in constructor initialization list
2995 //mFastMixerFutex = 0;
2996 state->mColdFutexAddr = &mFastMixerFutex;
2997 state->mColdGen++;
2998 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08002999#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003000 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08003001#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08003002 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3003 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003004 sq->end();
3005 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3006
3007 // start the fast mixer
3008 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3009 pid_t tid = mFastMixer->getTid();
3010 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
3011 if (err != 0) {
3012 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
3013 kPriorityFastMixer, getpid_cached, tid, err);
3014 }
3015
3016#ifdef AUDIO_WATCHDOG
3017 // create and start the watchdog
3018 mAudioWatchdog = new AudioWatchdog();
3019 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3020 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3021 tid = mAudioWatchdog->getTid();
3022 err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
3023 if (err != 0) {
3024 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
3025 kPriorityFastMixer, getpid_cached, tid, err);
3026 }
3027#endif
3028
Eric Laurent81784c32012-11-19 14:55:58 -08003029 }
3030
3031 switch (kUseFastMixer) {
3032 case FastMixer_Never:
3033 case FastMixer_Dynamic:
3034 mNormalSink = mOutputSink;
3035 break;
3036 case FastMixer_Always:
3037 mNormalSink = mPipeSink;
3038 break;
3039 case FastMixer_Static:
3040 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3041 break;
3042 }
3043}
3044
3045AudioFlinger::MixerThread::~MixerThread()
3046{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003047 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003048 FastMixerStateQueue *sq = mFastMixer->sq();
3049 FastMixerState *state = sq->begin();
3050 if (state->mCommand == FastMixerState::COLD_IDLE) {
3051 int32_t old = android_atomic_inc(&mFastMixerFutex);
3052 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003053 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003054 }
3055 }
3056 state->mCommand = FastMixerState::EXIT;
3057 sq->end();
3058 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3059 mFastMixer->join();
3060 // Though the fast mixer thread has exited, it's state queue is still valid.
3061 // We'll use that extract the final state which contains one remaining fast track
3062 // corresponding to our sub-mix.
3063 state = sq->begin();
3064 ALOG_ASSERT(state->mTrackMask == 1);
3065 FastTrack *fastTrack = &state->mFastTracks[0];
3066 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3067 delete fastTrack->mBufferProvider;
3068 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003069 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003070#ifdef AUDIO_WATCHDOG
3071 if (mAudioWatchdog != 0) {
3072 mAudioWatchdog->requestExit();
3073 mAudioWatchdog->requestExitAndWait();
3074 mAudioWatchdog.clear();
3075 }
3076#endif
3077 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003078 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003079 delete mAudioMixer;
3080}
3081
3082
3083uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3084{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003085 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003086 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3087 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3088 }
3089 return latency;
3090}
3091
3092
3093void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3094{
3095 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3096}
3097
Eric Laurentbfb1b832013-01-07 09:53:42 -08003098ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003099{
3100 // FIXME we should only do one push per cycle; confirm this is true
3101 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003102 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003103 FastMixerStateQueue *sq = mFastMixer->sq();
3104 FastMixerState *state = sq->begin();
3105 if (state->mCommand != FastMixerState::MIX_WRITE &&
3106 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3107 if (state->mCommand == FastMixerState::COLD_IDLE) {
3108 int32_t old = android_atomic_inc(&mFastMixerFutex);
3109 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003110 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003111 }
3112#ifdef AUDIO_WATCHDOG
3113 if (mAudioWatchdog != 0) {
3114 mAudioWatchdog->resume();
3115 }
3116#endif
3117 }
3118 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003119 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
3120 FastMixerDumpState::kSamplingNforLowRamDevice : FastMixerDumpState::kSamplingN);
Eric Laurent81784c32012-11-19 14:55:58 -08003121 sq->end();
3122 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3123 if (kUseFastMixer == FastMixer_Dynamic) {
3124 mNormalSink = mPipeSink;
3125 }
3126 } else {
3127 sq->end(false /*didModify*/);
3128 }
3129 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003130 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003131}
3132
3133void AudioFlinger::MixerThread::threadLoop_standby()
3134{
3135 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003136 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003137 FastMixerStateQueue *sq = mFastMixer->sq();
3138 FastMixerState *state = sq->begin();
3139 if (!(state->mCommand & FastMixerState::IDLE)) {
3140 state->mCommand = FastMixerState::COLD_IDLE;
3141 state->mColdFutexAddr = &mFastMixerFutex;
3142 state->mColdGen++;
3143 mFastMixerFutex = 0;
3144 sq->end();
3145 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3146 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3147 if (kUseFastMixer == FastMixer_Dynamic) {
3148 mNormalSink = mOutputSink;
3149 }
3150#ifdef AUDIO_WATCHDOG
3151 if (mAudioWatchdog != 0) {
3152 mAudioWatchdog->pause();
3153 }
3154#endif
3155 } else {
3156 sq->end(false /*didModify*/);
3157 }
3158 }
3159 PlaybackThread::threadLoop_standby();
3160}
3161
Eric Laurentbfb1b832013-01-07 09:53:42 -08003162bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3163{
3164 return false;
3165}
3166
3167bool AudioFlinger::PlaybackThread::shouldStandby_l()
3168{
3169 return !mStandby;
3170}
3171
3172bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3173{
3174 Mutex::Autolock _l(mLock);
3175 return waitingAsyncCallback_l();
3176}
3177
Eric Laurent81784c32012-11-19 14:55:58 -08003178// shared by MIXER and DIRECT, overridden by DUPLICATING
3179void AudioFlinger::PlaybackThread::threadLoop_standby()
3180{
3181 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
3182 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003183 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003184 // discard any pending drain or write ack by incrementing sequence
3185 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3186 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003187 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003188 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3189 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003190 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003191 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003192}
3193
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003194void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3195{
3196 ALOGV("signal playback thread");
3197 broadcast_l();
3198}
3199
Eric Laurent81784c32012-11-19 14:55:58 -08003200void AudioFlinger::MixerThread::threadLoop_mix()
3201{
3202 // obtain the presentation timestamp of the next output buffer
3203 int64_t pts;
3204 status_t status = INVALID_OPERATION;
3205
3206 if (mNormalSink != 0) {
3207 status = mNormalSink->getNextWriteTimestamp(&pts);
3208 } else {
3209 status = mOutputSink->getNextWriteTimestamp(&pts);
3210 }
3211
3212 if (status != NO_ERROR) {
3213 pts = AudioBufferProvider::kInvalidPTS;
3214 }
3215
3216 // mix buffers...
3217 mAudioMixer->process(pts);
Andy Hung25c2dac2014-02-27 14:56:00 -08003218 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003219 // increase sleep time progressively when application underrun condition clears.
3220 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3221 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3222 // such that we would underrun the audio HAL.
3223 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
3224 sleepTimeShift--;
3225 }
3226 sleepTime = 0;
3227 standbyTime = systemTime() + standbyDelay;
3228 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003229
Eric Laurent81784c32012-11-19 14:55:58 -08003230}
3231
3232void AudioFlinger::MixerThread::threadLoop_sleepTime()
3233{
3234 // If no tracks are ready, sleep once for the duration of an output
3235 // buffer size, then write 0s to the output
3236 if (sleepTime == 0) {
3237 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3238 sleepTime = activeSleepTime >> sleepTimeShift;
3239 if (sleepTime < kMinThreadSleepTimeUs) {
3240 sleepTime = kMinThreadSleepTimeUs;
3241 }
3242 // reduce sleep time in case of consecutive application underruns to avoid
3243 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3244 // duration we would end up writing less data than needed by the audio HAL if
3245 // the condition persists.
3246 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3247 sleepTimeShift++;
3248 }
3249 } else {
3250 sleepTime = idleSleepTime;
3251 }
3252 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003253 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3254 // before effects processing or output.
3255 if (mMixerBufferValid) {
3256 memset(mMixerBuffer, 0, mMixerBufferSize);
3257 } else {
3258 memset(mSinkBuffer, 0, mSinkBufferSize);
3259 }
Eric Laurent81784c32012-11-19 14:55:58 -08003260 sleepTime = 0;
3261 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3262 "anticipated start");
3263 }
3264 // TODO add standby time extension fct of effect tail
3265}
3266
3267// prepareTracks_l() must be called with ThreadBase::mLock held
3268AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3269 Vector< sp<Track> > *tracksToRemove)
3270{
3271
3272 mixer_state mixerStatus = MIXER_IDLE;
3273 // find out which tracks need to be processed
3274 size_t count = mActiveTracks.size();
3275 size_t mixedTracks = 0;
3276 size_t tracksWithEffect = 0;
3277 // counts only _active_ fast tracks
3278 size_t fastTracks = 0;
3279 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
3280
3281 float masterVolume = mMasterVolume;
3282 bool masterMute = mMasterMute;
3283
3284 if (masterMute) {
3285 masterVolume = 0;
3286 }
3287 // Delegate master volume control to effect in output mix effect chain if needed
3288 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3289 if (chain != 0) {
3290 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
3291 chain->setVolume_l(&v, &v);
3292 masterVolume = (float)((v + (1 << 23)) >> 24);
3293 chain.clear();
3294 }
3295
3296 // prepare a new state to push
3297 FastMixerStateQueue *sq = NULL;
3298 FastMixerState *state = NULL;
3299 bool didModify = false;
3300 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003301 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003302 sq = mFastMixer->sq();
3303 state = sq->begin();
3304 }
3305
Andy Hung69aed5f2014-02-25 17:24:40 -08003306 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08003307 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08003308
Eric Laurent81784c32012-11-19 14:55:58 -08003309 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003310 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003311 if (t == 0) {
3312 continue;
3313 }
3314
3315 // this const just means the local variable doesn't change
3316 Track* const track = t.get();
3317
3318 // process fast tracks
3319 if (track->isFastTrack()) {
3320
3321 // It's theoretically possible (though unlikely) for a fast track to be created
3322 // and then removed within the same normal mix cycle. This is not a problem, as
3323 // the track never becomes active so it's fast mixer slot is never touched.
3324 // The converse, of removing an (active) track and then creating a new track
3325 // at the identical fast mixer slot within the same normal mix cycle,
3326 // is impossible because the slot isn't marked available until the end of each cycle.
3327 int j = track->mFastIndex;
3328 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
3329 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
3330 FastTrack *fastTrack = &state->mFastTracks[j];
3331
3332 // Determine whether the track is currently in underrun condition,
3333 // and whether it had a recent underrun.
3334 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
3335 FastTrackUnderruns underruns = ftDump->mUnderruns;
3336 uint32_t recentFull = (underruns.mBitFields.mFull -
3337 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
3338 uint32_t recentPartial = (underruns.mBitFields.mPartial -
3339 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
3340 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
3341 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
3342 uint32_t recentUnderruns = recentPartial + recentEmpty;
3343 track->mObservedUnderruns = underruns;
3344 // don't count underruns that occur while stopping or pausing
3345 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07003346 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
3347 recentUnderruns > 0) {
3348 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
3349 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003350 }
3351
3352 // This is similar to the state machine for normal tracks,
3353 // with a few modifications for fast tracks.
3354 bool isActive = true;
3355 switch (track->mState) {
3356 case TrackBase::STOPPING_1:
3357 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08003358 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003359 track->mState = TrackBase::STOPPING_2;
3360 }
3361 break;
3362 case TrackBase::PAUSING:
3363 // ramp down is not yet implemented
3364 track->setPaused();
3365 break;
3366 case TrackBase::RESUMING:
3367 // ramp up is not yet implemented
3368 track->mState = TrackBase::ACTIVE;
3369 break;
3370 case TrackBase::ACTIVE:
3371 if (recentFull > 0 || recentPartial > 0) {
3372 // track has provided at least some frames recently: reset retry count
3373 track->mRetryCount = kMaxTrackRetries;
3374 }
3375 if (recentUnderruns == 0) {
3376 // no recent underruns: stay active
3377 break;
3378 }
3379 // there has recently been an underrun of some kind
3380 if (track->sharedBuffer() == 0) {
3381 // were any of the recent underruns "empty" (no frames available)?
3382 if (recentEmpty == 0) {
3383 // no, then ignore the partial underruns as they are allowed indefinitely
3384 break;
3385 }
3386 // there has recently been an "empty" underrun: decrement the retry counter
3387 if (--(track->mRetryCount) > 0) {
3388 break;
3389 }
3390 // indicate to client process that the track was disabled because of underrun;
3391 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003392 android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003393 // remove from active list, but state remains ACTIVE [confusing but true]
3394 isActive = false;
3395 break;
3396 }
3397 // fall through
3398 case TrackBase::STOPPING_2:
3399 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003400 case TrackBase::STOPPED:
3401 case TrackBase::FLUSHED: // flush() while active
3402 // Check for presentation complete if track is inactive
3403 // We have consumed all the buffers of this track.
3404 // This would be incomplete if we auto-paused on underrun
3405 {
3406 size_t audioHALFrames =
3407 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3408 size_t framesWritten = mBytesWritten / mFrameSize;
3409 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
3410 // track stays in active list until presentation is complete
3411 break;
3412 }
3413 }
3414 if (track->isStopping_2()) {
3415 track->mState = TrackBase::STOPPED;
3416 }
3417 if (track->isStopped()) {
3418 // Can't reset directly, as fast mixer is still polling this track
3419 // track->reset();
3420 // So instead mark this track as needing to be reset after push with ack
3421 resetMask |= 1 << i;
3422 }
3423 isActive = false;
3424 break;
3425 case TrackBase::IDLE:
3426 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08003427 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08003428 }
3429
3430 if (isActive) {
3431 // was it previously inactive?
3432 if (!(state->mTrackMask & (1 << j))) {
3433 ExtendedAudioBufferProvider *eabp = track;
3434 VolumeProvider *vp = track;
3435 fastTrack->mBufferProvider = eabp;
3436 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08003437 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003438 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08003439 fastTrack->mGeneration++;
3440 state->mTrackMask |= 1 << j;
3441 didModify = true;
3442 // no acknowledgement required for newly active tracks
3443 }
3444 // cache the combined master volume and stream type volume for fast mixer; this
3445 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08003446 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08003447 ++fastTracks;
3448 } else {
3449 // was it previously active?
3450 if (state->mTrackMask & (1 << j)) {
3451 fastTrack->mBufferProvider = NULL;
3452 fastTrack->mGeneration++;
3453 state->mTrackMask &= ~(1 << j);
3454 didModify = true;
3455 // If any fast tracks were removed, we must wait for acknowledgement
3456 // because we're about to decrement the last sp<> on those tracks.
3457 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3458 } else {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003459 LOG_ALWAYS_FATAL("fast track %d should have been active", j);
Eric Laurent81784c32012-11-19 14:55:58 -08003460 }
3461 tracksToRemove->add(track);
3462 // Avoids a misleading display in dumpsys
3463 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
3464 }
3465 continue;
3466 }
3467
3468 { // local variable scope to avoid goto warning
3469
3470 audio_track_cblk_t* cblk = track->cblk();
3471
3472 // The first time a track is added we wait
3473 // for all its buffers to be filled before processing it
3474 int name = track->name();
3475 // make sure that we have enough frames to mix one full buffer.
3476 // enforce this condition only once to enable draining the buffer in case the client
3477 // app does not call stop() and relies on underrun to stop:
3478 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
3479 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003480 size_t desiredFrames;
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003481 uint32_t sr = track->sampleRate();
3482 if (sr == mSampleRate) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003483 desiredFrames = mNormalFrameCount;
3484 } else {
Andy Hungc25b84a2015-01-14 19:04:10 -08003485 desiredFrames = sourceFramesNeeded(sr, mNormalFrameCount, mSampleRate);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003486 // add frames already consumed but not yet released by the resampler
Glenn Kasten2fc14732013-08-05 14:58:14 -07003487 // because mAudioTrackServerProxy->framesReady() will include these frames
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003488 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
Glenn Kasten74935e42013-12-19 08:56:45 -08003489#if 0
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003490 // the minimum track buffer size is normally twice the number of frames necessary
3491 // to fill one buffer and the resampler should not leave more than one buffer worth
3492 // of unreleased frames after each pass, but just in case...
3493 ALOG_ASSERT(desiredFrames <= cblk->frameCount_);
Glenn Kasten74935e42013-12-19 08:56:45 -08003494#endif
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003495 }
Eric Laurent81784c32012-11-19 14:55:58 -08003496 uint32_t minFrames = 1;
3497 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
3498 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003499 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08003500 }
Eric Laurent13e4c962013-12-20 17:36:01 -08003501
3502 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07003503 if (ATRACE_ENABLED()) {
3504 // I wish we had formatted trace names
3505 char traceName[16];
3506 strcpy(traceName, "nRdy");
3507 int name = track->name();
3508 if (AudioMixer::TRACK0 <= name &&
3509 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
3510 name -= AudioMixer::TRACK0;
3511 traceName[4] = (name / 10) + '0';
3512 traceName[5] = (name % 10) + '0';
3513 } else {
3514 traceName[4] = '?';
3515 traceName[5] = '?';
3516 }
3517 traceName[6] = '\0';
3518 ATRACE_INT(traceName, framesReady);
3519 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003520 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08003521 !track->isPaused() && !track->isTerminated())
3522 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003523 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003524
3525 mixedTracks++;
3526
Andy Hung69aed5f2014-02-25 17:24:40 -08003527 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
3528 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08003529 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08003530 if (track->mainBuffer() != mSinkBuffer &&
3531 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08003532 if (mEffectBufferEnabled) {
3533 mEffectBufferValid = true; // Later can set directly.
3534 }
Eric Laurent81784c32012-11-19 14:55:58 -08003535 chain = getEffectChain_l(track->sessionId());
3536 // Delegate volume control to effect in track effect chain if needed
3537 if (chain != 0) {
3538 tracksWithEffect++;
3539 } else {
3540 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
3541 "session %d",
3542 name, track->sessionId());
3543 }
3544 }
3545
3546
3547 int param = AudioMixer::VOLUME;
3548 if (track->mFillingUpStatus == Track::FS_FILLED) {
3549 // no ramp for the first volume setting
3550 track->mFillingUpStatus = Track::FS_ACTIVE;
3551 if (track->mState == TrackBase::RESUMING) {
3552 track->mState = TrackBase::ACTIVE;
3553 param = AudioMixer::RAMP_VOLUME;
3554 }
3555 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003556 // FIXME should not make a decision based on mServer
3557 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003558 // If the track is stopped before the first frame was mixed,
3559 // do not apply ramp
3560 param = AudioMixer::RAMP_VOLUME;
3561 }
3562
3563 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07003564 uint32_t vl, vr; // in U8.24 integer format
3565 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08003566 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07003567 vl = vr = 0;
3568 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08003569 if (track->isPausing()) {
3570 track->setPaused();
3571 }
3572 } else {
3573
3574 // read original volumes with volume control
3575 float typeVolume = mStreamTypes[track->streamType()].volume;
3576 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003577 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07003578 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07003579 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
3580 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08003581 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07003582 if (vlf > GAIN_FLOAT_UNITY) {
3583 ALOGV("Track left volume out of range: %.3g", vlf);
3584 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003585 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07003586 if (vrf > GAIN_FLOAT_UNITY) {
3587 ALOGV("Track right volume out of range: %.3g", vrf);
3588 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003589 }
3590 // now apply the master volume and stream type volume
Andy Hung6be49402014-05-30 10:42:03 -07003591 vlf *= v;
3592 vrf *= v;
Eric Laurent81784c32012-11-19 14:55:58 -08003593 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07003594 // then derive vl and vr as U8.24 versions for the effect chain
3595 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
3596 vl = (uint32_t) (scaleto8_24 * vlf);
3597 vr = (uint32_t) (scaleto8_24 * vrf);
3598 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08003599 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08003600 // send level comes from shared memory and so may be corrupt
3601 if (sendLevel > MAX_GAIN_INT) {
3602 ALOGV("Track send level out of range: %04X", sendLevel);
3603 sendLevel = MAX_GAIN_INT;
3604 }
Andy Hung6be49402014-05-30 10:42:03 -07003605 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
3606 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08003607 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003608
Eric Laurent81784c32012-11-19 14:55:58 -08003609 // Delegate volume control to effect in track effect chain if needed
3610 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3611 // Do not ramp volume if volume is controlled by effect
3612 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08003613 // Update remaining floating point volume levels
3614 vlf = (float)vl / (1 << 24);
3615 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08003616 track->mHasVolumeController = true;
3617 } else {
3618 // force no volume ramp when volume controller was just disabled or removed
3619 // from effect chain to avoid volume spike
3620 if (track->mHasVolumeController) {
3621 param = AudioMixer::VOLUME;
3622 }
3623 track->mHasVolumeController = false;
3624 }
3625
Eric Laurent81784c32012-11-19 14:55:58 -08003626 // XXX: these things DON'T need to be done each time
3627 mAudioMixer->setBufferProvider(name, track);
3628 mAudioMixer->enable(name);
3629
Andy Hung6be49402014-05-30 10:42:03 -07003630 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
3631 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
3632 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08003633 mAudioMixer->setParameter(
3634 name,
3635 AudioMixer::TRACK,
3636 AudioMixer::FORMAT, (void *)track->format());
3637 mAudioMixer->setParameter(
3638 name,
3639 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003640 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07003641 mAudioMixer->setParameter(
3642 name,
3643 AudioMixer::TRACK,
3644 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08003645 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07003646 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003647 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08003648 if (reqSampleRate == 0) {
3649 reqSampleRate = mSampleRate;
3650 } else if (reqSampleRate > maxSampleRate) {
3651 reqSampleRate = maxSampleRate;
3652 }
Eric Laurent81784c32012-11-19 14:55:58 -08003653 mAudioMixer->setParameter(
3654 name,
3655 AudioMixer::RESAMPLE,
3656 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003657 (void *)(uintptr_t)reqSampleRate);
Andy Hung69aed5f2014-02-25 17:24:40 -08003658 /*
3659 * Select the appropriate output buffer for the track.
3660 *
Andy Hung98ef9782014-03-04 14:46:50 -08003661 * Tracks with effects go into their own effects chain buffer
3662 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08003663 *
3664 * Other tracks can use mMixerBuffer for higher precision
3665 * channel accumulation. If this buffer is enabled
3666 * (mMixerBufferEnabled true), then selected tracks will accumulate
3667 * into it.
3668 *
3669 */
3670 if (mMixerBufferEnabled
3671 && (track->mainBuffer() == mSinkBuffer
3672 || track->mainBuffer() == mMixerBuffer)) {
3673 mAudioMixer->setParameter(
3674 name,
3675 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08003676 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08003677 mAudioMixer->setParameter(
3678 name,
3679 AudioMixer::TRACK,
3680 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
3681 // TODO: override track->mainBuffer()?
3682 mMixerBufferValid = true;
3683 } else {
3684 mAudioMixer->setParameter(
3685 name,
3686 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08003687 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08003688 mAudioMixer->setParameter(
3689 name,
3690 AudioMixer::TRACK,
3691 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3692 }
Eric Laurent81784c32012-11-19 14:55:58 -08003693 mAudioMixer->setParameter(
3694 name,
3695 AudioMixer::TRACK,
3696 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3697
3698 // reset retry count
3699 track->mRetryCount = kMaxTrackRetries;
3700
3701 // If one track is ready, set the mixer ready if:
3702 // - the mixer was not ready during previous round OR
3703 // - no other track is not ready
3704 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
3705 mixerStatus != MIXER_TRACKS_ENABLED) {
3706 mixerStatus = MIXER_TRACKS_READY;
3707 }
3708 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003709 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Glenn Kasten82aaf942013-07-17 16:05:07 -07003710 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003711 }
Eric Laurent81784c32012-11-19 14:55:58 -08003712 // clear effect chain input buffer if an active track underruns to avoid sending
3713 // previous audio buffer again to effects
3714 chain = getEffectChain_l(track->sessionId());
3715 if (chain != 0) {
3716 chain->clearInputBuffer();
3717 }
3718
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003719 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003720 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3721 track->isStopped() || track->isPaused()) {
3722 // We have consumed all the buffers of this track.
3723 // Remove it from the list of active tracks.
3724 // TODO: use actual buffer filling status instead of latency when available from
3725 // audio HAL
3726 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3727 size_t framesWritten = mBytesWritten / mFrameSize;
3728 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
3729 if (track->isStopped()) {
3730 track->reset();
3731 }
3732 tracksToRemove->add(track);
3733 }
3734 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08003735 // No buffers for this track. Give it a few chances to
3736 // fill a buffer, then remove it from active list.
3737 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08003738 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003739 tracksToRemove->add(track);
3740 // indicate to client process that the track was disabled because of underrun;
3741 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003742 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003743 // If one track is not ready, mark the mixer also not ready if:
3744 // - the mixer was ready during previous round OR
3745 // - no other track is ready
3746 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
3747 mixerStatus != MIXER_TRACKS_READY) {
3748 mixerStatus = MIXER_TRACKS_ENABLED;
3749 }
3750 }
3751 mAudioMixer->disable(name);
3752 }
3753
3754 } // local variable scope to avoid goto warning
3755track_is_ready: ;
3756
3757 }
3758
3759 // Push the new FastMixer state if necessary
3760 bool pauseAudioWatchdog = false;
3761 if (didModify) {
3762 state->mFastTracksGen++;
3763 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3764 if (kUseFastMixer == FastMixer_Dynamic &&
3765 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3766 state->mCommand = FastMixerState::COLD_IDLE;
3767 state->mColdFutexAddr = &mFastMixerFutex;
3768 state->mColdGen++;
3769 mFastMixerFutex = 0;
3770 if (kUseFastMixer == FastMixer_Dynamic) {
3771 mNormalSink = mOutputSink;
3772 }
3773 // If we go into cold idle, need to wait for acknowledgement
3774 // so that fast mixer stops doing I/O.
3775 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3776 pauseAudioWatchdog = true;
3777 }
Eric Laurent81784c32012-11-19 14:55:58 -08003778 }
3779 if (sq != NULL) {
3780 sq->end(didModify);
3781 sq->push(block);
3782 }
3783#ifdef AUDIO_WATCHDOG
3784 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3785 mAudioWatchdog->pause();
3786 }
3787#endif
3788
3789 // Now perform the deferred reset on fast tracks that have stopped
3790 while (resetMask != 0) {
3791 size_t i = __builtin_ctz(resetMask);
3792 ALOG_ASSERT(i < count);
3793 resetMask &= ~(1 << i);
3794 sp<Track> t = mActiveTracks[i].promote();
3795 if (t == 0) {
3796 continue;
3797 }
3798 Track* track = t.get();
3799 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3800 track->reset();
3801 }
3802
3803 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08003804 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08003805
Eric Laurent97d547d2014-09-02 14:45:53 -07003806 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
3807 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07003808 }
3809
3810 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07003811 // as long as there are effects we should clear the effects buffer, to avoid
3812 // passing a non-clean buffer to the effect chain
3813 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07003814 }
Andy Hung69aed5f2014-02-25 17:24:40 -08003815 // sink or mix buffer must be cleared if all tracks are connected to an
3816 // effect chain as in this case the mixer will not write to the sink or mix buffer
3817 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08003818 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3819 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08003820 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08003821 if (mMixerBufferValid) {
3822 memset(mMixerBuffer, 0, mMixerBufferSize);
3823 // TODO: In testing, mSinkBuffer below need not be cleared because
3824 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
3825 // after mixing.
3826 //
3827 // To enforce this guarantee:
3828 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3829 // (mixedTracks == 0 && fastTracks > 0))
3830 // must imply MIXER_TRACKS_READY.
3831 // Later, we may clear buffers regardless, and skip much of this logic.
3832 }
Andy Hung98ef9782014-03-04 14:46:50 -08003833 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07003834 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003835 }
3836
3837 // if any fast tracks, then status is ready
3838 mMixerStatusIgnoringFastTracks = mixerStatus;
3839 if (fastTracks > 0) {
3840 mixerStatus = MIXER_TRACKS_READY;
3841 }
3842 return mixerStatus;
3843}
3844
3845// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07003846int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
3847 audio_format_t format, int sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08003848{
Andy Hunge8a1ced2014-05-09 15:02:21 -07003849 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08003850}
3851
3852// deleteTrackName_l() must be called with ThreadBase::mLock held
3853void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3854{
3855 ALOGV("remove track (%d) and delete from mixer", name);
3856 mAudioMixer->deleteTrackName(name);
3857}
3858
Eric Laurent10351942014-05-08 18:49:52 -07003859// checkForNewParameter_l() must be called with ThreadBase::mLock held
3860bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
3861 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08003862{
Eric Laurent81784c32012-11-19 14:55:58 -08003863 bool reconfig = false;
3864
Eric Laurent10351942014-05-08 18:49:52 -07003865 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08003866
Eric Laurent10351942014-05-08 18:49:52 -07003867 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3868 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003869 if (mFastMixer != 0) {
Eric Laurent10351942014-05-08 18:49:52 -07003870 FastMixerStateQueue *sq = mFastMixer->sq();
3871 FastMixerState *state = sq->begin();
3872 if (!(state->mCommand & FastMixerState::IDLE)) {
3873 previousCommand = state->mCommand;
3874 state->mCommand = FastMixerState::HOT_IDLE;
3875 sq->end();
3876 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3877 } else {
3878 sq->end(false /*didModify*/);
Eric Laurent81784c32012-11-19 14:55:58 -08003879 }
Eric Laurent10351942014-05-08 18:49:52 -07003880 }
Eric Laurent81784c32012-11-19 14:55:58 -08003881
Eric Laurent10351942014-05-08 18:49:52 -07003882 AudioParameter param = AudioParameter(keyValuePair);
3883 int value;
3884 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3885 reconfig = true;
3886 }
3887 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07003888 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07003889 status = BAD_VALUE;
3890 } else {
3891 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08003892 reconfig = true;
3893 }
Eric Laurent10351942014-05-08 18:49:52 -07003894 }
3895 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07003896 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07003897 status = BAD_VALUE;
3898 } else {
3899 // no need to save value, since it's constant
3900 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003901 }
Eric Laurent10351942014-05-08 18:49:52 -07003902 }
3903 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3904 // do not accept frame count changes if tracks are open as the track buffer
3905 // size depends on frame count and correct behavior would not be guaranteed
3906 // if frame count is changed after track creation
3907 if (!mTracks.isEmpty()) {
3908 status = INVALID_OPERATION;
3909 } else {
3910 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003911 }
Eric Laurent10351942014-05-08 18:49:52 -07003912 }
3913 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08003914#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07003915 // when changing the audio output device, call addBatteryData to notify
3916 // the change
3917 if (mOutDevice != value) {
3918 uint32_t params = 0;
3919 // check whether speaker is on
3920 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
3921 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08003922 }
Eric Laurent10351942014-05-08 18:49:52 -07003923
3924 audio_devices_t deviceWithoutSpeaker
3925 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3926 // check if any other device (except speaker) is on
3927 if (value & deviceWithoutSpeaker ) {
3928 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3929 }
3930
3931 if (params != 0) {
3932 addBatteryData(params);
3933 }
3934 }
Eric Laurent81784c32012-11-19 14:55:58 -08003935#endif
3936
Eric Laurent10351942014-05-08 18:49:52 -07003937 // forward device change to effects that have requested to be
3938 // aware of attached audio device.
3939 if (value != AUDIO_DEVICE_NONE) {
3940 mOutDevice = value;
3941 for (size_t i = 0; i < mEffectChains.size(); i++) {
3942 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08003943 }
3944 }
Eric Laurent10351942014-05-08 18:49:52 -07003945 }
Eric Laurent81784c32012-11-19 14:55:58 -08003946
Eric Laurent10351942014-05-08 18:49:52 -07003947 if (status == NO_ERROR) {
3948 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3949 keyValuePair.string());
3950 if (!mStandby && status == INVALID_OPERATION) {
3951 mOutput->stream->common.standby(&mOutput->stream->common);
3952 mStandby = true;
3953 mBytesWritten = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003954 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Eric Laurent10351942014-05-08 18:49:52 -07003955 keyValuePair.string());
Eric Laurent81784c32012-11-19 14:55:58 -08003956 }
Eric Laurent10351942014-05-08 18:49:52 -07003957 if (status == NO_ERROR && reconfig) {
3958 readOutputParameters_l();
3959 delete mAudioMixer;
3960 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3961 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07003962 int name = getTrackName_l(mTracks[i]->mChannelMask,
3963 mTracks[i]->mFormat, mTracks[i]->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07003964 if (name < 0) {
3965 break;
3966 }
3967 mTracks[i]->mName = name;
3968 }
3969 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3970 }
Eric Laurent81784c32012-11-19 14:55:58 -08003971 }
3972
3973 if (!(previousCommand & FastMixerState::IDLE)) {
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003974 ALOG_ASSERT(mFastMixer != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08003975 FastMixerStateQueue *sq = mFastMixer->sq();
3976 FastMixerState *state = sq->begin();
3977 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3978 state->mCommand = previousCommand;
3979 sq->end();
3980 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3981 }
3982
3983 return reconfig;
3984}
3985
3986
3987void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
3988{
3989 const size_t SIZE = 256;
3990 char buffer[SIZE];
3991 String8 result;
3992
3993 PlaybackThread::dumpInternals(fd, args);
3994
Elliott Hughes87cebad2014-05-22 10:14:43 -07003995 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Eric Laurent81784c32012-11-19 14:55:58 -08003996
3997 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003998 const FastMixerDumpState copy(mFastMixerDumpState);
Eric Laurent81784c32012-11-19 14:55:58 -08003999 copy.dump(fd);
4000
4001#ifdef STATE_QUEUE_DUMP
4002 // Similar for state queue
4003 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4004 observerCopy.dump(fd);
4005 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4006 mutatorCopy.dump(fd);
4007#endif
4008
Glenn Kasten46909e72013-02-26 09:20:22 -08004009#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08004010 // Write the tee output to a .wav file
4011 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08004012#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004013
4014#ifdef AUDIO_WATCHDOG
4015 if (mAudioWatchdog != 0) {
4016 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4017 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4018 wdCopy.dump(fd);
4019 }
4020#endif
4021}
4022
4023uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4024{
4025 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4026}
4027
4028uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4029{
4030 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4031}
4032
4033void AudioFlinger::MixerThread::cacheParameters_l()
4034{
4035 PlaybackThread::cacheParameters_l();
4036
4037 // FIXME: Relaxed timing because of a certain device that can't meet latency
4038 // Should be reduced to 2x after the vendor fixes the driver issue
4039 // increase threshold again due to low power audio mode. The way this warning
4040 // threshold is calculated and its usefulness should be reconsidered anyway.
4041 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4042}
4043
4044// ----------------------------------------------------------------------------
4045
4046AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4047 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
4048 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
4049 // mLeftVolFloat, mRightVolFloat
4050{
4051}
4052
Eric Laurentbfb1b832013-01-07 09:53:42 -08004053AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4054 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
4055 ThreadBase::type_t type)
4056 : PlaybackThread(audioFlinger, output, id, device, type)
4057 // mLeftVolFloat, mRightVolFloat
4058{
4059}
4060
Eric Laurent81784c32012-11-19 14:55:58 -08004061AudioFlinger::DirectOutputThread::~DirectOutputThread()
4062{
4063}
4064
Eric Laurentbfb1b832013-01-07 09:53:42 -08004065void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
4066{
4067 audio_track_cblk_t* cblk = track->cblk();
4068 float left, right;
4069
4070 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4071 left = right = 0;
4072 } else {
4073 float typeVolume = mStreamTypes[track->streamType()].volume;
4074 float v = mMasterVolume * typeVolume;
4075 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004076 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4077 left = float_from_gain(gain_minifloat_unpack_left(vlr));
4078 if (left > GAIN_FLOAT_UNITY) {
4079 left = GAIN_FLOAT_UNITY;
4080 }
4081 left *= v;
4082 right = float_from_gain(gain_minifloat_unpack_right(vlr));
4083 if (right > GAIN_FLOAT_UNITY) {
4084 right = GAIN_FLOAT_UNITY;
4085 }
4086 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004087 }
4088
4089 if (lastTrack) {
4090 if (left != mLeftVolFloat || right != mRightVolFloat) {
4091 mLeftVolFloat = left;
4092 mRightVolFloat = right;
4093
4094 // Convert volumes from float to 8.24
4095 uint32_t vl = (uint32_t)(left * (1 << 24));
4096 uint32_t vr = (uint32_t)(right * (1 << 24));
4097
4098 // Delegate volume control to effect in track effect chain if needed
4099 // only one effect chain can be present on DirectOutputThread, so if
4100 // there is one, the track is connected to it
4101 if (!mEffectChains.isEmpty()) {
4102 mEffectChains[0]->setVolume_l(&vl, &vr);
4103 left = (float)vl / (1 << 24);
4104 right = (float)vr / (1 << 24);
4105 }
4106 if (mOutput->stream->set_volume) {
4107 mOutput->stream->set_volume(mOutput->stream, left, right);
4108 }
4109 }
4110 }
4111}
4112
4113
Eric Laurent81784c32012-11-19 14:55:58 -08004114AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4115 Vector< sp<Track> > *tracksToRemove
4116)
4117{
Eric Laurentd595b7c2013-04-03 17:27:56 -07004118 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08004119 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004120 bool doHwPause = false;
4121 bool doHwResume = false;
4122 bool flushPending = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004123
4124 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07004125 for (size_t i = 0; i < count; i++) {
4126 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08004127 // The track died recently
4128 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004129 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08004130 }
4131
4132 Track* const track = t.get();
4133 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07004134 // Only consider last track started for volume and mixer state control.
4135 // In theory an older track could underrun and restart after the new one starts
4136 // but as we only care about the transition phase between two tracks on a
4137 // direct output, it is not a problem to ignore the underrun case.
4138 sp<Track> l = mLatestActiveTrack.promote();
4139 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08004140
Eric Laurentd1f69b02014-12-15 14:33:13 -08004141 if (mHwSupportsPause && track->isPausing()) {
4142 track->setPaused();
4143 if (last && !mHwPaused) {
4144 doHwPause = true;
4145 mHwPaused = true;
4146 }
4147 tracksToRemove->add(track);
4148 } else if (track->isFlushPending()) {
4149 track->flushAck();
4150 if (last) {
4151 flushPending = true;
4152 }
4153 } else if (mHwSupportsPause && track->isResumePending()){
4154 track->resumeAck();
4155 if (last) {
4156 if (mHwPaused) {
4157 doHwResume = true;
4158 mHwPaused = false;
4159 }
4160 }
4161 }
4162
Eric Laurent81784c32012-11-19 14:55:58 -08004163 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08004164 // for all its buffers to be filled before processing it.
4165 // Allow draining the buffer in case the client
4166 // app does not call stop() and relies on underrun to stop:
4167 // hence the test on (track->mRetryCount > 1).
4168 // If retryCount<=1 then track is about to underrun and be removed.
Eric Laurent81784c32012-11-19 14:55:58 -08004169 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08004170 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
4171 && (track->mRetryCount > 1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004172 minFrames = mNormalFrameCount;
4173 } else {
4174 minFrames = 1;
4175 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004176
Eric Laurentab5cdba2014-06-09 17:22:27 -07004177 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4178 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08004179 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004180 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08004181
4182 if (track->mFillingUpStatus == Track::FS_FILLED) {
4183 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004184 // make sure processVolume_l() will apply new volume even if 0
4185 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004186 if (!mHwSupportsPause) {
4187 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08004188 }
4189 }
4190
4191 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004192 processVolume_l(track, last);
4193 if (last) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004194 // reset retry count
4195 track->mRetryCount = kMaxTrackRetriesDirect;
4196 mActiveTrack = t;
4197 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004198 if (usesHwAvSync() && mHwPaused) {
4199 doHwResume = true;
4200 mHwPaused = false;
4201 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004202 }
Eric Laurent81784c32012-11-19 14:55:58 -08004203 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004204 // clear effect chain input buffer if the last active track started underruns
4205 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07004206 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004207 mEffectChains[0]->clearInputBuffer();
4208 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004209 if (track->isStopping_1()) {
4210 track->mState = TrackBase::STOPPING_2;
4211 }
4212 if ((track->sharedBuffer() != 0) || track->isStopped() ||
4213 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004214 // We have consumed all the buffers of this track.
4215 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07004216 size_t audioHALFrames;
4217 if (audio_is_linear_pcm(mFormat)) {
4218 audioHALFrames = (latency_l() * mSampleRate) / 1000;
4219 } else {
4220 audioHALFrames = 0;
4221 }
4222
Eric Laurent81784c32012-11-19 14:55:58 -08004223 size_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07004224 if (mStandby || !last ||
4225 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004226 if (track->isStopping_2()) {
4227 track->mState = TrackBase::STOPPED;
4228 }
Eric Laurent81784c32012-11-19 14:55:58 -08004229 if (track->isStopped()) {
4230 track->reset();
4231 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004232 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08004233 }
4234 } else {
4235 // No buffers for this track. Give it a few chances to
4236 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07004237 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08004238 if (--(track->mRetryCount) <= 0) {
4239 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07004240 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004241 // indicate to client process that the track was disabled because of underrun;
4242 // it will then automatically call start() when data is available
4243 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004244 } else if (last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004245 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004246 if (usesHwAvSync() && !mHwPaused && !mStandby) {
4247 doHwPause = true;
4248 mHwPaused = true;
4249 }
Eric Laurent81784c32012-11-19 14:55:58 -08004250 }
4251 }
4252 }
4253 }
4254
Eric Laurentd1f69b02014-12-15 14:33:13 -08004255 // if an active track did not command a flush, check for pending flush on stopped tracks
4256 if (!flushPending) {
4257 for (size_t i = 0; i < mTracks.size(); i++) {
4258 if (mTracks[i]->isFlushPending()) {
4259 mTracks[i]->flushAck();
4260 flushPending = true;
4261 }
4262 }
4263 }
4264
4265 // make sure the pause/flush/resume sequence is executed in the right order.
4266 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4267 // before flush and then resume HW. This can happen in case of pause/flush/resume
4268 // if resume is received before pause is executed.
4269 if (mHwSupportsPause && !mStandby &&
4270 (doHwPause || (flushPending && !mHwPaused && (count != 0)))) {
4271 mOutput->stream->pause(mOutput->stream);
4272 }
4273 if (flushPending) {
4274 flushHw_l();
4275 }
4276 if (mHwSupportsPause && !mStandby && doHwResume) {
4277 mOutput->stream->resume(mOutput->stream);
4278 }
Eric Laurent81784c32012-11-19 14:55:58 -08004279 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004280 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004281
4282 return mixerStatus;
4283}
4284
4285void AudioFlinger::DirectOutputThread::threadLoop_mix()
4286{
Eric Laurent81784c32012-11-19 14:55:58 -08004287 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08004288 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004289 // output audio to hardware
4290 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07004291 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004292 buffer.frameCount = frameCount;
4293 mActiveTrack->getNextBuffer(&buffer);
Glenn Kastenfa319e62013-07-29 17:17:38 -07004294 if (buffer.raw == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08004295 memset(curBuf, 0, frameCount * mFrameSize);
4296 break;
4297 }
4298 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
4299 frameCount -= buffer.frameCount;
4300 curBuf += buffer.frameCount * mFrameSize;
4301 mActiveTrack->releaseBuffer(&buffer);
4302 }
Andy Hung2098f272014-02-27 14:00:06 -08004303 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004304 sleepTime = 0;
4305 standbyTime = systemTime() + standbyDelay;
4306 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004307}
4308
4309void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
4310{
Eric Laurentd1f69b02014-12-15 14:33:13 -08004311 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004312 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004313 sleepTime = idleSleepTime;
4314 return;
4315 }
Eric Laurent81784c32012-11-19 14:55:58 -08004316 if (sleepTime == 0) {
4317 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4318 sleepTime = activeSleepTime;
4319 } else {
4320 sleepTime = idleSleepTime;
4321 }
4322 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08004323 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004324 sleepTime = 0;
4325 }
4326}
4327
Eric Laurentd1f69b02014-12-15 14:33:13 -08004328void AudioFlinger::DirectOutputThread::threadLoop_exit()
4329{
4330 {
4331 Mutex::Autolock _l(mLock);
4332 bool flushPending = false;
4333 for (size_t i = 0; i < mTracks.size(); i++) {
4334 if (mTracks[i]->isFlushPending()) {
4335 mTracks[i]->flushAck();
4336 flushPending = true;
4337 }
4338 }
4339 if (flushPending) {
4340 flushHw_l();
4341 }
4342 }
4343 PlaybackThread::threadLoop_exit();
4344}
4345
4346// must be called with thread mutex locked
4347bool AudioFlinger::DirectOutputThread::shouldStandby_l()
4348{
4349 bool trackPaused = false;
4350
4351 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4352 // after a timeout and we will enter standby then.
4353 if (mTracks.size() > 0) {
4354 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
4355 }
4356
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004357 return !mStandby && !(trackPaused || (usesHwAvSync() && mHwPaused));
Eric Laurentd1f69b02014-12-15 14:33:13 -08004358}
4359
Eric Laurent81784c32012-11-19 14:55:58 -08004360// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004361int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Andy Hunge8a1ced2014-05-09 15:02:21 -07004362 audio_format_t format __unused, int sessionId __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004363{
4364 return 0;
4365}
4366
4367// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004368void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004369{
4370}
4371
Eric Laurent10351942014-05-08 18:49:52 -07004372// checkForNewParameter_l() must be called with ThreadBase::mLock held
4373bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
4374 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004375{
4376 bool reconfig = false;
4377
Eric Laurent10351942014-05-08 18:49:52 -07004378 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004379
Eric Laurent10351942014-05-08 18:49:52 -07004380 AudioParameter param = AudioParameter(keyValuePair);
4381 int value;
4382 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4383 // forward device change to effects that have requested to be
4384 // aware of attached audio device.
4385 if (value != AUDIO_DEVICE_NONE) {
4386 mOutDevice = value;
4387 for (size_t i = 0; i < mEffectChains.size(); i++) {
4388 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07004389 }
4390 }
Eric Laurent81784c32012-11-19 14:55:58 -08004391 }
Eric Laurent10351942014-05-08 18:49:52 -07004392 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4393 // do not accept frame count changes if tracks are open as the track buffer
4394 // size depends on frame count and correct behavior would not be garantied
4395 // if frame count is changed after track creation
4396 if (!mTracks.isEmpty()) {
4397 status = INVALID_OPERATION;
4398 } else {
4399 reconfig = true;
4400 }
4401 }
4402 if (status == NO_ERROR) {
4403 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4404 keyValuePair.string());
4405 if (!mStandby && status == INVALID_OPERATION) {
4406 mOutput->stream->common.standby(&mOutput->stream->common);
4407 mStandby = true;
4408 mBytesWritten = 0;
4409 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4410 keyValuePair.string());
4411 }
4412 if (status == NO_ERROR && reconfig) {
4413 readOutputParameters_l();
4414 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
4415 }
4416 }
4417
Eric Laurent81784c32012-11-19 14:55:58 -08004418 return reconfig;
4419}
4420
4421uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
4422{
4423 uint32_t time;
4424 if (audio_is_linear_pcm(mFormat)) {
4425 time = PlaybackThread::activeSleepTimeUs();
4426 } else {
4427 time = 10000;
4428 }
4429 return time;
4430}
4431
4432uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
4433{
4434 uint32_t time;
4435 if (audio_is_linear_pcm(mFormat)) {
4436 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
4437 } else {
4438 time = 10000;
4439 }
4440 return time;
4441}
4442
4443uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
4444{
4445 uint32_t time;
4446 if (audio_is_linear_pcm(mFormat)) {
4447 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
4448 } else {
4449 time = 10000;
4450 }
4451 return time;
4452}
4453
4454void AudioFlinger::DirectOutputThread::cacheParameters_l()
4455{
4456 PlaybackThread::cacheParameters_l();
4457
4458 // use shorter standby delay as on normal output to release
4459 // hardware resources as soon as possible
Eric Laurent972a1732013-09-04 09:42:59 -07004460 if (audio_is_linear_pcm(mFormat)) {
4461 standbyDelay = microseconds(activeSleepTime*2);
4462 } else {
4463 standbyDelay = kOffloadStandbyDelayNs;
4464 }
Eric Laurent81784c32012-11-19 14:55:58 -08004465}
4466
Eric Laurente659ef42014-09-29 13:06:46 -07004467void AudioFlinger::DirectOutputThread::flushHw_l()
4468{
Eric Laurentd1f69b02014-12-15 14:33:13 -08004469 if (mOutput->stream->flush != NULL) {
Eric Laurente659ef42014-09-29 13:06:46 -07004470 mOutput->stream->flush(mOutput->stream);
Eric Laurentd1f69b02014-12-15 14:33:13 -08004471 }
4472 mHwPaused = false;
Eric Laurente659ef42014-09-29 13:06:46 -07004473}
4474
Eric Laurent81784c32012-11-19 14:55:58 -08004475// ----------------------------------------------------------------------------
4476
Eric Laurentbfb1b832013-01-07 09:53:42 -08004477AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07004478 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004479 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07004480 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07004481 mWriteAckSequence(0),
4482 mDrainSequence(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004483{
4484}
4485
4486AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
4487{
4488}
4489
4490void AudioFlinger::AsyncCallbackThread::onFirstRef()
4491{
4492 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
4493}
4494
4495bool AudioFlinger::AsyncCallbackThread::threadLoop()
4496{
4497 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004498 uint32_t writeAckSequence;
4499 uint32_t drainSequence;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004500
4501 {
4502 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08004503 while (!((mWriteAckSequence & 1) ||
4504 (mDrainSequence & 1) ||
4505 exitPending())) {
4506 mWaitWorkCV.wait(mLock);
4507 }
4508
Eric Laurentbfb1b832013-01-07 09:53:42 -08004509 if (exitPending()) {
4510 break;
4511 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004512 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
4513 mWriteAckSequence, mDrainSequence);
4514 writeAckSequence = mWriteAckSequence;
4515 mWriteAckSequence &= ~1;
4516 drainSequence = mDrainSequence;
4517 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004518 }
4519 {
Eric Laurent4de95592013-09-26 15:28:21 -07004520 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
4521 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004522 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004523 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004524 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004525 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004526 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004527 }
4528 }
4529 }
4530 }
4531 return false;
4532}
4533
4534void AudioFlinger::AsyncCallbackThread::exit()
4535{
4536 ALOGV("AsyncCallbackThread::exit");
4537 Mutex::Autolock _l(mLock);
4538 requestExit();
4539 mWaitWorkCV.broadcast();
4540}
4541
Eric Laurent3b4529e2013-09-05 18:09:19 -07004542void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004543{
4544 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004545 // bit 0 is cleared
4546 mWriteAckSequence = sequence << 1;
4547}
4548
4549void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
4550{
4551 Mutex::Autolock _l(mLock);
4552 // ignore unexpected callbacks
4553 if (mWriteAckSequence & 2) {
4554 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004555 mWaitWorkCV.signal();
4556 }
4557}
4558
Eric Laurent3b4529e2013-09-05 18:09:19 -07004559void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004560{
4561 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004562 // bit 0 is cleared
4563 mDrainSequence = sequence << 1;
4564}
4565
4566void AudioFlinger::AsyncCallbackThread::resetDraining()
4567{
4568 Mutex::Autolock _l(mLock);
4569 // ignore unexpected callbacks
4570 if (mDrainSequence & 2) {
4571 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004572 mWaitWorkCV.signal();
4573 }
4574}
4575
4576
4577// ----------------------------------------------------------------------------
4578AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
4579 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
4580 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD),
Eric Laurentd7e59222013-11-15 12:02:28 -08004581 mPausedBytesRemaining(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004582{
Eric Laurentfd477972013-10-25 18:10:40 -07004583 //FIXME: mStandby should be set to true by ThreadBase constructor
4584 mStandby = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004585}
4586
Eric Laurentbfb1b832013-01-07 09:53:42 -08004587void AudioFlinger::OffloadThread::threadLoop_exit()
4588{
4589 if (mFlushPending || mHwPaused) {
4590 // If a flush is pending or track was paused, just discard buffered data
4591 flushHw_l();
4592 } else {
4593 mMixerStatus = MIXER_DRAIN_ALL;
4594 threadLoop_drain();
4595 }
Uday Gupta56604aa2014-05-13 11:19:17 -07004596 if (mUseAsyncWrite) {
4597 ALOG_ASSERT(mCallbackThread != 0);
4598 mCallbackThread->exit();
4599 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004600 PlaybackThread::threadLoop_exit();
4601}
4602
4603AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
4604 Vector< sp<Track> > *tracksToRemove
4605)
4606{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004607 size_t count = mActiveTracks.size();
4608
4609 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07004610 bool doHwPause = false;
4611 bool doHwResume = false;
4612
Eric Laurentede6c3b2013-09-19 14:37:46 -07004613 ALOGV("OffloadThread::prepareTracks_l active tracks %d", count);
4614
Eric Laurentbfb1b832013-01-07 09:53:42 -08004615 // find out which tracks need to be processed
4616 for (size_t i = 0; i < count; i++) {
4617 sp<Track> t = mActiveTracks[i].promote();
4618 // The track died recently
4619 if (t == 0) {
4620 continue;
4621 }
4622 Track* const track = t.get();
4623 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07004624 // Only consider last track started for volume and mixer state control.
4625 // In theory an older track could underrun and restart after the new one starts
4626 // but as we only care about the transition phase between two tracks on a
4627 // direct output, it is not a problem to ignore the underrun case.
4628 sp<Track> l = mLatestActiveTrack.promote();
4629 bool last = l.get() == track;
4630
Haynes Mathew George7844f672014-01-15 12:32:55 -08004631 if (track->isInvalid()) {
4632 ALOGW("An invalidated track shouldn't be in active list");
4633 tracksToRemove->add(track);
4634 continue;
4635 }
4636
4637 if (track->mState == TrackBase::IDLE) {
4638 ALOGW("An idle track shouldn't be in active list");
4639 continue;
4640 }
4641
Eric Laurentbfb1b832013-01-07 09:53:42 -08004642 if (track->isPausing()) {
4643 track->setPaused();
4644 if (last) {
4645 if (!mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07004646 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004647 mHwPaused = true;
4648 }
4649 // If we were part way through writing the mixbuffer to
4650 // the HAL we must save this until we resume
4651 // BUG - this will be wrong if a different track is made active,
4652 // in that case we want to discard the pending data in the
4653 // mixbuffer and tell the client to present it again when the
4654 // track is resumed
4655 mPausedWriteLength = mCurrentWriteLength;
4656 mPausedBytesRemaining = mBytesRemaining;
4657 mBytesRemaining = 0; // stop writing
4658 }
4659 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08004660 } else if (track->isFlushPending()) {
4661 track->flushAck();
4662 if (last) {
4663 mFlushPending = true;
4664 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08004665 } else if (track->isResumePending()){
4666 track->resumeAck();
4667 if (last) {
4668 if (mPausedBytesRemaining) {
4669 // Need to continue write that was interrupted
4670 mCurrentWriteLength = mPausedWriteLength;
4671 mBytesRemaining = mPausedBytesRemaining;
4672 mPausedBytesRemaining = 0;
4673 }
4674 if (mHwPaused) {
4675 doHwResume = true;
4676 mHwPaused = false;
4677 // threadLoop_mix() will handle the case that we need to
4678 // resume an interrupted write
4679 }
4680 // enable write to audio HAL
4681 sleepTime = 0;
4682
4683 // Do not handle new data in this iteration even if track->framesReady()
4684 mixerStatus = MIXER_TRACKS_ENABLED;
4685 }
4686 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07004687 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004688 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004689 if (track->mFillingUpStatus == Track::FS_FILLED) {
4690 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004691 // make sure processVolume_l() will apply new volume even if 0
4692 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004693 }
4694
4695 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08004696 sp<Track> previousTrack = mPreviousTrack.promote();
4697 if (previousTrack != 0) {
4698 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08004699 // Flush any data still being written from last track
4700 mBytesRemaining = 0;
4701 if (mPausedBytesRemaining) {
4702 // Last track was paused so we also need to flush saved
4703 // mixbuffer state and invalidate track so that it will
4704 // re-submit that unwritten data when it is next resumed
4705 mPausedBytesRemaining = 0;
4706 // Invalidate is a bit drastic - would be more efficient
4707 // to have a flag to tell client that some of the
4708 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08004709 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004710 }
4711 // flush data already sent to the DSP if changing audio session as audio
4712 // comes from a different source. Also invalidate previous track to force a
4713 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08004714 if (previousTrack->sessionId() != track->sessionId()) {
4715 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004716 }
4717 }
4718 }
4719 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004720 // reset retry count
4721 track->mRetryCount = kMaxTrackRetriesOffload;
4722 mActiveTrack = t;
4723 mixerStatus = MIXER_TRACKS_READY;
4724 }
4725 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004726 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004727 if (track->isStopping_1()) {
4728 // Hardware buffer can hold a large amount of audio so we must
4729 // wait for all current track's data to drain before we say
4730 // that the track is stopped.
4731 if (mBytesRemaining == 0) {
4732 // Only start draining when all data in mixbuffer
4733 // has been written
4734 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
4735 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004736 // do not drain if no data was ever sent to HAL (mStandby == true)
4737 if (last && !mStandby) {
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004738 // do not modify drain sequence if we are already draining. This happens
4739 // when resuming from pause after drain.
4740 if ((mDrainSequence & 1) == 0) {
4741 sleepTime = 0;
4742 standbyTime = systemTime() + standbyDelay;
4743 mixerStatus = MIXER_DRAIN_TRACK;
4744 mDrainSequence += 2;
4745 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004746 if (mHwPaused) {
4747 // It is possible to move from PAUSED to STOPPING_1 without
4748 // a resume so we must ensure hardware is running
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004749 doHwResume = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004750 mHwPaused = false;
4751 }
4752 }
4753 }
4754 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004755 // Drain has completed or we are in standby, signal presentation complete
4756 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004757 track->mState = TrackBase::STOPPED;
4758 size_t audioHALFrames =
4759 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
4760 size_t framesWritten =
Eric Laurent665470b2014-07-03 16:37:08 -07004761 mBytesWritten / audio_stream_out_frame_size(mOutput->stream);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004762 track->presentationComplete(framesWritten, audioHALFrames);
4763 track->reset();
4764 tracksToRemove->add(track);
4765 }
4766 } else {
4767 // No buffers for this track. Give it a few chances to
4768 // fill a buffer, then remove it from active list.
4769 if (--(track->mRetryCount) <= 0) {
4770 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
4771 track->name());
4772 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004773 // indicate to client process that the track was disabled because of underrun;
4774 // it will then automatically call start() when data is available
4775 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004776 } else if (last){
4777 mixerStatus = MIXER_TRACKS_ENABLED;
4778 }
4779 }
4780 }
4781 // compute volume for this track
4782 processVolume_l(track, last);
4783 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004784
Eric Laurentea0fade2013-10-04 16:23:48 -07004785 // make sure the pause/flush/resume sequence is executed in the right order.
4786 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4787 // before flush and then resume HW. This can happen in case of pause/flush/resume
4788 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07004789 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurent972a1732013-09-04 09:42:59 -07004790 mOutput->stream->pause(mOutput->stream);
4791 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004792 if (mFlushPending) {
4793 flushHw_l();
4794 mFlushPending = false;
4795 }
Eric Laurentfd477972013-10-25 18:10:40 -07004796 if (!mStandby && doHwResume) {
Eric Laurent972a1732013-09-04 09:42:59 -07004797 mOutput->stream->resume(mOutput->stream);
4798 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004799
Eric Laurentbfb1b832013-01-07 09:53:42 -08004800 // remove all the tracks that need to be...
4801 removeTracks_l(*tracksToRemove);
4802
4803 return mixerStatus;
4804}
4805
Eric Laurentbfb1b832013-01-07 09:53:42 -08004806// must be called with thread mutex locked
4807bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
4808{
Eric Laurent3b4529e2013-09-05 18:09:19 -07004809 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
4810 mWriteAckSequence, mDrainSequence);
4811 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004812 return true;
4813 }
4814 return false;
4815}
4816
Eric Laurentbfb1b832013-01-07 09:53:42 -08004817bool AudioFlinger::OffloadThread::waitingAsyncCallback()
4818{
4819 Mutex::Autolock _l(mLock);
4820 return waitingAsyncCallback_l();
4821}
4822
4823void AudioFlinger::OffloadThread::flushHw_l()
4824{
Eric Laurente659ef42014-09-29 13:06:46 -07004825 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004826 // Flush anything still waiting in the mixbuffer
4827 mCurrentWriteLength = 0;
4828 mBytesRemaining = 0;
4829 mPausedWriteLength = 0;
4830 mPausedBytesRemaining = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08004831
Eric Laurentbfb1b832013-01-07 09:53:42 -08004832 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004833 // discard any pending drain or write ack by incrementing sequence
4834 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4835 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004836 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004837 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4838 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004839 }
4840}
4841
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08004842void AudioFlinger::OffloadThread::onAddNewTrack_l()
4843{
4844 sp<Track> previousTrack = mPreviousTrack.promote();
4845 sp<Track> latestTrack = mLatestActiveTrack.promote();
4846
4847 if (previousTrack != 0 && latestTrack != 0 &&
4848 (previousTrack->sessionId() != latestTrack->sessionId())) {
4849 mFlushPending = true;
4850 }
4851 PlaybackThread::onAddNewTrack_l();
4852}
4853
Eric Laurentbfb1b832013-01-07 09:53:42 -08004854// ----------------------------------------------------------------------------
4855
Eric Laurent81784c32012-11-19 14:55:58 -08004856AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
4857 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
4858 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
4859 DUPLICATING),
4860 mWaitTimeMs(UINT_MAX)
4861{
4862 addOutputTrack(mainThread);
4863}
4864
4865AudioFlinger::DuplicatingThread::~DuplicatingThread()
4866{
4867 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4868 mOutputTracks[i]->destroy();
4869 }
4870}
4871
4872void AudioFlinger::DuplicatingThread::threadLoop_mix()
4873{
4874 // mix buffers...
4875 if (outputsReady(outputTracks)) {
4876 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
4877 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08004878 if (mMixerBufferValid) {
4879 memset(mMixerBuffer, 0, mMixerBufferSize);
4880 } else {
4881 memset(mSinkBuffer, 0, mSinkBufferSize);
4882 }
Eric Laurent81784c32012-11-19 14:55:58 -08004883 }
4884 sleepTime = 0;
4885 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08004886 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004887 standbyTime = systemTime() + standbyDelay;
4888}
4889
4890void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
4891{
4892 if (sleepTime == 0) {
4893 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4894 sleepTime = activeSleepTime;
4895 } else {
4896 sleepTime = idleSleepTime;
4897 }
4898 } else if (mBytesWritten != 0) {
4899 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4900 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08004901 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004902 } else {
4903 // flush remaining overflow buffers in output tracks
4904 writeFrames = 0;
4905 }
4906 sleepTime = 0;
4907 }
4908}
4909
Eric Laurentbfb1b832013-01-07 09:53:42 -08004910ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004911{
4912 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08004913 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08004914 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07004915 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08004916 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004917}
4918
4919void AudioFlinger::DuplicatingThread::threadLoop_standby()
4920{
4921 // DuplicatingThread implements standby by stopping all tracks
4922 for (size_t i = 0; i < outputTracks.size(); i++) {
4923 outputTracks[i]->stop();
4924 }
4925}
4926
4927void AudioFlinger::DuplicatingThread::saveOutputTracks()
4928{
4929 outputTracks = mOutputTracks;
4930}
4931
4932void AudioFlinger::DuplicatingThread::clearOutputTracks()
4933{
4934 outputTracks.clear();
4935}
4936
4937void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
4938{
4939 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08004940 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
4941 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
4942 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
4943 const size_t frameCount =
4944 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
4945 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
4946 // from different OutputTracks and their associated MixerThreads (e.g. one may
4947 // nearly empty and the other may be dropping data).
4948
4949 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08004950 this,
4951 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08004952 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08004953 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004954 frameCount,
4955 IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08004956 if (outputTrack->cblk() != NULL) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004957 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
Eric Laurent81784c32012-11-19 14:55:58 -08004958 mOutputTracks.add(outputTrack);
Andy Hungc25b84a2015-01-14 19:04:10 -08004959 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
Eric Laurent81784c32012-11-19 14:55:58 -08004960 updateWaitTime_l();
4961 }
4962}
4963
4964void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
4965{
4966 Mutex::Autolock _l(mLock);
4967 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4968 if (mOutputTracks[i]->thread() == thread) {
4969 mOutputTracks[i]->destroy();
4970 mOutputTracks.removeAt(i);
4971 updateWaitTime_l();
4972 return;
4973 }
4974 }
4975 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
4976}
4977
4978// caller must hold mLock
4979void AudioFlinger::DuplicatingThread::updateWaitTime_l()
4980{
4981 mWaitTimeMs = UINT_MAX;
4982 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4983 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
4984 if (strong != 0) {
4985 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4986 if (waitTimeMs < mWaitTimeMs) {
4987 mWaitTimeMs = waitTimeMs;
4988 }
4989 }
4990 }
4991}
4992
4993
4994bool AudioFlinger::DuplicatingThread::outputsReady(
4995 const SortedVector< sp<OutputTrack> > &outputTracks)
4996{
4997 for (size_t i = 0; i < outputTracks.size(); i++) {
4998 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
4999 if (thread == 0) {
5000 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
5001 outputTracks[i].get());
5002 return false;
5003 }
5004 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5005 // see note at standby() declaration
5006 if (playbackThread->standby() && !playbackThread->isSuspended()) {
5007 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
5008 thread.get());
5009 return false;
5010 }
5011 }
5012 return true;
5013}
5014
5015uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
5016{
5017 return (mWaitTimeMs * 1000) / 2;
5018}
5019
5020void AudioFlinger::DuplicatingThread::cacheParameters_l()
5021{
5022 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
5023 updateWaitTime_l();
5024
5025 MixerThread::cacheParameters_l();
5026}
5027
5028// ----------------------------------------------------------------------------
5029// Record
5030// ----------------------------------------------------------------------------
5031
5032AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5033 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08005034 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08005035 audio_devices_t outDevice,
Glenn Kasten46909e72013-02-26 09:20:22 -08005036 audio_devices_t inDevice
5037#ifdef TEE_SINK
5038 , const sp<NBAIO_Sink>& teeSink
5039#endif
5040 ) :
Eric Laurentd3922f72013-02-01 17:57:04 -08005041 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD),
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005042 mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005043 // mRsmpInFrames and mRsmpInFramesP2 are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005044 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08005045#ifdef TEE_SINK
5046 , mTeeSink(teeSink)
5047#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07005048 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
5049 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005050 // mFastCapture below
5051 , mFastCaptureFutex(0)
5052 // mInputSource
5053 // mPipeSink
5054 // mPipeSource
5055 , mPipeFramesP2(0)
5056 // mPipeMemory
5057 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005058 , mFastTrackAvail(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005059{
5060 snprintf(mName, kNameLength, "AudioIn_%X", id);
Glenn Kasten481fb672013-09-30 14:39:28 -07005061 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mName);
Eric Laurent81784c32012-11-19 14:55:58 -08005062
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005063 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005064
5065 // create an NBAIO source for the HAL input stream, and negotiate
5066 mInputSource = new AudioStreamInSource(input->stream);
5067 size_t numCounterOffers = 0;
5068 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
5069 ssize_t index = mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
5070 ALOG_ASSERT(index == 0);
5071
5072 // initialize fast capture depending on configuration
5073 bool initFastCapture;
5074 switch (kUseFastCapture) {
5075 case FastCapture_Never:
5076 initFastCapture = false;
5077 break;
5078 case FastCapture_Always:
5079 initFastCapture = true;
5080 break;
5081 case FastCapture_Static:
5082 uint32_t primaryOutputSampleRate;
5083 {
5084 AutoMutex _l(audioFlinger->mHardwareLock);
5085 primaryOutputSampleRate = audioFlinger->mPrimaryOutputSampleRate;
5086 }
5087 initFastCapture =
5088 // either capture sample rate is same as (a reasonable) primary output sample rate
5089 (((primaryOutputSampleRate == 44100 || primaryOutputSampleRate == 48000) &&
5090 (mSampleRate == primaryOutputSampleRate)) ||
5091 // or primary output sample rate is unknown, and capture sample rate is reasonable
5092 ((primaryOutputSampleRate == 0) &&
5093 ((mSampleRate == 44100 || mSampleRate == 48000)))) &&
Glenn Kasten9f81de32014-07-27 15:02:23 -07005094 // and the buffer size is < 12 ms
5095 (mFrameCount * 1000) / mSampleRate < 12;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005096 break;
5097 // case FastCapture_Dynamic:
5098 }
5099
5100 if (initFastCapture) {
5101 // create a Pipe for FastMixer to write to, and for us and fast tracks to read from
5102 NBAIO_Format format = mInputSource->format();
Glenn Kasten49d00ad2014-07-21 11:22:03 -07005103 size_t pipeFramesP2 = roundup(mSampleRate / 25); // double-buffering of 20 ms each
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005104 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
5105 void *pipeBuffer;
5106 const sp<MemoryDealer> roHeap(readOnlyHeap());
5107 sp<IMemory> pipeMemory;
5108 if ((roHeap == 0) ||
5109 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
5110 (pipeBuffer = pipeMemory->pointer()) == NULL) {
5111 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
5112 goto failed;
5113 }
5114 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
5115 memset(pipeBuffer, 0, pipeSize);
5116 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
5117 const NBAIO_Format offers[1] = {format};
5118 size_t numCounterOffers = 0;
5119 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
5120 ALOG_ASSERT(index == 0);
5121 mPipeSink = pipe;
5122 PipeReader *pipeReader = new PipeReader(*pipe);
5123 numCounterOffers = 0;
5124 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
5125 ALOG_ASSERT(index == 0);
5126 mPipeSource = pipeReader;
5127 mPipeFramesP2 = pipeFramesP2;
5128 mPipeMemory = pipeMemory;
5129
5130 // create fast capture
5131 mFastCapture = new FastCapture();
5132 FastCaptureStateQueue *sq = mFastCapture->sq();
5133#ifdef STATE_QUEUE_DUMP
5134 // FIXME
5135#endif
5136 FastCaptureState *state = sq->begin();
5137 state->mCblk = NULL;
5138 state->mInputSource = mInputSource.get();
5139 state->mInputSourceGen++;
5140 state->mPipeSink = pipe;
5141 state->mPipeSinkGen++;
5142 state->mFrameCount = mFrameCount;
5143 state->mCommand = FastCaptureState::COLD_IDLE;
5144 // already done in constructor initialization list
5145 //mFastCaptureFutex = 0;
5146 state->mColdFutexAddr = &mFastCaptureFutex;
5147 state->mColdGen++;
5148 state->mDumpState = &mFastCaptureDumpState;
5149#ifdef TEE_SINK
5150 // FIXME
5151#endif
5152 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
5153 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
5154 sq->end();
5155 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5156
5157 // start the fast capture
5158 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
5159 pid_t tid = mFastCapture->getTid();
5160 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
5161 if (err != 0) {
5162 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
5163 kPriorityFastCapture, getpid_cached, tid, err);
5164 }
5165
5166#ifdef AUDIO_WATCHDOG
5167 // FIXME
5168#endif
5169
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005170 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005171 }
5172failed: ;
5173
5174 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08005175}
5176
5177
5178AudioFlinger::RecordThread::~RecordThread()
5179{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005180 if (mFastCapture != 0) {
5181 FastCaptureStateQueue *sq = mFastCapture->sq();
5182 FastCaptureState *state = sq->begin();
5183 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5184 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5185 if (old == -1) {
5186 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5187 }
5188 }
5189 state->mCommand = FastCaptureState::EXIT;
5190 sq->end();
5191 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5192 mFastCapture->join();
5193 mFastCapture.clear();
5194 }
5195 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07005196 mAudioFlinger->unregisterWriter(mNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08005197 delete[] mRsmpInBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005198}
5199
5200void AudioFlinger::RecordThread::onFirstRef()
5201{
5202 run(mName, PRIORITY_URGENT_AUDIO);
5203}
5204
Eric Laurent81784c32012-11-19 14:55:58 -08005205bool AudioFlinger::RecordThread::threadLoop()
5206{
Eric Laurent81784c32012-11-19 14:55:58 -08005207 nsecs_t lastWarning = 0;
5208
5209 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08005210
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005211reacquire_wakelock:
5212 sp<RecordTrack> activeTrack;
Glenn Kasten2b806402013-11-20 16:37:38 -08005213 int activeTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005214 {
5215 Mutex::Autolock _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005216 size_t size = mActiveTracks.size();
5217 activeTracksGen = mActiveTracksGen;
5218 if (size > 0) {
5219 // FIXME an arbitrary choice
5220 activeTrack = mActiveTracks[0];
5221 acquireWakeLock_l(activeTrack->uid());
5222 if (size > 1) {
5223 SortedVector<int> tmp;
5224 for (size_t i = 0; i < size; i++) {
5225 tmp.add(mActiveTracks[i]->uid());
5226 }
5227 updateWakeLockUids_l(tmp);
5228 }
5229 } else {
5230 acquireWakeLock_l(-1);
5231 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005232 }
5233
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005234 // used to request a deferred sleep, to be executed later while mutex is unlocked
5235 uint32_t sleepUs = 0;
5236
5237 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005238 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005239 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07005240
Glenn Kasten5edadd42013-08-14 16:30:49 -07005241 // sleep with mutex unlocked
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005242 if (sleepUs > 0) {
Glenn Kastene7754022014-10-31 12:11:26 -07005243 ATRACE_BEGIN("sleep");
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005244 usleep(sleepUs);
Glenn Kastene7754022014-10-31 12:11:26 -07005245 ATRACE_END();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005246 sleepUs = 0;
Glenn Kasten5edadd42013-08-14 16:30:49 -07005247 }
5248
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005249 // activeTracks accumulates a copy of a subset of mActiveTracks
5250 Vector< sp<RecordTrack> > activeTracks;
5251
Glenn Kasten735f45f2014-08-18 15:51:59 -07005252 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005253 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07005254
Glenn Kasten735f45f2014-08-18 15:51:59 -07005255 // reference to a fast track which is about to be removed
5256 sp<RecordTrack> fastTrackToRemove;
5257
Eric Laurent81784c32012-11-19 14:55:58 -08005258 { // scope for mLock
5259 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08005260
Eric Laurent021cf962014-05-13 10:18:14 -07005261 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005262
Eric Laurent000a4192014-01-29 15:17:32 -08005263 // check exitPending here because checkForNewParameters_l() and
5264 // checkForNewParameters_l() can temporarily release mLock
5265 if (exitPending()) {
5266 break;
5267 }
5268
Glenn Kasten2b806402013-11-20 16:37:38 -08005269 // if no active track(s), then standby and release wakelock
5270 size_t size = mActiveTracks.size();
5271 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07005272 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005273 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08005274 releaseWakeLock_l();
5275 ALOGV("RecordThread: loop stopping");
5276 // go to sleep
5277 mWaitWorkCV.wait(mLock);
5278 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005279 goto reacquire_wakelock;
5280 }
5281
Glenn Kasten2b806402013-11-20 16:37:38 -08005282 if (mActiveTracksGen != activeTracksGen) {
5283 activeTracksGen = mActiveTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005284 SortedVector<int> tmp;
Glenn Kasten2b806402013-11-20 16:37:38 -08005285 for (size_t i = 0; i < size; i++) {
5286 tmp.add(mActiveTracks[i]->uid());
5287 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005288 updateWakeLockUids_l(tmp);
Eric Laurent81784c32012-11-19 14:55:58 -08005289 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005290
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005291 bool doBroadcast = false;
5292 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07005293
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005294 activeTrack = mActiveTracks[i];
5295 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07005296 if (activeTrack->isFastTrack()) {
5297 ALOG_ASSERT(fastTrackToRemove == 0);
5298 fastTrackToRemove = activeTrack;
5299 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005300 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08005301 mActiveTracks.remove(activeTrack);
5302 mActiveTracksGen++;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005303 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07005304 continue;
5305 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005306
5307 TrackBase::track_state activeTrackState = activeTrack->mState;
5308 switch (activeTrackState) {
5309
5310 case TrackBase::PAUSING:
5311 mActiveTracks.remove(activeTrack);
5312 mActiveTracksGen++;
5313 doBroadcast = true;
5314 size--;
5315 continue;
5316
5317 case TrackBase::STARTING_1:
5318 sleepUs = 10000;
5319 i++;
5320 continue;
5321
5322 case TrackBase::STARTING_2:
5323 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005324 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07005325 activeTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005326 break;
5327
5328 case TrackBase::ACTIVE:
5329 break;
5330
5331 case TrackBase::IDLE:
5332 i++;
5333 continue;
5334
5335 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08005336 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07005337 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005338
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005339 activeTracks.add(activeTrack);
5340 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07005341
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005342 if (activeTrack->isFastTrack()) {
5343 ALOG_ASSERT(!mFastTrackAvail);
5344 ALOG_ASSERT(fastTrack == 0);
5345 fastTrack = activeTrack;
5346 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005347 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005348 if (doBroadcast) {
5349 mStartStopCond.broadcast();
5350 }
5351
5352 // sleep if there are no active tracks to process
5353 if (activeTracks.size() == 0) {
5354 if (sleepUs == 0) {
5355 sleepUs = kRecordThreadSleepUs;
5356 }
5357 continue;
5358 }
5359 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07005360
Eric Laurent81784c32012-11-19 14:55:58 -08005361 lockEffectChains_l(effectChains);
5362 }
5363
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005364 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07005365
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005366 size_t size = effectChains.size();
5367 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005368 // thread mutex is not locked, but effect chain is locked
5369 effectChains[i]->process_l();
5370 }
5371
Glenn Kasten735f45f2014-08-18 15:51:59 -07005372 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005373 if (mFastCapture != 0) {
5374 FastCaptureStateQueue *sq = mFastCapture->sq();
5375 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07005376 bool didModify = false;
5377 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005378 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
5379 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
5380 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5381 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5382 if (old == -1) {
5383 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5384 }
5385 }
5386 state->mCommand = FastCaptureState::READ_WRITE;
5387#if 0 // FIXME
5388 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenb187de12014-12-30 08:18:15 -08005389 FastCaptureDumpState::kSamplingNforLowRamDevice :
5390 FastMixerDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005391#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07005392 didModify = true;
5393 }
5394 audio_track_cblk_t *cblkOld = state->mCblk;
5395 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
5396 if (cblkNew != cblkOld) {
5397 state->mCblk = cblkNew;
5398 // block until acked if removing a fast track
5399 if (cblkOld != NULL) {
5400 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
5401 }
5402 didModify = true;
5403 }
5404 sq->end(didModify);
5405 if (didModify) {
5406 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005407#if 0
5408 if (kUseFastCapture == FastCapture_Dynamic) {
5409 mNormalSource = mPipeSource;
5410 }
5411#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005412 }
5413 }
5414
Glenn Kasten735f45f2014-08-18 15:51:59 -07005415 // now run the fast track destructor with thread mutex unlocked
5416 fastTrackToRemove.clear();
5417
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005418 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
5419 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
5420 // slow, then this RecordThread will overrun by not calling HAL read often enough.
5421 // If destination is non-contiguous, first read past the nominal end of buffer, then
5422 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005423
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005424 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005425 ssize_t framesRead;
5426
5427 // If an NBAIO source is present, use it to read the normal capture's data
5428 if (mPipeSource != 0) {
5429 size_t framesToRead = mBufferSize / mFrameSize;
5430 framesRead = mPipeSource->read(&mRsmpInBuffer[rear * mChannelCount],
5431 framesToRead, AudioBufferProvider::kInvalidPTS);
5432 if (framesRead == 0) {
5433 // since pipe is non-blocking, simulate blocking input
5434 sleepUs = (framesToRead * 1000000LL) / mSampleRate;
5435 }
5436 // otherwise use the HAL / AudioStreamIn directly
5437 } else {
5438 ssize_t bytesRead = mInput->stream->read(mInput->stream,
5439 &mRsmpInBuffer[rear * mChannelCount], mBufferSize);
5440 if (bytesRead < 0) {
5441 framesRead = bytesRead;
5442 } else {
5443 framesRead = bytesRead / mFrameSize;
5444 }
5445 }
5446
5447 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
5448 ALOGE("read failed: framesRead=%d", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005449 // Force input into standby so that it tries to recover at next read attempt
5450 inputStandBy();
5451 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005452 }
5453 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005454 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005455 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005456 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005457
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005458 if (mTeeSink != 0) {
5459 (void) mTeeSink->write(&mRsmpInBuffer[rear * mChannelCount], framesRead);
5460 }
5461 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005462 {
5463 size_t part1 = mRsmpInFramesP2 - rear;
5464 if ((size_t) framesRead > part1) {
5465 memcpy(mRsmpInBuffer, &mRsmpInBuffer[mRsmpInFramesP2 * mChannelCount],
5466 (framesRead - part1) * mFrameSize);
5467 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005468 }
5469 rear = mRsmpInRear += framesRead;
5470
5471 size = activeTracks.size();
5472 // loop over each active track
5473 for (size_t i = 0; i < size; i++) {
5474 activeTrack = activeTracks[i];
5475
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005476 // skip fast tracks, as those are handled directly by FastCapture
5477 if (activeTrack->isFastTrack()) {
5478 continue;
5479 }
5480
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005481 enum {
5482 OVERRUN_UNKNOWN,
5483 OVERRUN_TRUE,
5484 OVERRUN_FALSE
5485 } overrun = OVERRUN_UNKNOWN;
5486
5487 // loop over getNextBuffer to handle circular sink
5488 for (;;) {
5489
5490 activeTrack->mSink.frameCount = ~0;
5491 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
5492 size_t framesOut = activeTrack->mSink.frameCount;
5493 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
5494
5495 int32_t front = activeTrack->mRsmpInFront;
5496 ssize_t filled = rear - front;
5497 size_t framesIn;
5498
5499 if (filled < 0) {
5500 // should not happen, but treat like a massive overrun and re-sync
5501 framesIn = 0;
5502 activeTrack->mRsmpInFront = rear;
5503 overrun = OVERRUN_TRUE;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005504 } else if ((size_t) filled <= mRsmpInFrames) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005505 framesIn = (size_t) filled;
5506 } else {
5507 // client is not keeping up with server, but give it latest data
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005508 framesIn = mRsmpInFrames;
5509 activeTrack->mRsmpInFront = front = rear - framesIn;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005510 overrun = OVERRUN_TRUE;
5511 }
5512
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005513 if (framesOut == 0 || framesIn == 0) {
5514 break;
5515 }
5516
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005517 if (activeTrack->mResampler == NULL) {
5518 // no resampling
5519 if (framesIn > framesOut) {
5520 framesIn = framesOut;
5521 } else {
5522 framesOut = framesIn;
5523 }
5524 int8_t *dst = activeTrack->mSink.i8;
5525 while (framesIn > 0) {
5526 front &= mRsmpInFramesP2 - 1;
5527 size_t part1 = mRsmpInFramesP2 - front;
5528 if (part1 > framesIn) {
5529 part1 = framesIn;
5530 }
5531 int8_t *src = (int8_t *)mRsmpInBuffer + (front * mFrameSize);
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005532 if (mChannelCount == activeTrack->mChannelCount) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005533 memcpy(dst, src, part1 * mFrameSize);
5534 } else if (mChannelCount == 1) {
Glenn Kastencd704212014-07-14 17:26:36 -07005535 upmix_to_stereo_i16_from_mono_i16((int16_t *)dst, (const int16_t *)src,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005536 part1);
5537 } else {
Glenn Kastenb187de12014-12-30 08:18:15 -08005538 downmix_to_mono_i16_from_stereo_i16((int16_t *)dst,
5539 (const int16_t *)src, part1);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005540 }
5541 dst += part1 * activeTrack->mFrameSize;
5542 front += part1;
5543 framesIn -= part1;
5544 }
5545 activeTrack->mRsmpInFront += framesOut;
5546
5547 } else {
5548 // resampling
5549 // FIXME framesInNeeded should really be part of resampler API, and should
5550 // depend on the SRC ratio
5551 // to keep mRsmpInBuffer full so resampler always has sufficient input
5552 size_t framesInNeeded;
5553 // FIXME only re-calculate when it changes, and optimize for common ratios
Andy Hung8661aaf2014-07-28 14:38:41 -07005554 // Do not precompute in/out because floating point is not associative
5555 // e.g. a*b/c != a*(b/c).
5556 const double in(mSampleRate);
5557 const double out(activeTrack->mSampleRate);
5558 framesInNeeded = ceil(framesOut * in / out) + 1;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005559 ALOGV("need %u frames in to produce %u out given in/out ratio of %.4g",
Andy Hung8661aaf2014-07-28 14:38:41 -07005560 framesInNeeded, framesOut, in / out);
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005561 // Although we theoretically have framesIn in circular buffer, some of those are
5562 // unreleased frames, and thus must be discounted for purpose of budgeting.
5563 size_t unreleased = activeTrack->mRsmpInUnrel;
5564 framesIn = framesIn > unreleased ? framesIn - unreleased : 0;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005565 if (framesIn < framesInNeeded) {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005566 ALOGV("not enough to resample: have %u frames in but need %u in to "
5567 "produce %u out given in/out ratio of %.4g",
Andy Hung8661aaf2014-07-28 14:38:41 -07005568 framesIn, framesInNeeded, framesOut, in / out);
5569 size_t newFramesOut = framesIn > 0 ? floor((framesIn - 1) * out / in) : 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005570 LOG_ALWAYS_FATAL_IF(newFramesOut >= framesOut);
5571 if (newFramesOut == 0) {
5572 break;
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005573 }
Andy Hung8661aaf2014-07-28 14:38:41 -07005574 framesInNeeded = ceil(newFramesOut * in / out) + 1;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005575 ALOGV("now need %u frames in to produce %u out given out/in ratio of %.4g",
Andy Hung8661aaf2014-07-28 14:38:41 -07005576 framesInNeeded, newFramesOut, out / in);
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005577 LOG_ALWAYS_FATAL_IF(framesIn < framesInNeeded);
5578 ALOGV("success 2: have %u frames in and need %u in to produce %u out "
5579 "given in/out ratio of %.4g",
Andy Hung8661aaf2014-07-28 14:38:41 -07005580 framesIn, framesInNeeded, newFramesOut, in / out);
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005581 framesOut = newFramesOut;
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005582 } else {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005583 ALOGV("success 1: have %u in and need %u in to produce %u out "
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005584 "given in/out ratio of %.4g",
Andy Hung8661aaf2014-07-28 14:38:41 -07005585 framesIn, framesInNeeded, framesOut, in / out);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005586 }
5587
5588 // reallocate mRsmpOutBuffer as needed; we will grow but never shrink
5589 if (activeTrack->mRsmpOutFrameCount < framesOut) {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005590 // FIXME why does each track need it's own mRsmpOutBuffer? can't they share?
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005591 delete[] activeTrack->mRsmpOutBuffer;
5592 // resampler always outputs stereo
5593 activeTrack->mRsmpOutBuffer = new int32_t[framesOut * FCC_2];
5594 activeTrack->mRsmpOutFrameCount = framesOut;
5595 }
5596
5597 // resampler accumulates, but we only have one source track
5598 memset(activeTrack->mRsmpOutBuffer, 0, framesOut * FCC_2 * sizeof(int32_t));
5599 activeTrack->mResampler->resample(activeTrack->mRsmpOutBuffer, framesOut,
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005600 // FIXME how about having activeTrack implement this interface itself?
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005601 activeTrack->mResamplerBufferProvider
5602 /*this*/ /* AudioBufferProvider* */);
5603 // ditherAndClamp() works as long as all buffers returned by
5604 // activeTrack->getNextBuffer() are 32 bit aligned which should be always true.
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005605 if (activeTrack->mChannelCount == 1) {
Andy Hung84a0c6e2014-04-02 11:24:53 -07005606 // temporarily type pun mRsmpOutBuffer from Q4.27 to int16_t
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005607 ditherAndClamp(activeTrack->mRsmpOutBuffer, activeTrack->mRsmpOutBuffer,
5608 framesOut);
5609 // the resampler always outputs stereo samples:
5610 // do post stereo to mono conversion
5611 downmix_to_mono_i16_from_stereo_i16(activeTrack->mSink.i16,
Glenn Kastencd704212014-07-14 17:26:36 -07005612 (const int16_t *)activeTrack->mRsmpOutBuffer, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005613 } else {
5614 ditherAndClamp((int32_t *)activeTrack->mSink.raw,
5615 activeTrack->mRsmpOutBuffer, framesOut);
5616 }
5617 // now done with mRsmpOutBuffer
5618
5619 }
5620
5621 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
5622 overrun = OVERRUN_FALSE;
5623 }
5624
5625 if (activeTrack->mFramesToDrop == 0) {
5626 if (framesOut > 0) {
5627 activeTrack->mSink.frameCount = framesOut;
5628 activeTrack->releaseBuffer(&activeTrack->mSink);
5629 }
5630 } else {
5631 // FIXME could do a partial drop of framesOut
5632 if (activeTrack->mFramesToDrop > 0) {
5633 activeTrack->mFramesToDrop -= framesOut;
5634 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005635 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005636 }
5637 } else {
5638 activeTrack->mFramesToDrop += framesOut;
5639 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
5640 activeTrack->mSyncStartEvent->isCancelled()) {
5641 ALOGW("Synced record %s, session %d, trigger session %d",
5642 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
5643 activeTrack->sessionId(),
5644 (activeTrack->mSyncStartEvent != 0) ?
5645 activeTrack->mSyncStartEvent->triggerSession() : 0);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005646 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005647 }
5648 }
5649 }
5650
5651 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005652 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005653 }
5654 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005655
5656 switch (overrun) {
5657 case OVERRUN_TRUE:
5658 // client isn't retrieving buffers fast enough
5659 if (!activeTrack->setOverflow()) {
5660 nsecs_t now = systemTime();
5661 // FIXME should lastWarning per track?
5662 if ((now - lastWarning) > kWarningThrottleNs) {
5663 ALOGW("RecordThread: buffer overflow");
5664 lastWarning = now;
5665 }
5666 }
5667 break;
5668 case OVERRUN_FALSE:
5669 activeTrack->clearOverflow();
5670 break;
5671 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005672 break;
5673 }
5674
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005675 }
5676
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005677unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08005678 // enable changes in effect chain
5679 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005680 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08005681 }
5682
Glenn Kasten93e471f2013-08-19 08:40:07 -07005683 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08005684
5685 {
5686 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07005687 for (size_t i = 0; i < mTracks.size(); i++) {
5688 sp<RecordTrack> track = mTracks[i];
5689 track->invalidate();
5690 }
Glenn Kasten2b806402013-11-20 16:37:38 -08005691 mActiveTracks.clear();
5692 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08005693 mStartStopCond.broadcast();
5694 }
5695
5696 releaseWakeLock();
5697
5698 ALOGV("RecordThread %p exiting", this);
5699 return false;
5700}
5701
Glenn Kasten93e471f2013-08-19 08:40:07 -07005702void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08005703{
5704 if (!mStandby) {
5705 inputStandBy();
5706 mStandby = true;
5707 }
5708}
5709
5710void AudioFlinger::RecordThread::inputStandBy()
5711{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005712 // Idle the fast capture if it's currently running
5713 if (mFastCapture != 0) {
5714 FastCaptureStateQueue *sq = mFastCapture->sq();
5715 FastCaptureState *state = sq->begin();
5716 if (!(state->mCommand & FastCaptureState::IDLE)) {
5717 state->mCommand = FastCaptureState::COLD_IDLE;
5718 state->mColdFutexAddr = &mFastCaptureFutex;
5719 state->mColdGen++;
5720 mFastCaptureFutex = 0;
5721 sq->end();
5722 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
5723 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
5724#if 0
5725 if (kUseFastCapture == FastCapture_Dynamic) {
5726 // FIXME
5727 }
5728#endif
5729#ifdef AUDIO_WATCHDOG
5730 // FIXME
5731#endif
5732 } else {
5733 sq->end(false /*didModify*/);
5734 }
5735 }
Eric Laurent81784c32012-11-19 14:55:58 -08005736 mInput->stream->common.standby(&mInput->stream->common);
5737}
5738
Glenn Kasten05997e22014-03-13 15:08:33 -07005739// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07005740sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08005741 const sp<AudioFlinger::Client>& client,
5742 uint32_t sampleRate,
5743 audio_format_t format,
5744 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08005745 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08005746 int sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07005747 size_t *notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005748 int uid,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07005749 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08005750 pid_t tid,
5751 status_t *status)
5752{
Glenn Kasten74935e42013-12-19 08:56:45 -08005753 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005754 sp<RecordTrack> track;
5755 status_t lStatus;
5756
Glenn Kasten90e58b12013-07-31 16:16:02 -07005757 // client expresses a preference for FAST, but we get the final say
5758 if (*flags & IAudioFlinger::TRACK_FAST) {
5759 if (
Glenn Kasten74105912014-07-03 12:28:53 -07005760 // use case: callback handler
5761 (tid != -1) &&
5762 // frame count is not specified, or is exactly the pipe depth
5763 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005764 // PCM data
5765 audio_is_linear_pcm(format) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005766 // native format
5767 (format == mFormat) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005768 // native channel mask
5769 (channelMask == mChannelMask) &&
5770 // native hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07005771 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005772 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005773 hasFastCapture() &&
5774 // there are sufficient fast track slots available
5775 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07005776 ) {
Glenn Kasten74105912014-07-03 12:28:53 -07005777 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%u mFrameCount=%u",
Glenn Kasten90e58b12013-07-31 16:16:02 -07005778 frameCount, mFrameCount);
5779 } else {
Glenn Kasten74105912014-07-03 12:28:53 -07005780 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%u mFrameCount=%u mPipeFramesP2=%u "
5781 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005782 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Glenn Kasten74105912014-07-03 12:28:53 -07005783 frameCount, mFrameCount, mPipeFramesP2,
5784 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
5785 hasFastCapture(), tid, mFastTrackAvail);
Glenn Kasten90e58b12013-07-31 16:16:02 -07005786 *flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kasten74105912014-07-03 12:28:53 -07005787 }
5788 }
5789
5790 // compute track buffer size in frames, and suggest the notification frame count
5791 if (*flags & IAudioFlinger::TRACK_FAST) {
5792 // fast track: frame count is exactly the pipe depth
5793 frameCount = mPipeFramesP2;
5794 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
5795 *notificationFrames = mFrameCount;
5796 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07005797 // not fast track: max notification period is resampled equivalent of one HAL buffer time
5798 // or 20 ms if there is a fast capture
5799 // TODO This could be a roundupRatio inline, and const
5800 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
5801 * sampleRate + mSampleRate - 1) / mSampleRate;
5802 // minimum number of notification periods is at least kMinNotifications,
5803 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
5804 static const size_t kMinNotifications = 3;
5805 static const uint32_t kMinMs = 30;
5806 // TODO This could be a roundupRatio inline
5807 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
5808 // TODO This could be a roundupRatio inline
5809 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
5810 maxNotificationFrames;
5811 const size_t minFrameCount = maxNotificationFrames *
5812 max(kMinNotifications, minNotificationsByMs);
5813 frameCount = max(frameCount, minFrameCount);
5814 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
5815 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07005816 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07005817 }
Glenn Kasten74935e42013-12-19 08:56:45 -08005818 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07005819
Glenn Kasten15e57982013-09-24 11:52:37 -07005820 lStatus = initCheck();
5821 if (lStatus != NO_ERROR) {
5822 ALOGE("createRecordTrack_l() audio driver not initialized");
5823 goto Exit;
5824 }
Eric Laurent81784c32012-11-19 14:55:58 -08005825
5826 { // scope for mLock
5827 Mutex::Autolock _l(mLock);
5828
5829 track = new RecordTrack(this, client, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07005830 format, channelMask, frameCount, NULL, sessionId, uid,
5831 *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08005832
Glenn Kasten03003332013-08-06 15:40:54 -07005833 lStatus = track->initCheck();
5834 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07005835 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08005836 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08005837 goto Exit;
5838 }
5839 mTracks.add(track);
5840
5841 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5842 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
5843 mAudioFlinger->btNrecIsOff();
5844 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
5845 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07005846
5847 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
5848 pid_t callingPid = IPCThreadState::self()->getCallingPid();
5849 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
5850 // so ask activity manager to do this on our behalf
5851 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
5852 }
Eric Laurent81784c32012-11-19 14:55:58 -08005853 }
Glenn Kasten05997e22014-03-13 15:08:33 -07005854
Eric Laurent81784c32012-11-19 14:55:58 -08005855 lStatus = NO_ERROR;
5856
5857Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07005858 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08005859 return track;
5860}
5861
5862status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
5863 AudioSystem::sync_event_t event,
5864 int triggerSession)
5865{
5866 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
5867 sp<ThreadBase> strongMe = this;
5868 status_t status = NO_ERROR;
5869
5870 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005871 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08005872 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005873 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08005874 triggerSession,
5875 recordTrack->sessionId(),
5876 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005877 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08005878 // Sync event can be cancelled by the trigger session if the track is not in a
5879 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005880 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005881 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08005882 } else {
5883 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005884 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005885 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08005886 }
5887 }
5888
5889 {
Glenn Kasten47c20702013-08-13 15:37:35 -07005890 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08005891 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005892 if (mActiveTracks.indexOf(recordTrack) >= 0) {
5893 if (recordTrack->mState == TrackBase::PAUSING) {
5894 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005895 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005896 } else {
5897 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08005898 }
5899 return status;
5900 }
5901
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005902 // TODO consider other ways of handling this, such as changing the state to :STARTING and
5903 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
5904 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005905 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08005906 mActiveTracks.add(recordTrack);
5907 mActiveTracksGen++;
Eric Laurent83b88082014-06-20 18:31:16 -07005908 status_t status = NO_ERROR;
5909 if (recordTrack->isExternalTrack()) {
5910 mLock.unlock();
Eric Laurent4dc68062014-07-28 17:26:49 -07005911 status = AudioSystem::startInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07005912 mLock.lock();
5913 // FIXME should verify that recordTrack is still in mActiveTracks
5914 if (status != NO_ERROR) {
5915 mActiveTracks.remove(recordTrack);
5916 mActiveTracksGen++;
5917 recordTrack->clearSyncStartEvent();
5918 ALOGV("RecordThread::start error %d", status);
5919 return status;
5920 }
Eric Laurent81784c32012-11-19 14:55:58 -08005921 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005922 // Catch up with current buffer indices if thread is already running.
5923 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
5924 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
5925 // see previously buffered data before it called start(), but with greater risk of overrun.
5926
5927 recordTrack->mRsmpInFront = mRsmpInRear;
5928 recordTrack->mRsmpInUnrel = 0;
5929 // FIXME why reset?
5930 if (recordTrack->mResampler != NULL) {
5931 recordTrack->mResampler->reset();
Eric Laurent81784c32012-11-19 14:55:58 -08005932 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005933 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08005934 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08005935 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08005936 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005937 ALOGV("Record failed to start");
5938 status = BAD_VALUE;
5939 goto startError;
5940 }
Eric Laurent81784c32012-11-19 14:55:58 -08005941 return status;
5942 }
Glenn Kasten7c027242012-12-26 14:43:16 -08005943
Eric Laurent81784c32012-11-19 14:55:58 -08005944startError:
Eric Laurent83b88082014-06-20 18:31:16 -07005945 if (recordTrack->isExternalTrack()) {
Eric Laurent4dc68062014-07-28 17:26:49 -07005946 AudioSystem::stopInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07005947 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005948 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005949 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08005950 return status;
5951}
5952
Eric Laurent81784c32012-11-19 14:55:58 -08005953void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
5954{
5955 sp<SyncEvent> strongEvent = event.promote();
5956
5957 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08005958 sp<RefBase> ptr = strongEvent->cookie().promote();
5959 if (ptr != 0) {
5960 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
5961 recordTrack->handleSyncStartEvent(strongEvent);
5962 }
Eric Laurent81784c32012-11-19 14:55:58 -08005963 }
5964}
5965
Glenn Kastena8356f62013-07-25 14:37:52 -07005966bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08005967 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07005968 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005969 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08005970 return false;
5971 }
Glenn Kasten47c20702013-08-13 15:37:35 -07005972 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08005973 recordTrack->mState = TrackBase::PAUSING;
5974 // do not wait for mStartStopCond if exiting
5975 if (exitPending()) {
5976 return true;
5977 }
Glenn Kasten47c20702013-08-13 15:37:35 -07005978 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08005979 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005980 // if we have been restarted, recordTrack is in mActiveTracks here
5981 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005982 ALOGV("Record stopped OK");
5983 return true;
5984 }
5985 return false;
5986}
5987
Glenn Kasten0f11b512014-01-31 16:18:54 -08005988bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08005989{
5990 return false;
5991}
5992
Glenn Kasten0f11b512014-01-31 16:18:54 -08005993status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005994{
5995#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
5996 if (!isValidSyncEvent(event)) {
5997 return BAD_VALUE;
5998 }
5999
6000 int eventSession = event->triggerSession();
6001 status_t ret = NAME_NOT_FOUND;
6002
6003 Mutex::Autolock _l(mLock);
6004
6005 for (size_t i = 0; i < mTracks.size(); i++) {
6006 sp<RecordTrack> track = mTracks[i];
6007 if (eventSession == track->sessionId()) {
6008 (void) track->setSyncEvent(event);
6009 ret = NO_ERROR;
6010 }
6011 }
6012 return ret;
6013#else
6014 return BAD_VALUE;
6015#endif
6016}
6017
6018// destroyTrack_l() must be called with ThreadBase::mLock held
6019void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6020{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006021 track->terminate();
6022 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08006023 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08006024 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006025 removeTrack_l(track);
6026 }
6027}
6028
6029void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6030{
6031 mTracks.remove(track);
6032 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006033 if (track->isFastTrack()) {
6034 ALOG_ASSERT(!mFastTrackAvail);
6035 mFastTrackAvail = true;
6036 }
Eric Laurent81784c32012-11-19 14:55:58 -08006037}
6038
6039void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6040{
6041 dumpInternals(fd, args);
6042 dumpTracks(fd, args);
6043 dumpEffectChains(fd, args);
6044}
6045
6046void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6047{
Elliott Hughes87cebad2014-05-22 10:14:43 -07006048 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08006049
Glenn Kasten2b806402013-11-20 16:37:38 -08006050 if (mActiveTracks.size() > 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006051 dprintf(fd, " Buffer size: %zu bytes\n", mBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006052 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006053 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006054 }
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006055 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006056 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Eric Laurent81784c32012-11-19 14:55:58 -08006057
Eric Laurent81784c32012-11-19 14:55:58 -08006058 dumpBase(fd, args);
6059}
6060
Glenn Kasten0f11b512014-01-31 16:18:54 -08006061void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006062{
6063 const size_t SIZE = 256;
6064 char buffer[SIZE];
6065 String8 result;
6066
Marco Nelissenb2208842014-02-07 14:00:50 -08006067 size_t numtracks = mTracks.size();
6068 size_t numactive = mActiveTracks.size();
6069 size_t numactiveseen = 0;
Elliott Hughes87cebad2014-05-22 10:14:43 -07006070 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08006071 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006072 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08006073 RecordTrack::appendDumpHeader(result);
6074 for (size_t i = 0; i < numtracks ; ++i) {
6075 sp<RecordTrack> track = mTracks[i];
6076 if (track != 0) {
6077 bool active = mActiveTracks.indexOf(track) >= 0;
6078 if (active) {
6079 numactiveseen++;
6080 }
6081 track->dump(buffer, SIZE, active);
6082 result.append(buffer);
6083 }
Eric Laurent81784c32012-11-19 14:55:58 -08006084 }
Marco Nelissenb2208842014-02-07 14:00:50 -08006085 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006086 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006087 }
6088
Marco Nelissenb2208842014-02-07 14:00:50 -08006089 if (numactiveseen != numactive) {
6090 snprintf(buffer, SIZE, " The following tracks are in the active list but"
6091 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006092 result.append(buffer);
6093 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08006094 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08006095 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08006096 if (mTracks.indexOf(track) < 0) {
6097 track->dump(buffer, SIZE, true);
6098 result.append(buffer);
6099 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006100 }
Eric Laurent81784c32012-11-19 14:55:58 -08006101
6102 }
6103 write(fd, result.string(), result.size());
6104}
6105
6106// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006107status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
6108 AudioBufferProvider::Buffer* buffer, int64_t pts __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006109{
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006110 RecordTrack *activeTrack = mRecordTrack;
6111 sp<ThreadBase> threadBase = activeTrack->mThread.promote();
6112 if (threadBase == 0) {
6113 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006114 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006115 return NOT_ENOUGH_DATA;
6116 }
6117 RecordThread *recordThread = (RecordThread *) threadBase.get();
6118 int32_t rear = recordThread->mRsmpInRear;
6119 int32_t front = activeTrack->mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07006120 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006121 // FIXME should not be P2 (don't want to increase latency)
6122 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006123 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07006124 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006125 front &= recordThread->mRsmpInFramesP2 - 1;
6126 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07006127 if (part1 > (size_t) filled) {
6128 part1 = filled;
6129 }
6130 size_t ask = buffer->frameCount;
6131 ALOG_ASSERT(ask > 0);
6132 if (part1 > ask) {
6133 part1 = ask;
6134 }
6135 if (part1 == 0) {
6136 // Higher-level should keep mRsmpInBuffer full, and not call resampler if empty
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006137 LOG_ALWAYS_FATAL("RecordThread::getNextBuffer() starved");
Glenn Kasten85948432013-08-19 12:09:05 -07006138 buffer->raw = NULL;
6139 buffer->frameCount = 0;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006140 activeTrack->mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07006141 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08006142 }
6143
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006144 buffer->raw = recordThread->mRsmpInBuffer + front * recordThread->mChannelCount;
Glenn Kasten85948432013-08-19 12:09:05 -07006145 buffer->frameCount = part1;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006146 activeTrack->mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08006147 return NO_ERROR;
6148}
6149
6150// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006151void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
6152 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006153{
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006154 RecordTrack *activeTrack = mRecordTrack;
Glenn Kasten85948432013-08-19 12:09:05 -07006155 size_t stepCount = buffer->frameCount;
6156 if (stepCount == 0) {
6157 return;
6158 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006159 ALOG_ASSERT(stepCount <= activeTrack->mRsmpInUnrel);
6160 activeTrack->mRsmpInUnrel -= stepCount;
6161 activeTrack->mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07006162 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006163 buffer->frameCount = 0;
6164}
6165
Eric Laurent10351942014-05-08 18:49:52 -07006166bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
6167 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006168{
6169 bool reconfig = false;
6170
Eric Laurent10351942014-05-08 18:49:52 -07006171 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006172
Eric Laurent10351942014-05-08 18:49:52 -07006173 audio_format_t reqFormat = mFormat;
6174 uint32_t samplingRate = mSampleRate;
6175 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
6176
6177 AudioParameter param = AudioParameter(keyValuePair);
6178 int value;
6179 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
6180 // channel count change can be requested. Do we mandate the first client defines the
6181 // HAL sampling rate and channel count or do we allow changes on the fly?
6182 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6183 samplingRate = value;
6184 reconfig = true;
6185 }
6186 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
6187 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
6188 status = BAD_VALUE;
6189 } else {
6190 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08006191 reconfig = true;
6192 }
Eric Laurent10351942014-05-08 18:49:52 -07006193 }
6194 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
6195 audio_channel_mask_t mask = (audio_channel_mask_t) value;
6196 if (mask != AUDIO_CHANNEL_IN_MONO && mask != AUDIO_CHANNEL_IN_STEREO) {
6197 status = BAD_VALUE;
6198 } else {
6199 channelMask = mask;
6200 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006201 }
Eric Laurent10351942014-05-08 18:49:52 -07006202 }
6203 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6204 // do not accept frame count changes if tracks are open as the track buffer
6205 // size depends on frame count and correct behavior would not be guaranteed
6206 // if frame count is changed after track creation
6207 if (mActiveTracks.size() > 0) {
6208 status = INVALID_OPERATION;
6209 } else {
6210 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006211 }
Eric Laurent10351942014-05-08 18:49:52 -07006212 }
6213 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6214 // forward device change to effects that have requested to be
6215 // aware of attached audio device.
6216 for (size_t i = 0; i < mEffectChains.size(); i++) {
6217 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08006218 }
Eric Laurent81784c32012-11-19 14:55:58 -08006219
Eric Laurent10351942014-05-08 18:49:52 -07006220 // store input device and output device but do not forward output device to audio HAL.
6221 // Note that status is ignored by the caller for output device
6222 // (see AudioFlinger::setParameters()
6223 if (audio_is_output_devices(value)) {
6224 mOutDevice = value;
6225 status = BAD_VALUE;
6226 } else {
6227 mInDevice = value;
6228 // disable AEC and NS if the device is a BT SCO headset supporting those
6229 // pre processings
6230 if (mTracks.size() > 0) {
6231 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6232 mAudioFlinger->btNrecIsOff();
6233 for (size_t i = 0; i < mTracks.size(); i++) {
6234 sp<RecordTrack> track = mTracks[i];
6235 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
6236 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08006237 }
6238 }
6239 }
Eric Laurent10351942014-05-08 18:49:52 -07006240 }
6241 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
6242 mAudioSource != (audio_source_t)value) {
6243 // forward device change to effects that have requested to be
6244 // aware of attached audio device.
6245 for (size_t i = 0; i < mEffectChains.size(); i++) {
6246 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08006247 }
Eric Laurent10351942014-05-08 18:49:52 -07006248 mAudioSource = (audio_source_t)value;
6249 }
Glenn Kastene198c362013-08-13 09:13:36 -07006250
Eric Laurent10351942014-05-08 18:49:52 -07006251 if (status == NO_ERROR) {
6252 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6253 keyValuePair.string());
6254 if (status == INVALID_OPERATION) {
6255 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006256 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6257 keyValuePair.string());
Eric Laurent10351942014-05-08 18:49:52 -07006258 }
6259 if (reconfig) {
6260 if (status == BAD_VALUE &&
6261 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
6262 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
6263 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
6264 <= (2 * samplingRate)) &&
Andy Hunge5412692014-05-16 11:25:07 -07006265 audio_channel_count_from_in_mask(
6266 mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
Eric Laurent10351942014-05-08 18:49:52 -07006267 (channelMask == AUDIO_CHANNEL_IN_MONO ||
6268 channelMask == AUDIO_CHANNEL_IN_STEREO)) {
6269 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006270 }
Eric Laurent10351942014-05-08 18:49:52 -07006271 if (status == NO_ERROR) {
6272 readInputParameters_l();
6273 sendIoConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08006274 }
6275 }
Eric Laurent81784c32012-11-19 14:55:58 -08006276 }
Eric Laurent10351942014-05-08 18:49:52 -07006277
Eric Laurent81784c32012-11-19 14:55:58 -08006278 return reconfig;
6279}
6280
6281String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6282{
Eric Laurent81784c32012-11-19 14:55:58 -08006283 Mutex::Autolock _l(mLock);
6284 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07006285 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08006286 }
6287
Glenn Kastend8ea6992013-07-16 14:17:15 -07006288 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
6289 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08006290 free(s);
6291 return out_s8;
6292}
6293
Eric Laurent021cf962014-05-13 10:18:14 -07006294void AudioFlinger::RecordThread::audioConfigChanged(int event, int param __unused) {
Eric Laurent81784c32012-11-19 14:55:58 -08006295 AudioSystem::OutputDescriptor desc;
Glenn Kastenb2737d02013-08-19 12:03:11 -07006296 const void *param2 = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006297
6298 switch (event) {
6299 case AudioSystem::INPUT_OPENED:
6300 case AudioSystem::INPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07006301 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08006302 desc.samplingRate = mSampleRate;
6303 desc.format = mFormat;
6304 desc.frameCount = mFrameCount;
6305 desc.latency = 0;
6306 param2 = &desc;
6307 break;
6308
6309 case AudioSystem::INPUT_CLOSED:
6310 default:
6311 break;
6312 }
Eric Laurent021cf962014-05-13 10:18:14 -07006313 mAudioFlinger->audioConfigChanged(event, mId, param2);
Eric Laurent81784c32012-11-19 14:55:58 -08006314}
6315
Glenn Kastendeca2ae2014-02-07 10:25:56 -08006316void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006317{
Eric Laurent81784c32012-11-19 14:55:58 -08006318 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
6319 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Andy Hunge5412692014-05-16 11:25:07 -07006320 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Andy Hung463be252014-07-10 16:56:07 -07006321 mHALFormat = mInput->stream->common.get_format(&mInput->stream->common);
6322 mFormat = mHALFormat;
Glenn Kasten291bb6d2013-07-16 17:23:39 -07006323 if (mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08006324 ALOGE("HAL format %#x not supported; must be AUDIO_FORMAT_PCM_16_BIT", mFormat);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07006325 }
Eric Laurent665470b2014-07-03 16:37:08 -07006326 mFrameSize = audio_stream_in_frame_size(mInput->stream);
Glenn Kasten548efc92012-11-29 08:48:51 -08006327 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
6328 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006329 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08006330 // 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 -07006331 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08006332 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006333 // A larger value should allow more old data to be read after a track calls start(),
6334 // without increasing latency.
Glenn Kastene8426142014-02-28 16:45:03 -08006335 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07006336 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006337 delete[] mRsmpInBuffer;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006338
6339 // TODO optimize audio capture buffer sizes ...
6340 // Here we calculate the size of the sliding buffer used as a source
6341 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
6342 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
6343 // be better to have it derived from the pipe depth in the long term.
6344 // The current value is higher than necessary. However it should not add to latency.
6345
Glenn Kasten85948432013-08-19 12:09:05 -07006346 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
6347 mRsmpInBuffer = new int16_t[(mRsmpInFramesP2 + mFrameCount - 1) * mChannelCount];
Eric Laurent81784c32012-11-19 14:55:58 -08006348
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006349 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
6350 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08006351}
6352
Glenn Kasten5f972c02014-01-13 09:59:31 -08006353uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08006354{
6355 Mutex::Autolock _l(mLock);
6356 if (initCheck() != NO_ERROR) {
6357 return 0;
6358 }
6359
6360 return mInput->stream->get_input_frames_lost(mInput->stream);
6361}
6362
6363uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
6364{
6365 Mutex::Autolock _l(mLock);
6366 uint32_t result = 0;
6367 if (getEffectChain_l(sessionId) != 0) {
6368 result = EFFECT_SESSION;
6369 }
6370
6371 for (size_t i = 0; i < mTracks.size(); ++i) {
6372 if (sessionId == mTracks[i]->sessionId()) {
6373 result |= TRACK_SESSION;
6374 break;
6375 }
6376 }
6377
6378 return result;
6379}
6380
6381KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
6382{
6383 KeyedVector<int, bool> ids;
6384 Mutex::Autolock _l(mLock);
6385 for (size_t j = 0; j < mTracks.size(); ++j) {
6386 sp<RecordThread::RecordTrack> track = mTracks[j];
6387 int sessionId = track->sessionId();
6388 if (ids.indexOfKey(sessionId) < 0) {
6389 ids.add(sessionId, true);
6390 }
6391 }
6392 return ids;
6393}
6394
6395AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
6396{
6397 Mutex::Autolock _l(mLock);
6398 AudioStreamIn *input = mInput;
6399 mInput = NULL;
6400 return input;
6401}
6402
6403// this method must always be called either with ThreadBase mLock held or inside the thread loop
6404audio_stream_t* AudioFlinger::RecordThread::stream() const
6405{
6406 if (mInput == NULL) {
6407 return NULL;
6408 }
6409 return &mInput->stream->common;
6410}
6411
6412status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6413{
6414 // only one chain per input thread
6415 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07006416 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08006417 return INVALID_OPERATION;
6418 }
6419 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07006420 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08006421 chain->setInBuffer(NULL);
6422 chain->setOutBuffer(NULL);
6423
6424 checkSuspendOnAddEffectChain_l(chain);
6425
Eric Laurent1b928682014-10-02 19:41:47 -07006426 // make sure enabled pre processing effects state is communicated to the HAL as we
6427 // just moved them to a new input stream.
6428 chain->syncHalEffectsState();
6429
Eric Laurent81784c32012-11-19 14:55:58 -08006430 mEffectChains.add(chain);
6431
6432 return NO_ERROR;
6433}
6434
6435size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6436{
6437 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
6438 ALOGW_IF(mEffectChains.size() != 1,
6439 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6440 chain.get(), mEffectChains.size(), this);
6441 if (mEffectChains.size() == 1) {
6442 mEffectChains.removeAt(0);
6443 }
6444 return 0;
6445}
6446
Eric Laurent1c333e22014-05-20 10:48:17 -07006447status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
6448 audio_patch_handle_t *handle)
6449{
6450 status_t status = NO_ERROR;
6451 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
6452 // store new device and send to effects
6453 mInDevice = patch->sources[0].ext.device.type;
6454 for (size_t i = 0; i < mEffectChains.size(); i++) {
6455 mEffectChains[i]->setDevice_l(mInDevice);
6456 }
6457
6458 // disable AEC and NS if the device is a BT SCO headset supporting those
6459 // pre processings
6460 if (mTracks.size() > 0) {
6461 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6462 mAudioFlinger->btNrecIsOff();
6463 for (size_t i = 0; i < mTracks.size(); i++) {
6464 sp<RecordTrack> track = mTracks[i];
6465 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
6466 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
6467 }
6468 }
6469
6470 // store new source and send to effects
6471 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
6472 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
6473 for (size_t i = 0; i < mEffectChains.size(); i++) {
6474 mEffectChains[i]->setAudioSource_l(mAudioSource);
6475 }
6476 }
6477
6478 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
6479 status = hwDevice->create_audio_patch(hwDevice,
6480 patch->num_sources,
6481 patch->sources,
6482 patch->num_sinks,
6483 patch->sinks,
6484 handle);
6485 } else {
6486 ALOG_ASSERT(false, "createAudioPatch_l() called on a pre 3.0 HAL");
6487 }
6488 return status;
6489}
6490
6491status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
6492{
6493 status_t status = NO_ERROR;
6494 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
6495 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
6496 status = hwDevice->release_audio_patch(hwDevice, handle);
6497 } else {
6498 ALOG_ASSERT(false, "releaseAudioPatch_l() called on a pre 3.0 HAL");
6499 }
6500 return status;
6501}
6502
Eric Laurent83b88082014-06-20 18:31:16 -07006503void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
6504{
6505 Mutex::Autolock _l(mLock);
6506 mTracks.add(record);
6507}
6508
6509void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
6510{
6511 Mutex::Autolock _l(mLock);
6512 destroyTrack_l(record);
6513}
6514
6515void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
6516{
6517 ThreadBase::getAudioPortConfig(config);
6518 config->role = AUDIO_PORT_ROLE_SINK;
6519 config->ext.mix.hw_module = mInput->audioHwDev->handle();
6520 config->ext.mix.usecase.source = mAudioSource;
6521}
Eric Laurent1c333e22014-05-20 10:48:17 -07006522
Eric Laurent81784c32012-11-19 14:55:58 -08006523}; // namespace android