blob: 1ed4e1808bc32e559bcd44e8275684317bda9766 [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"
Andy Hungd330ee42015-04-20 13:23:41 -070059#include "BufferProviders.h"
Eric Laurent81784c32012-11-19 14:55:58 -080060#include "FastMixer.h"
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070061#include "FastCapture.h"
Eric Laurent81784c32012-11-19 14:55:58 -080062#include "ServiceUtilities.h"
63#include "SchedulingPolicyService.h"
64
Eric Laurent81784c32012-11-19 14:55:58 -080065#ifdef ADD_BATTERY_DATA
66#include <media/IMediaPlayerService.h>
67#include <media/IMediaDeathNotifier.h>
68#endif
69
Eric Laurent81784c32012-11-19 14:55:58 -080070#ifdef DEBUG_CPU_USAGE
71#include <cpustats/CentralTendencyStatistics.h>
72#include <cpustats/ThreadCpuUsage.h>
73#endif
74
75// ----------------------------------------------------------------------------
76
77// Note: the following macro is used for extremely verbose logging message. In
78// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
79// 0; but one side effect of this is to turn all LOGV's as well. Some messages
80// are so verbose that we want to suppress them even when we have ALOG_ASSERT
81// turned on. Do not uncomment the #def below unless you really know what you
82// are doing and want to see all of the extremely verbose messages.
83//#define VERY_VERY_VERBOSE_LOGGING
84#ifdef VERY_VERY_VERBOSE_LOGGING
85#define ALOGVV ALOGV
86#else
87#define ALOGVV(a...) do { } while(0)
88#endif
89
Andy Hung6770c6f2015-04-07 13:43:36 -070090// TODO: Move these macro/inlines to a header file.
Glenn Kasten49d00ad2014-07-21 11:22:03 -070091#define max(a, b) ((a) > (b) ? (a) : (b))
Andy Hung6770c6f2015-04-07 13:43:36 -070092template <typename T>
93static inline T min(const T& a, const T& b)
94{
95 return a < b ? a : b;
96}
Glenn Kasten49d00ad2014-07-21 11:22:03 -070097
Andy Hungd330ee42015-04-20 13:23:41 -070098#ifndef ARRAY_SIZE
99#define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
100#endif
101
Eric Laurent81784c32012-11-19 14:55:58 -0800102namespace android {
103
104// retry counts for buffer fill timeout
105// 50 * ~20msecs = 1 second
106static const int8_t kMaxTrackRetries = 50;
107static const int8_t kMaxTrackStartupRetries = 50;
108// allow less retry attempts on direct output thread.
109// direct outputs can be a scarce resource in audio hardware and should
110// be released as quickly as possible.
111static const int8_t kMaxTrackRetriesDirect = 2;
112
113// don't warn about blocked writes or record buffer overflows more often than this
114static const nsecs_t kWarningThrottleNs = seconds(5);
115
116// RecordThread loop sleep time upon application overrun or audio HAL read error
117static const int kRecordThreadSleepUs = 5000;
118
Eric Laurent10351942014-05-08 18:49:52 -0700119// maximum time to wait in sendConfigEvent_l() for a status to be received
120static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800121
122// minimum sleep time for the mixer thread loop when tracks are active but in underrun
123static const uint32_t kMinThreadSleepTimeUs = 5000;
124// maximum divider applied to the active sleep time in the mixer thread loop
125static const uint32_t kMaxThreadSleepTimeShift = 2;
126
Andy Hung09a50072014-02-27 14:30:47 -0800127// minimum normal sink buffer size, expressed in milliseconds rather than frames
128static const uint32_t kMinNormalSinkBufferSizeMs = 20;
129// maximum normal sink buffer size
130static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800131
Eric Laurent972a1732013-09-04 09:42:59 -0700132// Offloaded output thread standby delay: allows track transition without going to standby
133static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
134
Eric Laurent81784c32012-11-19 14:55:58 -0800135// Whether to use fast mixer
136static const enum {
137 FastMixer_Never, // never initialize or use: for debugging only
138 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
139 // normal mixer multiplier is 1
140 FastMixer_Static, // initialize if needed, then use all the time if initialized,
141 // multiplier is calculated based on min & max normal mixer buffer size
142 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
143 // multiplier is calculated based on min & max normal mixer buffer size
144 // FIXME for FastMixer_Dynamic:
145 // Supporting this option will require fixing HALs that can't handle large writes.
146 // For example, one HAL implementation returns an error from a large write,
147 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
148 // We could either fix the HAL implementations, or provide a wrapper that breaks
149 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
150} kUseFastMixer = FastMixer_Static;
151
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700152// Whether to use fast capture
153static const enum {
154 FastCapture_Never, // never initialize or use: for debugging only
155 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
156 FastCapture_Static, // initialize if needed, then use all the time if initialized
157} kUseFastCapture = FastCapture_Static;
158
Eric Laurent81784c32012-11-19 14:55:58 -0800159// Priorities for requestPriority
160static const int kPriorityAudioApp = 2;
161static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700162static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800163
164// IAudioFlinger::createTrack() reports back to client the total size of shared memory area
165// for the track. The client then sub-divides this into smaller buffers for its use.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800166// Currently the client uses N-buffering by default, but doesn't tell us about the value of N.
167// So for now we just assume that client is double-buffered for fast tracks.
168// FIXME It would be better for client to tell AudioFlinger the value of N,
169// so AudioFlinger could allocate the right amount of memory.
Eric Laurent81784c32012-11-19 14:55:58 -0800170// See the client's minBufCount and mNotificationFramesAct calculations for details.
Glenn Kasten03490092014-05-27 12:30:54 -0700171
172// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800173static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800174
Glenn Kasten03490092014-05-27 12:30:54 -0700175// The minimum and maximum allowed values
176static const int kFastTrackMultiplierMin = 1;
177static const int kFastTrackMultiplierMax = 2;
178
179// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
180static int sFastTrackMultiplier = kFastTrackMultiplier;
181
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700182// See Thread::readOnlyHeap().
183// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
184// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
185// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Glenn Kasten9f81de32014-07-27 15:02:23 -0700186static const size_t kRecordThreadReadOnlyHeapSize = 0x2000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700187
Eric Laurent81784c32012-11-19 14:55:58 -0800188// ----------------------------------------------------------------------------
189
Glenn Kasten03490092014-05-27 12:30:54 -0700190static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
191
192static void sFastTrackMultiplierInit()
193{
194 char value[PROPERTY_VALUE_MAX];
195 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
196 char *endptr;
197 unsigned long ul = strtoul(value, &endptr, 0);
198 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
199 sFastTrackMultiplier = (int) ul;
200 }
201 }
202}
203
204// ----------------------------------------------------------------------------
205
Eric Laurent81784c32012-11-19 14:55:58 -0800206#ifdef ADD_BATTERY_DATA
207// To collect the amplifier usage
208static void addBatteryData(uint32_t params) {
209 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
210 if (service == NULL) {
211 // it already logged
212 return;
213 }
214
215 service->addBatteryData(params);
216}
217#endif
218
219
220// ----------------------------------------------------------------------------
221// CPU Stats
222// ----------------------------------------------------------------------------
223
224class CpuStats {
225public:
226 CpuStats();
227 void sample(const String8 &title);
228#ifdef DEBUG_CPU_USAGE
229private:
230 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
231 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
232
233 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
234
235 int mCpuNum; // thread's current CPU number
236 int mCpukHz; // frequency of thread's current CPU in kHz
237#endif
238};
239
240CpuStats::CpuStats()
241#ifdef DEBUG_CPU_USAGE
242 : mCpuNum(-1), mCpukHz(-1)
243#endif
244{
245}
246
Glenn Kasten0f11b512014-01-31 16:18:54 -0800247void CpuStats::sample(const String8 &title
248#ifndef DEBUG_CPU_USAGE
249 __unused
250#endif
251 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800252#ifdef DEBUG_CPU_USAGE
253 // get current thread's delta CPU time in wall clock ns
254 double wcNs;
255 bool valid = mCpuUsage.sampleAndEnable(wcNs);
256
257 // record sample for wall clock statistics
258 if (valid) {
259 mWcStats.sample(wcNs);
260 }
261
262 // get the current CPU number
263 int cpuNum = sched_getcpu();
264
265 // get the current CPU frequency in kHz
266 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
267
268 // check if either CPU number or frequency changed
269 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
270 mCpuNum = cpuNum;
271 mCpukHz = cpukHz;
272 // ignore sample for purposes of cycles
273 valid = false;
274 }
275
276 // if no change in CPU number or frequency, then record sample for cycle statistics
277 if (valid && mCpukHz > 0) {
278 double cycles = wcNs * cpukHz * 0.000001;
279 mHzStats.sample(cycles);
280 }
281
282 unsigned n = mWcStats.n();
283 // mCpuUsage.elapsed() is expensive, so don't call it every loop
284 if ((n & 127) == 1) {
285 long long elapsed = mCpuUsage.elapsed();
286 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
287 double perLoop = elapsed / (double) n;
288 double perLoop100 = perLoop * 0.01;
289 double perLoop1k = perLoop * 0.001;
290 double mean = mWcStats.mean();
291 double stddev = mWcStats.stddev();
292 double minimum = mWcStats.minimum();
293 double maximum = mWcStats.maximum();
294 double meanCycles = mHzStats.mean();
295 double stddevCycles = mHzStats.stddev();
296 double minCycles = mHzStats.minimum();
297 double maxCycles = mHzStats.maximum();
298 mCpuUsage.resetElapsed();
299 mWcStats.reset();
300 mHzStats.reset();
301 ALOGD("CPU usage for %s over past %.1f secs\n"
302 " (%u mixer loops at %.1f mean ms per loop):\n"
303 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
304 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
305 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
306 title.string(),
307 elapsed * .000000001, n, perLoop * .000001,
308 mean * .001,
309 stddev * .001,
310 minimum * .001,
311 maximum * .001,
312 mean / perLoop100,
313 stddev / perLoop100,
314 minimum / perLoop100,
315 maximum / perLoop100,
316 meanCycles / perLoop1k,
317 stddevCycles / perLoop1k,
318 minCycles / perLoop1k,
319 maxCycles / perLoop1k);
320
321 }
322 }
323#endif
324};
325
326// ----------------------------------------------------------------------------
327// ThreadBase
328// ----------------------------------------------------------------------------
329
Glenn Kasten97b7b752014-09-28 13:04:24 -0700330// static
331const char *AudioFlinger::ThreadBase::threadTypeToString(AudioFlinger::ThreadBase::type_t type)
332{
333 switch (type) {
334 case MIXER:
335 return "MIXER";
336 case DIRECT:
337 return "DIRECT";
338 case DUPLICATING:
339 return "DUPLICATING";
340 case RECORD:
341 return "RECORD";
342 case OFFLOAD:
343 return "OFFLOAD";
344 default:
345 return "unknown";
346 }
347}
348
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800349String8 devicesToString(audio_devices_t devices)
350{
351 static const struct mapping {
352 audio_devices_t mDevices;
353 const char * mString;
354 } mappingsOut[] = {
355 AUDIO_DEVICE_OUT_EARPIECE, "EARPIECE",
356 AUDIO_DEVICE_OUT_SPEAKER, "SPEAKER",
357 AUDIO_DEVICE_OUT_WIRED_HEADSET, "WIRED_HEADSET",
358 AUDIO_DEVICE_OUT_WIRED_HEADPHONE, "WIRED_HEADPHONE",
359 AUDIO_DEVICE_OUT_TELEPHONY_TX, "TELEPHONY_TX",
360 AUDIO_DEVICE_NONE, "NONE", // must be last
361 }, mappingsIn[] = {
362 AUDIO_DEVICE_IN_BUILTIN_MIC, "BUILTIN_MIC",
363 AUDIO_DEVICE_IN_WIRED_HEADSET, "WIRED_HEADSET",
364 AUDIO_DEVICE_IN_VOICE_CALL, "VOICE_CALL",
365 AUDIO_DEVICE_IN_REMOTE_SUBMIX, "REMOTE_SUBMIX",
366 AUDIO_DEVICE_NONE, "NONE", // must be last
367 };
368 String8 result;
369 audio_devices_t allDevices = AUDIO_DEVICE_NONE;
370 const mapping *entry;
371 if (devices & AUDIO_DEVICE_BIT_IN) {
372 devices &= ~AUDIO_DEVICE_BIT_IN;
373 entry = mappingsIn;
374 } else {
375 entry = mappingsOut;
376 }
377 for ( ; entry->mDevices != AUDIO_DEVICE_NONE; entry++) {
378 allDevices = (audio_devices_t) (allDevices | entry->mDevices);
379 if (devices & entry->mDevices) {
380 if (!result.isEmpty()) {
381 result.append("|");
382 }
383 result.append(entry->mString);
384 }
385 }
386 if (devices & ~allDevices) {
387 if (!result.isEmpty()) {
388 result.append("|");
389 }
390 result.appendFormat("0x%X", devices & ~allDevices);
391 }
392 if (result.isEmpty()) {
393 result.append(entry->mString);
394 }
395 return result;
396}
397
398String8 inputFlagsToString(audio_input_flags_t flags)
399{
400 static const struct mapping {
401 audio_input_flags_t mFlag;
402 const char * mString;
403 } mappings[] = {
404 AUDIO_INPUT_FLAG_FAST, "FAST",
405 AUDIO_INPUT_FLAG_HW_HOTWORD, "HW_HOTWORD",
406 AUDIO_INPUT_FLAG_NONE, "NONE", // must be last
407 };
408 String8 result;
409 audio_input_flags_t allFlags = AUDIO_INPUT_FLAG_NONE;
410 const mapping *entry;
411 for (entry = mappings; entry->mFlag != AUDIO_INPUT_FLAG_NONE; entry++) {
412 allFlags = (audio_input_flags_t) (allFlags | entry->mFlag);
413 if (flags & entry->mFlag) {
414 if (!result.isEmpty()) {
415 result.append("|");
416 }
417 result.append(entry->mString);
418 }
419 }
420 if (flags & ~allFlags) {
421 if (!result.isEmpty()) {
422 result.append("|");
423 }
424 result.appendFormat("0x%X", flags & ~allFlags);
425 }
426 if (result.isEmpty()) {
427 result.append(entry->mString);
428 }
429 return result;
430}
431
432String8 outputFlagsToString(audio_output_flags_t flags)
Glenn Kasten97b7b752014-09-28 13:04:24 -0700433{
434 static const struct mapping {
435 audio_output_flags_t mFlag;
436 const char * mString;
437 } mappings[] = {
438 AUDIO_OUTPUT_FLAG_DIRECT, "DIRECT",
439 AUDIO_OUTPUT_FLAG_PRIMARY, "PRIMARY",
440 AUDIO_OUTPUT_FLAG_FAST, "FAST",
441 AUDIO_OUTPUT_FLAG_DEEP_BUFFER, "DEEP_BUFFER",
Glenn Kastendfb0e112015-02-18 14:33:39 -0800442 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD, "COMPRESS_OFFLOAD",
Glenn Kasten97b7b752014-09-28 13:04:24 -0700443 AUDIO_OUTPUT_FLAG_NON_BLOCKING, "NON_BLOCKING",
444 AUDIO_OUTPUT_FLAG_HW_AV_SYNC, "HW_AV_SYNC",
445 AUDIO_OUTPUT_FLAG_NONE, "NONE", // must be last
446 };
447 String8 result;
448 audio_output_flags_t allFlags = AUDIO_OUTPUT_FLAG_NONE;
449 const mapping *entry;
450 for (entry = mappings; entry->mFlag != AUDIO_OUTPUT_FLAG_NONE; entry++) {
451 allFlags = (audio_output_flags_t) (allFlags | entry->mFlag);
452 if (flags & entry->mFlag) {
453 if (!result.isEmpty()) {
454 result.append("|");
455 }
456 result.append(entry->mString);
457 }
458 }
459 if (flags & ~allFlags) {
460 if (!result.isEmpty()) {
461 result.append("|");
462 }
463 result.appendFormat("0x%X", flags & ~allFlags);
464 }
465 if (result.isEmpty()) {
466 result.append(entry->mString);
467 }
468 return result;
469}
470
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800471const char *sourceToString(audio_source_t source)
472{
473 switch (source) {
474 case AUDIO_SOURCE_DEFAULT: return "default";
475 case AUDIO_SOURCE_MIC: return "mic";
476 case AUDIO_SOURCE_VOICE_UPLINK: return "voice uplink";
477 case AUDIO_SOURCE_VOICE_DOWNLINK: return "voice downlink";
478 case AUDIO_SOURCE_VOICE_CALL: return "voice call";
479 case AUDIO_SOURCE_CAMCORDER: return "camcorder";
480 case AUDIO_SOURCE_VOICE_RECOGNITION: return "voice recognition";
481 case AUDIO_SOURCE_VOICE_COMMUNICATION: return "voice communication";
482 case AUDIO_SOURCE_REMOTE_SUBMIX: return "remote submix";
483 case AUDIO_SOURCE_FM_TUNER: return "FM tuner";
484 case AUDIO_SOURCE_HOTWORD: return "hotword";
485 default: return "unknown";
486 }
487}
488
Eric Laurent81784c32012-11-19 14:55:58 -0800489AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -0700490 audio_devices_t outDevice, audio_devices_t inDevice, type_t type, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -0800491 : Thread(false /*canCallJava*/),
492 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700493 mAudioFlinger(audioFlinger),
Glenn Kasten70949c42013-08-06 07:40:12 -0700494 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800495 // are set by PlaybackThread::readOutputParameters_l() or
496 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700497 //FIXME: mStandby should be true here. Is this some kind of hack?
Eric Laurent81784c32012-11-19 14:55:58 -0800498 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
499 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
500 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700501 mDeathRecipient(new PMDeathRecipient(this)),
502 mSystemReady(systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -0800503{
Eric Laurent296fb132015-05-01 11:38:42 -0700504 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800505}
506
507AudioFlinger::ThreadBase::~ThreadBase()
508{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700509 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700510 mConfigEvents.clear();
511
Eric Laurent81784c32012-11-19 14:55:58 -0800512 // do not lock the mutex in destructor
513 releaseWakeLock_l();
514 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800515 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800516 binder->unlinkToDeath(mDeathRecipient);
517 }
518}
519
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700520status_t AudioFlinger::ThreadBase::readyToRun()
521{
522 status_t status = initCheck();
523 if (status == NO_ERROR) {
524 ALOGI("AudioFlinger's thread %p ready to run", this);
525 } else {
526 ALOGE("No working audio driver found.");
527 }
528 return status;
529}
530
Eric Laurent81784c32012-11-19 14:55:58 -0800531void AudioFlinger::ThreadBase::exit()
532{
533 ALOGV("ThreadBase::exit");
534 // do any cleanup required for exit to succeed
535 preExit();
536 {
537 // This lock prevents the following race in thread (uniprocessor for illustration):
538 // if (!exitPending()) {
539 // // context switch from here to exit()
540 // // exit() calls requestExit(), what exitPending() observes
541 // // exit() calls signal(), which is dropped since no waiters
542 // // context switch back from exit() to here
543 // mWaitWorkCV.wait(...);
544 // // now thread is hung
545 // }
546 AutoMutex lock(mLock);
547 requestExit();
548 mWaitWorkCV.broadcast();
549 }
550 // When Thread::requestExitAndWait is made virtual and this method is renamed to
551 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
552 requestExitAndWait();
553}
554
555status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
556{
557 status_t status;
558
559 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
560 Mutex::Autolock _l(mLock);
561
Eric Laurent10351942014-05-08 18:49:52 -0700562 return sendSetParameterConfigEvent_l(keyValuePairs);
563}
564
565// sendConfigEvent_l() must be called with ThreadBase::mLock held
566// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
567status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
568{
569 status_t status = NO_ERROR;
570
Eric Laurent72e3f392015-05-20 14:43:50 -0700571 if (event->mRequiresSystemReady && !mSystemReady) {
572 event->mWaitStatus = false;
573 mPendingConfigEvents.add(event);
574 return status;
575 }
Eric Laurent10351942014-05-08 18:49:52 -0700576 mConfigEvents.add(event);
577 ALOGV("sendConfigEvent_l() num events %d event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800578 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700579 mLock.unlock();
580 {
581 Mutex::Autolock _l(event->mLock);
582 while (event->mWaitStatus) {
583 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
584 event->mStatus = TIMED_OUT;
585 event->mWaitStatus = false;
586 }
587 }
588 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800589 }
Eric Laurent10351942014-05-08 18:49:52 -0700590 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800591 return status;
592}
593
Eric Laurent73e26b62015-04-27 16:55:58 -0700594void AudioFlinger::ThreadBase::sendIoConfigEvent(audio_io_config_event event)
Eric Laurent81784c32012-11-19 14:55:58 -0800595{
596 Mutex::Autolock _l(mLock);
Eric Laurent73e26b62015-04-27 16:55:58 -0700597 sendIoConfigEvent_l(event);
Eric Laurent81784c32012-11-19 14:55:58 -0800598}
599
600// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
Eric Laurent73e26b62015-04-27 16:55:58 -0700601void AudioFlinger::ThreadBase::sendIoConfigEvent_l(audio_io_config_event event)
Eric Laurent81784c32012-11-19 14:55:58 -0800602{
Eric Laurent73e26b62015-04-27 16:55:58 -0700603 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event);
Eric Laurent10351942014-05-08 18:49:52 -0700604 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800605}
606
Eric Laurent72e3f392015-05-20 14:43:50 -0700607void AudioFlinger::ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio)
608{
609 Mutex::Autolock _l(mLock);
610 sendPrioConfigEvent_l(pid, tid, prio);
611}
612
Eric Laurent81784c32012-11-19 14:55:58 -0800613// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
614void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
615{
Eric Laurent10351942014-05-08 18:49:52 -0700616 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio);
617 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800618}
619
Eric Laurent10351942014-05-08 18:49:52 -0700620// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
621status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800622{
Eric Laurent10351942014-05-08 18:49:52 -0700623 sp<ConfigEvent> configEvent = (ConfigEvent *)new SetParameterConfigEvent(keyValuePair);
624 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700625}
626
Eric Laurent1c333e22014-05-20 10:48:17 -0700627status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
628 const struct audio_patch *patch,
629 audio_patch_handle_t *handle)
630{
631 Mutex::Autolock _l(mLock);
632 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
633 status_t status = sendConfigEvent_l(configEvent);
634 if (status == NO_ERROR) {
635 CreateAudioPatchConfigEventData *data =
636 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
637 *handle = data->mHandle;
638 }
639 return status;
640}
641
642status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
643 const audio_patch_handle_t handle)
644{
645 Mutex::Autolock _l(mLock);
646 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
647 return sendConfigEvent_l(configEvent);
648}
649
650
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700651// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700652void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700653{
Eric Laurent10351942014-05-08 18:49:52 -0700654 bool configChanged = false;
655
Eric Laurent81784c32012-11-19 14:55:58 -0800656 while (!mConfigEvents.isEmpty()) {
Eric Laurent10351942014-05-08 18:49:52 -0700657 ALOGV("processConfigEvents_l() remaining events %d", mConfigEvents.size());
658 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800659 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700660 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700661 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700662 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
663 // FIXME Need to understand why this has to be done asynchronously
664 int err = requestPriority(data->mPid, data->mTid, data->mPrio,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700665 true /*asynchronous*/);
666 if (err != 0) {
667 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700668 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700669 }
670 } break;
671 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700672 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent73e26b62015-04-27 16:55:58 -0700673 ioConfigChanged(data->mEvent);
Eric Laurent10351942014-05-08 18:49:52 -0700674 } break;
675 case CFG_EVENT_SET_PARAMETER: {
676 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
677 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
678 configChanged = true;
Glenn Kastend5418eb2013-08-14 13:11:06 -0700679 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700680 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700681 case CFG_EVENT_CREATE_AUDIO_PATCH: {
682 CreateAudioPatchConfigEventData *data =
683 (CreateAudioPatchConfigEventData *)event->mData.get();
684 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
685 } break;
686 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
687 ReleaseAudioPatchConfigEventData *data =
688 (ReleaseAudioPatchConfigEventData *)event->mData.get();
689 event->mStatus = releaseAudioPatch_l(data->mHandle);
690 } break;
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700691 default:
Eric Laurent10351942014-05-08 18:49:52 -0700692 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700693 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800694 }
Eric Laurent10351942014-05-08 18:49:52 -0700695 {
696 Mutex::Autolock _l(event->mLock);
697 if (event->mWaitStatus) {
698 event->mWaitStatus = false;
699 event->mCond.signal();
700 }
701 }
702 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
703 }
704
705 if (configChanged) {
706 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800707 }
Eric Laurent81784c32012-11-19 14:55:58 -0800708}
709
Marco Nelissenb2208842014-02-07 14:00:50 -0800710String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
711 String8 s;
712 if (output) {
713 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
714 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
715 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
716 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
717 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
718 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
719 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
720 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
721 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
722 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
723 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
724 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
725 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
726 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
727 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
728 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
729 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
730 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
731 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
732 } else {
733 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
734 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
735 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
736 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
737 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
738 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
739 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
740 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
741 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
742 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
743 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
744 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
745 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
746 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
747 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
748 }
749 int len = s.length();
750 if (s.length() > 2) {
751 char *str = s.lockBuffer(len);
752 s.unlockBuffer(len - 2);
753 }
754 return s;
755}
756
Glenn Kasten0f11b512014-01-31 16:18:54 -0800757void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800758{
759 const size_t SIZE = 256;
760 char buffer[SIZE];
761 String8 result;
762
763 bool locked = AudioFlinger::dumpTryLock(mLock);
764 if (!locked) {
Glenn Kasten97b7b752014-09-28 13:04:24 -0700765 dprintf(fd, "thread %p may be deadlocked\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -0800766 }
767
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800768 dprintf(fd, " Thread name: %s\n", mThreadName);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700769 dprintf(fd, " I/O handle: %d\n", mId);
770 dprintf(fd, " TID: %d\n", getTid());
771 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700772 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700773 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700774 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat));
Elliott Hughes87cebad2014-05-22 10:14:43 -0700775 dprintf(fd, " HAL buffer size: %u bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700776 dprintf(fd, " Channel count: %u\n", mChannelCount);
777 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800778 channelMaskToString(mChannelMask, mType != RECORD).string());
Glenn Kasten97b7b752014-09-28 13:04:24 -0700779 dprintf(fd, " Format: 0x%x (%s)\n", mFormat, formatToString(mFormat));
780 dprintf(fd, " Frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700781 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800782 size_t numConfig = mConfigEvents.size();
783 if (numConfig) {
784 for (size_t i = 0; i < numConfig; i++) {
785 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700786 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800787 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700788 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800789 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700790 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800791 }
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800792 dprintf(fd, " Output device: %#x (%s)\n", mOutDevice, devicesToString(mOutDevice).string());
793 dprintf(fd, " Input device: %#x (%s)\n", mInDevice, devicesToString(mInDevice).string());
794 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, sourceToString(mAudioSource));
Eric Laurent81784c32012-11-19 14:55:58 -0800795
796 if (locked) {
797 mLock.unlock();
798 }
799}
800
801void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
802{
803 const size_t SIZE = 256;
804 char buffer[SIZE];
805 String8 result;
806
Marco Nelissenb2208842014-02-07 14:00:50 -0800807 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000808 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800809 write(fd, buffer, strlen(buffer));
810
Marco Nelissenb2208842014-02-07 14:00:50 -0800811 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800812 sp<EffectChain> chain = mEffectChains[i];
813 if (chain != 0) {
814 chain->dump(fd, args);
815 }
816 }
817}
818
Marco Nelissene14a5d62013-10-03 08:51:24 -0700819void AudioFlinger::ThreadBase::acquireWakeLock(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800820{
821 Mutex::Autolock _l(mLock);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700822 acquireWakeLock_l(uid);
Eric Laurent81784c32012-11-19 14:55:58 -0800823}
824
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100825String16 AudioFlinger::ThreadBase::getWakeLockTag()
826{
827 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -0800828 case MIXER:
829 return String16("AudioMix");
830 case DIRECT:
831 return String16("AudioDirectOut");
832 case DUPLICATING:
833 return String16("AudioDup");
834 case RECORD:
835 return String16("AudioIn");
836 case OFFLOAD:
837 return String16("AudioOffload");
838 default:
839 ALOG_ASSERT(false);
840 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100841 }
842}
843
Marco Nelissene14a5d62013-10-03 08:51:24 -0700844void AudioFlinger::ThreadBase::acquireWakeLock_l(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800845{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800846 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800847 if (mPowerManager != 0) {
848 sp<IBinder> binder = new BBinder();
Marco Nelissene14a5d62013-10-03 08:51:24 -0700849 status_t status;
850 if (uid >= 0) {
Eric Laurent547789d2013-10-04 11:46:55 -0700851 status = mPowerManager->acquireWakeLockWithUid(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700852 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100853 getWakeLockTag(),
Marco Nelissene14a5d62013-10-03 08:51:24 -0700854 String16("media"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700855 uid,
856 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700857 } else {
Eric Laurent547789d2013-10-04 11:46:55 -0700858 status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700859 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100860 getWakeLockTag(),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700861 String16("media"),
862 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700863 }
Eric Laurent81784c32012-11-19 14:55:58 -0800864 if (status == NO_ERROR) {
865 mWakeLockToken = binder;
866 }
Glenn Kastend7dca052015-03-05 16:05:54 -0800867 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Eric Laurent81784c32012-11-19 14:55:58 -0800868 }
869}
870
871void AudioFlinger::ThreadBase::releaseWakeLock()
872{
873 Mutex::Autolock _l(mLock);
874 releaseWakeLock_l();
875}
876
877void AudioFlinger::ThreadBase::releaseWakeLock_l()
878{
879 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800880 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -0800881 if (mPowerManager != 0) {
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700882 mPowerManager->releaseWakeLock(mWakeLockToken, 0,
883 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800884 }
885 mWakeLockToken.clear();
886 }
887}
888
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800889void AudioFlinger::ThreadBase::updateWakeLockUids(const SortedVector<int> &uids) {
890 Mutex::Autolock _l(mLock);
891 updateWakeLockUids_l(uids);
892}
893
894void AudioFlinger::ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -0700895 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800896 // use checkService() to avoid blocking if power service is not up yet
897 sp<IBinder> binder =
898 defaultServiceManager()->checkService(String16("power"));
899 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800900 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800901 } else {
902 mPowerManager = interface_cast<IPowerManager>(binder);
903 binder->linkToDeath(mDeathRecipient);
904 }
905 }
906}
907
908void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<int> &uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800909 getPowerManager_l();
910 if (mWakeLockToken == NULL) {
911 ALOGE("no wake lock to update!");
912 return;
913 }
914 if (mPowerManager != 0) {
915 sp<IBinder> binder = new BBinder();
916 status_t status;
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700917 status = mPowerManager->updateWakeLockUids(mWakeLockToken, uids.size(), uids.array(),
918 true /* FIXME force oneway contrary to .aidl */);
Glenn Kastend7dca052015-03-05 16:05:54 -0800919 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800920 }
921}
922
Eric Laurent81784c32012-11-19 14:55:58 -0800923void AudioFlinger::ThreadBase::clearPowerManager()
924{
925 Mutex::Autolock _l(mLock);
926 releaseWakeLock_l();
927 mPowerManager.clear();
928}
929
Glenn Kasten0f11b512014-01-31 16:18:54 -0800930void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800931{
932 sp<ThreadBase> thread = mThread.promote();
933 if (thread != 0) {
934 thread->clearPowerManager();
935 }
936 ALOGW("power manager service died !!!");
937}
938
939void AudioFlinger::ThreadBase::setEffectSuspended(
940 const effect_uuid_t *type, bool suspend, int sessionId)
941{
942 Mutex::Autolock _l(mLock);
943 setEffectSuspended_l(type, suspend, sessionId);
944}
945
946void AudioFlinger::ThreadBase::setEffectSuspended_l(
947 const effect_uuid_t *type, bool suspend, int sessionId)
948{
949 sp<EffectChain> chain = getEffectChain_l(sessionId);
950 if (chain != 0) {
951 if (type != NULL) {
952 chain->setEffectSuspended_l(type, suspend);
953 } else {
954 chain->setEffectSuspendedAll_l(suspend);
955 }
956 }
957
958 updateSuspendedSessions_l(type, suspend, sessionId);
959}
960
961void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
962{
963 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
964 if (index < 0) {
965 return;
966 }
967
968 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
969 mSuspendedSessions.valueAt(index);
970
971 for (size_t i = 0; i < sessionEffects.size(); i++) {
972 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
973 for (int j = 0; j < desc->mRefCount; j++) {
974 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
975 chain->setEffectSuspendedAll_l(true);
976 } else {
977 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
978 desc->mType.timeLow);
979 chain->setEffectSuspended_l(&desc->mType, true);
980 }
981 }
982 }
983}
984
985void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
986 bool suspend,
987 int sessionId)
988{
989 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
990
991 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
992
993 if (suspend) {
994 if (index >= 0) {
995 sessionEffects = mSuspendedSessions.valueAt(index);
996 } else {
997 mSuspendedSessions.add(sessionId, sessionEffects);
998 }
999 } else {
1000 if (index < 0) {
1001 return;
1002 }
1003 sessionEffects = mSuspendedSessions.valueAt(index);
1004 }
1005
1006
1007 int key = EffectChain::kKeyForSuspendAll;
1008 if (type != NULL) {
1009 key = type->timeLow;
1010 }
1011 index = sessionEffects.indexOfKey(key);
1012
1013 sp<SuspendedSessionDesc> desc;
1014 if (suspend) {
1015 if (index >= 0) {
1016 desc = sessionEffects.valueAt(index);
1017 } else {
1018 desc = new SuspendedSessionDesc();
1019 if (type != NULL) {
1020 desc->mType = *type;
1021 }
1022 sessionEffects.add(key, desc);
1023 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1024 }
1025 desc->mRefCount++;
1026 } else {
1027 if (index < 0) {
1028 return;
1029 }
1030 desc = sessionEffects.valueAt(index);
1031 if (--desc->mRefCount == 0) {
1032 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1033 sessionEffects.removeItemsAt(index);
1034 if (sessionEffects.isEmpty()) {
1035 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1036 sessionId);
1037 mSuspendedSessions.removeItem(sessionId);
1038 }
1039 }
1040 }
1041 if (!sessionEffects.isEmpty()) {
1042 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1043 }
1044}
1045
1046void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1047 bool enabled,
1048 int sessionId)
1049{
1050 Mutex::Autolock _l(mLock);
1051 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1052}
1053
1054void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1055 bool enabled,
1056 int sessionId)
1057{
1058 if (mType != RECORD) {
1059 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1060 // another session. This gives the priority to well behaved effect control panels
1061 // and applications not using global effects.
1062 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1063 // global effects
1064 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
1065 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1066 }
1067 }
1068
1069 sp<EffectChain> chain = getEffectChain_l(sessionId);
1070 if (chain != 0) {
1071 chain->checkSuspendOnEffectEnabled(effect, enabled);
1072 }
1073}
1074
1075// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1076sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1077 const sp<AudioFlinger::Client>& client,
1078 const sp<IEffectClient>& effectClient,
1079 int32_t priority,
1080 int sessionId,
1081 effect_descriptor_t *desc,
1082 int *enabled,
Glenn Kasten9156ef32013-08-06 15:39:08 -07001083 status_t *status)
Eric Laurent81784c32012-11-19 14:55:58 -08001084{
1085 sp<EffectModule> effect;
1086 sp<EffectHandle> handle;
1087 status_t lStatus;
1088 sp<EffectChain> chain;
1089 bool chainCreated = false;
1090 bool effectCreated = false;
1091 bool effectRegistered = false;
1092
1093 lStatus = initCheck();
1094 if (lStatus != NO_ERROR) {
1095 ALOGW("createEffect_l() Audio driver not initialized.");
1096 goto Exit;
1097 }
1098
Andy Hung98ef9782014-03-04 14:46:50 -08001099 // Reject any effect on Direct output threads for now, since the format of
1100 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1101 if (mType == DIRECT) {
1102 ALOGW("createEffect_l() Cannot add effect %s on Direct output type thread %s",
Glenn Kastend7dca052015-03-05 16:05:54 -08001103 desc->name, mThreadName);
Andy Hung98ef9782014-03-04 14:46:50 -08001104 lStatus = BAD_VALUE;
1105 goto Exit;
1106 }
1107
Andy Hung389cfdb2014-08-07 17:49:53 -07001108 // Reject any effect on mixer or duplicating multichannel sinks.
Andy Hung9a592762014-07-21 21:56:01 -07001109 // TODO: fix both format and multichannel issues with effects.
Andy Hung389cfdb2014-08-07 17:49:53 -07001110 if ((mType == MIXER || mType == DUPLICATING) && mChannelCount != FCC_2) {
1111 ALOGW("createEffect_l() Cannot add effect %s for multichannel(%d) %s threads",
1112 desc->name, mChannelCount, mType == MIXER ? "MIXER" : "DUPLICATING");
Andy Hung9a592762014-07-21 21:56:01 -07001113 lStatus = BAD_VALUE;
1114 goto Exit;
1115 }
1116
Eric Laurent5baf2af2013-09-12 17:37:00 -07001117 // Allow global effects only on offloaded and mixer threads
1118 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1119 switch (mType) {
1120 case MIXER:
1121 case OFFLOAD:
1122 break;
1123 case DIRECT:
1124 case DUPLICATING:
1125 case RECORD:
1126 default:
Glenn Kastend7dca052015-03-05 16:05:54 -08001127 ALOGW("createEffect_l() Cannot add global effect %s on thread %s",
1128 desc->name, mThreadName);
Eric Laurent5baf2af2013-09-12 17:37:00 -07001129 lStatus = BAD_VALUE;
1130 goto Exit;
1131 }
Eric Laurent81784c32012-11-19 14:55:58 -08001132 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07001133
Eric Laurent81784c32012-11-19 14:55:58 -08001134 // Only Pre processor effects are allowed on input threads and only on input threads
1135 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
1136 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
1137 desc->name, desc->flags, mType);
1138 lStatus = BAD_VALUE;
1139 goto Exit;
1140 }
1141
1142 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1143
1144 { // scope for mLock
1145 Mutex::Autolock _l(mLock);
1146
1147 // check for existing effect chain with the requested audio session
1148 chain = getEffectChain_l(sessionId);
1149 if (chain == 0) {
1150 // create a new chain for this session
1151 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1152 chain = new EffectChain(this, sessionId);
1153 addEffectChain_l(chain);
1154 chain->setStrategy(getStrategyForSession_l(sessionId));
1155 chainCreated = true;
1156 } else {
1157 effect = chain->getEffectFromDesc_l(desc);
1158 }
1159
1160 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1161
1162 if (effect == 0) {
1163 int id = mAudioFlinger->nextUniqueId();
1164 // Check CPU and memory usage
1165 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
1166 if (lStatus != NO_ERROR) {
1167 goto Exit;
1168 }
1169 effectRegistered = true;
1170 // create a new effect module if none present in the chain
1171 effect = new EffectModule(this, chain, desc, id, sessionId);
1172 lStatus = effect->status();
1173 if (lStatus != NO_ERROR) {
1174 goto Exit;
1175 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07001176 effect->setOffloaded(mType == OFFLOAD, mId);
1177
Eric Laurent81784c32012-11-19 14:55:58 -08001178 lStatus = chain->addEffect_l(effect);
1179 if (lStatus != NO_ERROR) {
1180 goto Exit;
1181 }
1182 effectCreated = true;
1183
1184 effect->setDevice(mOutDevice);
1185 effect->setDevice(mInDevice);
1186 effect->setMode(mAudioFlinger->getMode());
1187 effect->setAudioSource(mAudioSource);
1188 }
1189 // create effect handle and connect it to effect module
1190 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001191 lStatus = handle->initCheck();
1192 if (lStatus == OK) {
1193 lStatus = effect->addHandle(handle.get());
1194 }
Eric Laurent81784c32012-11-19 14:55:58 -08001195 if (enabled != NULL) {
1196 *enabled = (int)effect->isEnabled();
1197 }
1198 }
1199
1200Exit:
1201 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1202 Mutex::Autolock _l(mLock);
1203 if (effectCreated) {
1204 chain->removeEffect_l(effect);
1205 }
1206 if (effectRegistered) {
1207 AudioSystem::unregisterEffect(effect->id());
1208 }
1209 if (chainCreated) {
1210 removeEffectChain_l(chain);
1211 }
1212 handle.clear();
1213 }
1214
Glenn Kasten9156ef32013-08-06 15:39:08 -07001215 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001216 return handle;
1217}
1218
1219sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
1220{
1221 Mutex::Autolock _l(mLock);
1222 return getEffect_l(sessionId, effectId);
1223}
1224
1225sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
1226{
1227 sp<EffectChain> chain = getEffectChain_l(sessionId);
1228 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1229}
1230
1231// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1232// PlaybackThread::mLock held
1233status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1234{
1235 // check for existing effect chain with the requested audio session
1236 int sessionId = effect->sessionId();
1237 sp<EffectChain> chain = getEffectChain_l(sessionId);
1238 bool chainCreated = false;
1239
Eric Laurent5baf2af2013-09-12 17:37:00 -07001240 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
1241 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
1242 this, effect->desc().name, effect->desc().flags);
1243
Eric Laurent81784c32012-11-19 14:55:58 -08001244 if (chain == 0) {
1245 // create a new chain for this session
1246 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1247 chain = new EffectChain(this, sessionId);
1248 addEffectChain_l(chain);
1249 chain->setStrategy(getStrategyForSession_l(sessionId));
1250 chainCreated = true;
1251 }
1252 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1253
1254 if (chain->getEffectFromId_l(effect->id()) != 0) {
1255 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1256 this, effect->desc().name, chain.get());
1257 return BAD_VALUE;
1258 }
1259
Eric Laurent5baf2af2013-09-12 17:37:00 -07001260 effect->setOffloaded(mType == OFFLOAD, mId);
1261
Eric Laurent81784c32012-11-19 14:55:58 -08001262 status_t status = chain->addEffect_l(effect);
1263 if (status != NO_ERROR) {
1264 if (chainCreated) {
1265 removeEffectChain_l(chain);
1266 }
1267 return status;
1268 }
1269
1270 effect->setDevice(mOutDevice);
1271 effect->setDevice(mInDevice);
1272 effect->setMode(mAudioFlinger->getMode());
1273 effect->setAudioSource(mAudioSource);
1274 return NO_ERROR;
1275}
1276
1277void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
1278
1279 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
1280 effect_descriptor_t desc = effect->desc();
1281 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1282 detachAuxEffect_l(effect->id());
1283 }
1284
1285 sp<EffectChain> chain = effect->chain().promote();
1286 if (chain != 0) {
1287 // remove effect chain if removing last effect
1288 if (chain->removeEffect_l(effect) == 0) {
1289 removeEffectChain_l(chain);
1290 }
1291 } else {
1292 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1293 }
1294}
1295
1296void AudioFlinger::ThreadBase::lockEffectChains_l(
1297 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1298{
1299 effectChains = mEffectChains;
1300 for (size_t i = 0; i < mEffectChains.size(); i++) {
1301 mEffectChains[i]->lock();
1302 }
1303}
1304
1305void AudioFlinger::ThreadBase::unlockEffectChains(
1306 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1307{
1308 for (size_t i = 0; i < effectChains.size(); i++) {
1309 effectChains[i]->unlock();
1310 }
1311}
1312
1313sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
1314{
1315 Mutex::Autolock _l(mLock);
1316 return getEffectChain_l(sessionId);
1317}
1318
1319sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const
1320{
1321 size_t size = mEffectChains.size();
1322 for (size_t i = 0; i < size; i++) {
1323 if (mEffectChains[i]->sessionId() == sessionId) {
1324 return mEffectChains[i];
1325 }
1326 }
1327 return 0;
1328}
1329
1330void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1331{
1332 Mutex::Autolock _l(mLock);
1333 size_t size = mEffectChains.size();
1334 for (size_t i = 0; i < size; i++) {
1335 mEffectChains[i]->setMode_l(mode);
1336 }
1337}
1338
Eric Laurent83b88082014-06-20 18:31:16 -07001339void AudioFlinger::ThreadBase::getAudioPortConfig(struct audio_port_config *config)
1340{
1341 config->type = AUDIO_PORT_TYPE_MIX;
1342 config->ext.mix.handle = mId;
1343 config->sample_rate = mSampleRate;
1344 config->format = mFormat;
1345 config->channel_mask = mChannelMask;
1346 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1347 AUDIO_PORT_CONFIG_FORMAT;
1348}
1349
Eric Laurent72e3f392015-05-20 14:43:50 -07001350void AudioFlinger::ThreadBase::systemReady()
1351{
1352 Mutex::Autolock _l(mLock);
1353 if (mSystemReady) {
1354 return;
1355 }
1356 mSystemReady = true;
1357
1358 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1359 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1360 }
1361 mPendingConfigEvents.clear();
1362}
1363
Eric Laurent83b88082014-06-20 18:31:16 -07001364
Eric Laurent81784c32012-11-19 14:55:58 -08001365// ----------------------------------------------------------------------------
1366// Playback
1367// ----------------------------------------------------------------------------
1368
1369AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1370 AudioStreamOut* output,
1371 audio_io_handle_t id,
1372 audio_devices_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07001373 type_t type,
1374 bool systemReady)
1375 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type, systemReady),
Andy Hung2098f272014-02-27 14:00:06 -08001376 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001377 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001378 mMixerBuffer(NULL),
1379 mMixerBufferSize(0),
1380 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1381 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001382 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001383 mEffectBuffer(NULL),
1384 mEffectBufferSize(0),
1385 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1386 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001387 mSuspended(0), mBytesWritten(0),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001388 mActiveTracksGeneration(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001389 // mStreamTypes[] initialized in constructor body
1390 mOutput(output),
1391 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
1392 mMixerStatus(MIXER_IDLE),
1393 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
1394 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001395 mBytesRemaining(0),
1396 mCurrentWriteLength(0),
1397 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001398 mWriteAckSequence(0),
1399 mDrainSequence(0),
Eric Laurentede6c3b2013-09-19 14:37:46 -07001400 mSignalPending(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001401 mScreenState(AudioFlinger::mScreenState),
1402 // index 0 is reserved for normal mixer's submix
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001403 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1),
Eric Laurentd1f69b02014-12-15 14:33:13 -08001404 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001405 // mLatchD, mLatchQ,
1406 mLatchDValid(false), mLatchQValid(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001407{
Glenn Kastend7dca052015-03-05 16:05:54 -08001408 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1409 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001410
1411 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1412 // it would be safer to explicitly pass initial masterVolume/masterMute as
1413 // parameter.
1414 //
1415 // If the HAL we are using has support for master volume or master mute,
1416 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1417 // and the mute set to false).
1418 mMasterVolume = audioFlinger->masterVolume_l();
1419 mMasterMute = audioFlinger->masterMute_l();
1420 if (mOutput && mOutput->audioHwDev) {
1421 if (mOutput->audioHwDev->canSetMasterVolume()) {
1422 mMasterVolume = 1.0;
1423 }
1424
1425 if (mOutput->audioHwDev->canSetMasterMute()) {
1426 mMasterMute = false;
1427 }
1428 }
1429
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001430 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001431
Eric Laurent223fd5c2014-11-11 13:43:36 -08001432 // ++ operator does not compile
Glenn Kasten66e46352014-01-16 17:44:23 -08001433 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001434 stream = (audio_stream_type_t) (stream + 1)) {
1435 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1436 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1437 }
Eric Laurent81784c32012-11-19 14:55:58 -08001438}
1439
1440AudioFlinger::PlaybackThread::~PlaybackThread()
1441{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001442 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001443 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001444 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001445 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001446}
1447
1448void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1449{
1450 dumpInternals(fd, args);
1451 dumpTracks(fd, args);
1452 dumpEffectChains(fd, args);
1453}
1454
Glenn Kasten0f11b512014-01-31 16:18:54 -08001455void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001456{
1457 const size_t SIZE = 256;
1458 char buffer[SIZE];
1459 String8 result;
1460
Marco Nelissenb2208842014-02-07 14:00:50 -08001461 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001462 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1463 const stream_type_t *st = &mStreamTypes[i];
1464 if (i > 0) {
1465 result.appendFormat(", ");
1466 }
1467 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1468 if (st->mute) {
1469 result.append("M");
1470 }
1471 }
1472 result.append("\n");
1473 write(fd, result.string(), result.length());
1474 result.clear();
1475
Eric Laurent81784c32012-11-19 14:55:58 -08001476 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1477 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001478 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001479 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001480
1481 size_t numtracks = mTracks.size();
1482 size_t numactive = mActiveTracks.size();
Elliott Hughes87cebad2014-05-22 10:14:43 -07001483 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001484 size_t numactiveseen = 0;
1485 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07001486 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08001487 Track::appendDumpHeader(result);
1488 for (size_t i = 0; i < numtracks; ++i) {
1489 sp<Track> track = mTracks[i];
1490 if (track != 0) {
1491 bool active = mActiveTracks.indexOf(track) >= 0;
1492 if (active) {
1493 numactiveseen++;
1494 }
1495 track->dump(buffer, SIZE, active);
1496 result.append(buffer);
1497 }
1498 }
1499 } else {
1500 result.append("\n");
1501 }
1502 if (numactiveseen != numactive) {
1503 // some tracks in the active list were not in the tracks list
1504 snprintf(buffer, SIZE, " The following tracks are in the active list but"
1505 " not in the track list\n");
1506 result.append(buffer);
1507 Track::appendDumpHeader(result);
1508 for (size_t i = 0; i < numactive; ++i) {
1509 sp<Track> track = mActiveTracks[i].promote();
1510 if (track != 0 && mTracks.indexOf(track) < 0) {
1511 track->dump(buffer, SIZE, true);
1512 result.append(buffer);
1513 }
1514 }
1515 }
1516
1517 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001518}
1519
1520void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1521{
Glenn Kasten97b7b752014-09-28 13:04:24 -07001522 dprintf(fd, "\nOutput thread %p type %d (%s):\n", this, type(), threadTypeToString(type()));
Glenn Kasten44182c22015-03-05 17:12:23 -08001523
1524 dumpBase(fd, args);
1525
Elliott Hughes87cebad2014-05-22 10:14:43 -07001526 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
1527 dprintf(fd, " Last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1528 dprintf(fd, " Total writes: %d\n", mNumWrites);
1529 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1530 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1531 dprintf(fd, " Suspend count: %d\n", mSuspended);
1532 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1533 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1534 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1535 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001536 AudioStreamOut *output = mOutput;
1537 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
1538 String8 flagsAsString = outputFlagsToString(flags);
1539 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n", output, flags, flagsAsString.string());
Eric Laurent81784c32012-11-19 14:55:58 -08001540}
1541
1542// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001543
1544void AudioFlinger::PlaybackThread::onFirstRef()
1545{
Glenn Kastend7dca052015-03-05 16:05:54 -08001546 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001547}
1548
1549// ThreadBase virtuals
1550void AudioFlinger::PlaybackThread::preExit()
1551{
1552 ALOGV(" preExit()");
1553 // FIXME this is using hard-coded strings but in the future, this functionality will be
1554 // converted to use audio HAL extensions required to support tunneling
1555 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1556}
1557
1558// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1559sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1560 const sp<AudioFlinger::Client>& client,
1561 audio_stream_type_t streamType,
1562 uint32_t sampleRate,
1563 audio_format_t format,
1564 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001565 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001566 const sp<IMemory>& sharedBuffer,
1567 int sessionId,
1568 IAudioFlinger::track_flags_t *flags,
1569 pid_t tid,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001570 int uid,
Eric Laurent81784c32012-11-19 14:55:58 -08001571 status_t *status)
1572{
Glenn Kasten74935e42013-12-19 08:56:45 -08001573 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001574 sp<Track> track;
1575 status_t lStatus;
1576
1577 bool isTimed = (*flags & IAudioFlinger::TRACK_TIMED) != 0;
1578
1579 // client expresses a preference for FAST, but we get the final say
1580 if (*flags & IAudioFlinger::TRACK_FAST) {
1581 if (
1582 // not timed
1583 (!isTimed) &&
1584 // either of these use cases:
1585 (
1586 // use case 1: shared buffer with any frame count
1587 (
1588 (sharedBuffer != 0)
1589 ) ||
Glenn Kasten1dfe2f92015-03-09 12:03:14 -07001590 // use case 2: frame count is default or at least as large as HAL
Eric Laurent81784c32012-11-19 14:55:58 -08001591 (
Glenn Kasten1dfe2f92015-03-09 12:03:14 -07001592 // we formerly checked for a callback handler (non-0 tid),
1593 // but that is no longer required for TRANSFER_OBTAIN mode
Eric Laurent81784c32012-11-19 14:55:58 -08001594 ((frameCount == 0) ||
Glenn Kastenb5fed682013-12-03 09:06:43 -08001595 (frameCount >= mFrameCount))
Eric Laurent81784c32012-11-19 14:55:58 -08001596 )
1597 ) &&
1598 // PCM data
1599 audio_is_linear_pcm(format) &&
Andy Hung9a592762014-07-21 21:56:01 -07001600 // identical channel mask to sink, or mono in and stereo sink
1601 (channelMask == mChannelMask ||
1602 (channelMask == AUDIO_CHANNEL_OUT_MONO &&
1603 mChannelMask == AUDIO_CHANNEL_OUT_STEREO)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001604 // hardware sample rate
1605 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001606 // normal mixer has an associated fast mixer
1607 hasFastMixer() &&
1608 // there are sufficient fast track slots available
1609 (mFastTrackAvailMask != 0)
1610 // FIXME test that MixerThread for this fast track has a capable output HAL
1611 // FIXME add a permission test also?
1612 ) {
1613 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1614 if (frameCount == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001615 // read the fast track multiplier property the first time it is needed
1616 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1617 if (ok != 0) {
1618 ALOGE("%s pthread_once failed: %d", __func__, ok);
1619 }
1620 frameCount = mFrameCount * sFastTrackMultiplier;
Eric Laurent81784c32012-11-19 14:55:58 -08001621 }
1622 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
1623 frameCount, mFrameCount);
1624 } else {
1625 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
Andy Hung6146c082014-03-18 11:56:15 -07001626 "mFrameCount=%d format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
1627 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001628 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Andy Hung6146c082014-03-18 11:56:15 -07001629 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001630 audio_is_linear_pcm(format),
1631 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
1632 *flags &= ~IAudioFlinger::TRACK_FAST;
Andy Hung0e48d252015-01-26 11:43:15 -08001633 }
1634 }
1635 // For normal PCM streaming tracks, update minimum frame count.
1636 // For compatibility with AudioTrack calculation, buffer depth is forced
1637 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1638 // This is probably too conservative, but legacy application code may depend on it.
1639 // If you change this calculation, also review the start threshold which is related.
1640 if (!(*flags & IAudioFlinger::TRACK_FAST)
1641 && audio_is_linear_pcm(format) && sharedBuffer == 0) {
Andy Hung8edb8dc2015-03-26 19:13:55 -07001642 // this must match AudioTrack.cpp calculateMinFrameCount().
1643 // TODO: Move to a common library
Eric Laurent81784c32012-11-19 14:55:58 -08001644 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1645 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1646 if (minBufCount < 2) {
1647 minBufCount = 2;
1648 }
Andy Hung8edb8dc2015-03-26 19:13:55 -07001649 // For normal mixing tracks, if speed is > 1.0f (normal), AudioTrack
1650 // or the client should compute and pass in a larger buffer request.
Andy Hung0e48d252015-01-26 11:43:15 -08001651 size_t minFrameCount =
Andy Hung8edb8dc2015-03-26 19:13:55 -07001652 minBufCount * sourceFramesNeededWithTimestretch(
1653 sampleRate, mNormalFrameCount,
1654 mSampleRate, AUDIO_TIMESTRETCH_SPEED_NORMAL /*speed*/);
Andy Hung0e48d252015-01-26 11:43:15 -08001655 if (frameCount < minFrameCount) { // including frameCount == 0
Eric Laurent81784c32012-11-19 14:55:58 -08001656 frameCount = minFrameCount;
1657 }
Eric Laurent81784c32012-11-19 14:55:58 -08001658 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001659 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001660
Glenn Kastenc3df8382014-03-13 15:05:25 -07001661 switch (mType) {
1662
1663 case DIRECT:
Glenn Kasten993fa062014-05-02 11:14:34 -07001664 if (audio_is_linear_pcm(format)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001665 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001666 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1667 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001668 sampleRate, format, channelMask, mOutput, mFormat);
1669 lStatus = BAD_VALUE;
1670 goto Exit;
1671 }
1672 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001673 break;
1674
1675 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001676 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001677 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1678 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001679 sampleRate, format, channelMask, mOutput, mFormat);
1680 lStatus = BAD_VALUE;
1681 goto Exit;
1682 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001683 break;
1684
1685 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07001686 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001687 ALOGE("createTrack_l() Bad parameter: format %#x \""
1688 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001689 format, mOutput, mFormat);
1690 lStatus = BAD_VALUE;
1691 goto Exit;
1692 }
Andy Hungcd044842014-08-07 11:04:34 -07001693 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08001694 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1695 lStatus = BAD_VALUE;
1696 goto Exit;
1697 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001698 break;
1699
Eric Laurent81784c32012-11-19 14:55:58 -08001700 }
1701
1702 lStatus = initCheck();
1703 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07001704 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08001705 goto Exit;
1706 }
1707
1708 { // scope for mLock
1709 Mutex::Autolock _l(mLock);
1710
1711 // all tracks in same audio session must share the same routing strategy otherwise
1712 // conflicts will happen when tracks are moved from one output to another by audio policy
1713 // manager
1714 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1715 for (size_t i = 0; i < mTracks.size(); ++i) {
1716 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07001717 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001718 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1719 if (sessionId == t->sessionId() && strategy != actual) {
1720 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1721 strategy, actual);
1722 lStatus = BAD_VALUE;
1723 goto Exit;
1724 }
1725 }
1726 }
1727
1728 if (!isTimed) {
1729 track = new Track(this, client, streamType, sampleRate, format,
Eric Laurent83b88082014-06-20 18:31:16 -07001730 channelMask, frameCount, NULL, sharedBuffer,
1731 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08001732 } else {
1733 track = TimedTrack::create(this, client, streamType, sampleRate, format,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001734 channelMask, frameCount, sharedBuffer, sessionId, uid);
Eric Laurent81784c32012-11-19 14:55:58 -08001735 }
Glenn Kasten03003332013-08-06 15:40:54 -07001736
1737 // new Track always returns non-NULL,
1738 // but TimedTrack::create() is a factory that could fail by returning NULL
1739 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
1740 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08001741 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001742 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08001743 goto Exit;
1744 }
1745 mTracks.add(track);
1746
1747 sp<EffectChain> chain = getEffectChain_l(sessionId);
1748 if (chain != 0) {
1749 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1750 track->setMainBuffer(chain->inBuffer());
1751 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1752 chain->incTrackCnt();
1753 }
1754
1755 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1756 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1757 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1758 // so ask activity manager to do this on our behalf
1759 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1760 }
1761 }
1762
1763 lStatus = NO_ERROR;
1764
1765Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001766 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001767 return track;
1768}
1769
1770uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1771{
1772 return latency;
1773}
1774
1775uint32_t AudioFlinger::PlaybackThread::latency() const
1776{
1777 Mutex::Autolock _l(mLock);
1778 return latency_l();
1779}
1780uint32_t AudioFlinger::PlaybackThread::latency_l() const
1781{
1782 if (initCheck() == NO_ERROR) {
1783 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
1784 } else {
1785 return 0;
1786 }
1787}
1788
1789void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1790{
1791 Mutex::Autolock _l(mLock);
1792 // Don't apply master volume in SW if our HAL can do it for us.
1793 if (mOutput && mOutput->audioHwDev &&
1794 mOutput->audioHwDev->canSetMasterVolume()) {
1795 mMasterVolume = 1.0;
1796 } else {
1797 mMasterVolume = value;
1798 }
1799}
1800
1801void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1802{
1803 Mutex::Autolock _l(mLock);
1804 // Don't apply master mute in SW if our HAL can do it for us.
1805 if (mOutput && mOutput->audioHwDev &&
1806 mOutput->audioHwDev->canSetMasterMute()) {
1807 mMasterMute = false;
1808 } else {
1809 mMasterMute = muted;
1810 }
1811}
1812
1813void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
1814{
1815 Mutex::Autolock _l(mLock);
1816 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001817 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001818}
1819
1820void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
1821{
1822 Mutex::Autolock _l(mLock);
1823 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001824 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001825}
1826
1827float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
1828{
1829 Mutex::Autolock _l(mLock);
1830 return mStreamTypes[stream].volume;
1831}
1832
1833// addTrack_l() must be called with ThreadBase::mLock held
1834status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1835{
1836 status_t status = ALREADY_EXISTS;
1837
1838 // set retry count for buffer fill
1839 track->mRetryCount = kMaxTrackStartupRetries;
1840 if (mActiveTracks.indexOf(track) < 0) {
1841 // the track is newly added, make sure it fills up all its
1842 // buffers before playing. This is to ensure the client will
1843 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07001844 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001845 TrackBase::track_state state = track->mState;
1846 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08001847 status = AudioSystem::startOutput(mId, track->streamType(),
1848 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001849 mLock.lock();
1850 // abort track was stopped/paused while we released the lock
1851 if (state != track->mState) {
1852 if (status == NO_ERROR) {
1853 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08001854 AudioSystem::stopOutput(mId, track->streamType(),
1855 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001856 mLock.lock();
1857 }
1858 return INVALID_OPERATION;
1859 }
1860 // abort if start is rejected by audio policy manager
1861 if (status != NO_ERROR) {
1862 return PERMISSION_DENIED;
1863 }
1864#ifdef ADD_BATTERY_DATA
1865 // to track the speaker usage
1866 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
1867#endif
1868 }
1869
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001870 track->mFillingUpStatus = track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent81784c32012-11-19 14:55:58 -08001871 track->mResetDone = false;
1872 track->mPresentationCompleteFrames = 0;
1873 mActiveTracks.add(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001874 mWakeLockUids.add(track->uid());
1875 mActiveTracksGeneration++;
Eric Laurentfd477972013-10-25 18:10:40 -07001876 mLatestActiveTrack = track;
Eric Laurentd0107bc2013-06-11 14:38:48 -07001877 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1878 if (chain != 0) {
1879 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
1880 track->sessionId());
1881 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08001882 }
1883
1884 status = NO_ERROR;
1885 }
1886
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08001887 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001888 return status;
1889}
1890
Eric Laurentbfb1b832013-01-07 09:53:42 -08001891bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08001892{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001893 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08001894 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001895 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
1896 track->mState = TrackBase::STOPPED;
1897 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08001898 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07001899 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001900 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08001901 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001902
1903 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08001904}
1905
1906void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1907{
1908 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
1909 mTracks.remove(track);
1910 deleteTrackName_l(track->name());
1911 // redundant as track is about to be destroyed, for dumpsys only
1912 track->mName = -1;
1913 if (track->isFastTrack()) {
1914 int index = track->mFastIndex;
1915 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
1916 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1917 mFastTrackAvailMask |= 1 << index;
1918 // redundant as track is about to be destroyed, for dumpsys only
1919 track->mFastIndex = -1;
1920 }
1921 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1922 if (chain != 0) {
1923 chain->decTrackCnt();
1924 }
1925}
1926
Eric Laurentede6c3b2013-09-19 14:37:46 -07001927void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001928{
1929 // Thread could be blocked waiting for async
1930 // so signal it to handle state changes immediately
1931 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1932 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1933 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001934 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001935}
1936
Eric Laurent81784c32012-11-19 14:55:58 -08001937String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1938{
Eric Laurent81784c32012-11-19 14:55:58 -08001939 Mutex::Autolock _l(mLock);
1940 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07001941 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08001942 }
1943
Glenn Kastend8ea6992013-07-16 14:17:15 -07001944 char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
1945 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08001946 free(s);
1947 return out_s8;
1948}
1949
Eric Laurent73e26b62015-04-27 16:55:58 -07001950void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event) {
1951 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
1952 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08001953
Eric Laurent73e26b62015-04-27 16:55:58 -07001954 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08001955
1956 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07001957 case AUDIO_OUTPUT_OPENED:
1958 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07001959 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07001960 desc->mChannelMask = mChannelMask;
1961 desc->mSamplingRate = mSampleRate;
1962 desc->mFormat = mFormat;
1963 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08001964 // AudioFlinger::frameCount(audio_io_handle_t)
Eric Laurent73e26b62015-04-27 16:55:58 -07001965 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001966 break;
1967
Eric Laurent73e26b62015-04-27 16:55:58 -07001968 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08001969 default:
1970 break;
1971 }
Eric Laurent73e26b62015-04-27 16:55:58 -07001972 mAudioFlinger->ioConfigChanged(event, desc);
Eric Laurent81784c32012-11-19 14:55:58 -08001973}
1974
Eric Laurentbfb1b832013-01-07 09:53:42 -08001975void AudioFlinger::PlaybackThread::writeCallback()
1976{
1977 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001978 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001979}
1980
1981void AudioFlinger::PlaybackThread::drainCallback()
1982{
1983 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001984 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001985}
1986
Eric Laurent3b4529e2013-09-05 18:09:19 -07001987void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001988{
1989 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001990 // reject out of sequence requests
1991 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
1992 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001993 mWaitWorkCV.signal();
1994 }
1995}
1996
Eric Laurent3b4529e2013-09-05 18:09:19 -07001997void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001998{
1999 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002000 // reject out of sequence requests
2001 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
2002 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002003 mWaitWorkCV.signal();
2004 }
2005}
2006
2007// static
2008int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
Glenn Kasten0f11b512014-01-31 16:18:54 -08002009 void *param __unused,
Eric Laurentbfb1b832013-01-07 09:53:42 -08002010 void *cookie)
2011{
2012 AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
2013 ALOGV("asyncCallback() event %d", event);
2014 switch (event) {
2015 case STREAM_CBK_EVENT_WRITE_READY:
2016 me->writeCallback();
2017 break;
2018 case STREAM_CBK_EVENT_DRAIN_READY:
2019 me->drainCallback();
2020 break;
2021 default:
2022 ALOGW("asyncCallback() unknown event %d", event);
2023 break;
2024 }
2025 return 0;
2026}
2027
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002028void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002029{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002030 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Eric Laurent81784c32012-11-19 14:55:58 -08002031 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
2032 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002033 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002034 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002035 }
Andy Hung9a592762014-07-21 21:56:01 -07002036 if ((mType == MIXER || mType == DUPLICATING)
2037 && !isValidPcmSinkChannelMask(mChannelMask)) {
2038 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2039 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002040 }
Andy Hunge5412692014-05-16 11:25:07 -07002041 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Andy Hung463be252014-07-10 16:56:07 -07002042 mHALFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
2043 mFormat = mHALFormat;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002044 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002045 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002046 }
Andy Hung6146c082014-03-18 11:56:15 -07002047 if ((mType == MIXER || mType == DUPLICATING)
2048 && !isValidPcmSinkFormat(mFormat)) {
2049 LOG_FATAL("HAL format %#x not supported for mixed output",
2050 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002051 }
Phil Burk062e67a2015-02-11 13:40:50 -08002052 mFrameSize = mOutput->getFrameSize();
Glenn Kasten70949c42013-08-06 07:40:12 -07002053 mBufferSize = mOutput->stream->common.get_buffer_size(&mOutput->stream->common);
2054 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002055 if (mFrameCount & 15) {
2056 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
2057 mFrameCount);
2058 }
2059
Eric Laurentbfb1b832013-01-07 09:53:42 -08002060 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
2061 (mOutput->stream->set_callback != NULL)) {
2062 if (mOutput->stream->set_callback(mOutput->stream,
2063 AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
2064 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002065 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002066 }
2067 }
2068
Eric Laurentd1f69b02014-12-15 14:33:13 -08002069 mHwSupportsPause = false;
2070 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
2071 if (mOutput->stream->pause != NULL) {
2072 if (mOutput->stream->resume != NULL) {
2073 mHwSupportsPause = true;
2074 } else {
2075 ALOGW("direct output implements pause but not resume");
2076 }
2077 } else if (mOutput->stream->resume != NULL) {
2078 ALOGW("direct output implements resume but not pause");
2079 }
2080 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002081 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2082 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2083 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002084
Andy Hungfbfc3952015-01-15 13:33:51 -08002085 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2086 // For best precision, we use float instead of the associated output
2087 // device format (typically PCM 16 bit).
2088
2089 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2090 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2091 mBufferSize = mFrameSize * mFrameCount;
2092
2093 // TODO: We currently use the associated output device channel mask and sample rate.
2094 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2095 // (if a valid mask) to avoid premature downmix.
2096 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2097 // instead of the output device sample rate to avoid loss of high frequency information.
2098 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2099 }
2100
Andy Hung09a50072014-02-27 14:30:47 -08002101 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002102 double multiplier = 1.0;
2103 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2104 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002105 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2106 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Eric Laurent81784c32012-11-19 14:55:58 -08002107 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2108 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2109 maxNormalFrameCount = maxNormalFrameCount & ~15;
2110 if (maxNormalFrameCount < minNormalFrameCount) {
2111 maxNormalFrameCount = minNormalFrameCount;
2112 }
2113 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2114 if (multiplier <= 1.0) {
2115 multiplier = 1.0;
2116 } else if (multiplier <= 2.0) {
2117 if (2 * mFrameCount <= maxNormalFrameCount) {
2118 multiplier = 2.0;
2119 } else {
2120 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2121 }
2122 } else {
2123 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
Andy Hung09a50072014-02-27 14:30:47 -08002124 // 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 -08002125 // track, but we sometimes have to do this to satisfy the maximum frame count
2126 // constraint)
2127 // FIXME this rounding up should not be done if no HAL SRC
2128 uint32_t truncMult = (uint32_t) multiplier;
2129 if ((truncMult & 1)) {
2130 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
2131 ++truncMult;
2132 }
2133 }
2134 multiplier = (double) truncMult;
2135 }
2136 }
2137 mNormalFrameCount = multiplier * mFrameCount;
2138 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002139 if (mType == MIXER || mType == DUPLICATING) {
2140 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2141 }
Andy Hung09a50072014-02-27 14:30:47 -08002142 ALOGI("HAL output buffer size %u frames, normal sink buffer size %u frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002143 mNormalFrameCount);
2144
Andy Hung010a1a12014-03-13 13:57:33 -07002145 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2146 // Originally this was int16_t[] array, need to remove legacy implications.
2147 free(mSinkBuffer);
2148 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002149 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2150 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2151 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002152 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002153
Andy Hung69aed5f2014-02-25 17:24:40 -08002154 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2155 // drives the output.
2156 free(mMixerBuffer);
2157 mMixerBuffer = NULL;
2158 if (mMixerBufferEnabled) {
2159 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2160 mMixerBufferSize = mNormalFrameCount * mChannelCount
2161 * audio_bytes_per_sample(mMixerBufferFormat);
2162 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2163 }
Andy Hung98ef9782014-03-04 14:46:50 -08002164 free(mEffectBuffer);
2165 mEffectBuffer = NULL;
2166 if (mEffectBufferEnabled) {
2167 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
2168 mEffectBufferSize = mNormalFrameCount * mChannelCount
2169 * audio_bytes_per_sample(mEffectBufferFormat);
2170 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2171 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002172
Eric Laurent81784c32012-11-19 14:55:58 -08002173 // force reconfiguration of effect chains and engines to take new buffer size and audio
2174 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002175 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002176 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2177 // matter.
2178 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2179 Vector< sp<EffectChain> > effectChains = mEffectChains;
2180 for (size_t i = 0; i < effectChains.size(); i ++) {
2181 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2182 }
2183}
2184
2185
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002186status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002187{
2188 if (halFrames == NULL || dspFrames == NULL) {
2189 return BAD_VALUE;
2190 }
2191 Mutex::Autolock _l(mLock);
2192 if (initCheck() != NO_ERROR) {
2193 return INVALID_OPERATION;
2194 }
2195 size_t framesWritten = mBytesWritten / mFrameSize;
2196 *halFrames = framesWritten;
2197
2198 if (isSuspended()) {
2199 // return an estimation of rendered frames when the output is suspended
2200 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
2201 *dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0;
2202 return NO_ERROR;
2203 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002204 status_t status;
2205 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002206 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002207 *dspFrames = (size_t)frames;
2208 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002209 }
2210}
2211
2212uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
2213{
2214 Mutex::Autolock _l(mLock);
2215 uint32_t result = 0;
2216 if (getEffectChain_l(sessionId) != 0) {
2217 result = EFFECT_SESSION;
2218 }
2219
2220 for (size_t i = 0; i < mTracks.size(); ++i) {
2221 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002222 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002223 result |= TRACK_SESSION;
2224 break;
2225 }
2226 }
2227
2228 return result;
2229}
2230
2231uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
2232{
2233 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2234 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2235 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2236 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2237 }
2238 for (size_t i = 0; i < mTracks.size(); i++) {
2239 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002240 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002241 return AudioSystem::getStrategyForStream(track->streamType());
2242 }
2243 }
2244 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2245}
2246
2247
Phil Burk062e67a2015-02-11 13:40:50 -08002248AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002249{
2250 Mutex::Autolock _l(mLock);
2251 return mOutput;
2252}
2253
Phil Burk062e67a2015-02-11 13:40:50 -08002254AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002255{
2256 Mutex::Autolock _l(mLock);
2257 AudioStreamOut *output = mOutput;
2258 mOutput = NULL;
2259 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2260 // must push a NULL and wait for ack
2261 mOutputSink.clear();
2262 mPipeSink.clear();
2263 mNormalSink.clear();
2264 return output;
2265}
2266
2267// this method must always be called either with ThreadBase mLock held or inside the thread loop
2268audio_stream_t* AudioFlinger::PlaybackThread::stream() const
2269{
2270 if (mOutput == NULL) {
2271 return NULL;
2272 }
2273 return &mOutput->stream->common;
2274}
2275
2276uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2277{
2278 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2279}
2280
2281status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2282{
2283 if (!isValidSyncEvent(event)) {
2284 return BAD_VALUE;
2285 }
2286
2287 Mutex::Autolock _l(mLock);
2288
2289 for (size_t i = 0; i < mTracks.size(); ++i) {
2290 sp<Track> track = mTracks[i];
2291 if (event->triggerSession() == track->sessionId()) {
2292 (void) track->setSyncEvent(event);
2293 return NO_ERROR;
2294 }
2295 }
2296
2297 return NAME_NOT_FOUND;
2298}
2299
2300bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2301{
2302 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2303}
2304
2305void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2306 const Vector< sp<Track> >& tracksToRemove)
2307{
2308 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002309 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002310 for (size_t i = 0 ; i < count ; i++) {
2311 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002312 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002313 AudioSystem::stopOutput(mId, track->streamType(),
2314 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002315#ifdef ADD_BATTERY_DATA
2316 // to track the speaker usage
2317 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2318#endif
2319 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002320 AudioSystem::releaseOutput(mId, track->streamType(),
2321 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002322 }
Eric Laurent81784c32012-11-19 14:55:58 -08002323 }
2324 }
2325 }
Eric Laurent81784c32012-11-19 14:55:58 -08002326}
2327
2328void AudioFlinger::PlaybackThread::checkSilentMode_l()
2329{
2330 if (!mMasterMute) {
2331 char value[PROPERTY_VALUE_MAX];
2332 if (property_get("ro.audio.silent", value, "0") > 0) {
2333 char *endptr;
2334 unsigned long ul = strtoul(value, &endptr, 0);
2335 if (*endptr == '\0' && ul != 0) {
2336 ALOGD("Silence is golden");
2337 // The setprop command will not allow a property to be changed after
2338 // the first time it is set, so we don't have to worry about un-muting.
2339 setMasterMute_l(true);
2340 }
2341 }
2342 }
2343}
2344
2345// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002346ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002347{
2348 // FIXME rewrite to reduce number of system calls
2349 mLastWriteTime = systemTime();
2350 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002351 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002352 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002353
2354 // If an NBAIO sink is present, use it to write the normal mixer's submix
2355 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002356
Andy Hung010a1a12014-03-13 13:57:33 -07002357 const size_t count = mBytesRemaining / mFrameSize;
2358
Simon Wilson2d590962012-11-29 15:18:50 -08002359 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002360 // update the setpoint when AudioFlinger::mScreenState changes
2361 uint32_t screenState = AudioFlinger::mScreenState;
2362 if (screenState != mScreenState) {
2363 mScreenState = screenState;
2364 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2365 if (pipe != NULL) {
2366 pipe->setAvgFrames((mScreenState & 1) ?
2367 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2368 }
2369 }
Andy Hung010a1a12014-03-13 13:57:33 -07002370 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002371 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002372 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002373 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002374 } else {
2375 bytesWritten = framesWritten;
2376 }
Glenn Kastenefaa7ab2014-08-20 08:48:54 -07002377 mLatchDValid = false;
Glenn Kasten767094d2013-08-23 13:51:43 -07002378 status_t status = mNormalSink->getTimestamp(mLatchD.mTimestamp);
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002379 if (status == NO_ERROR) {
2380 size_t totalFramesWritten = mNormalSink->framesWritten();
2381 if (totalFramesWritten >= mLatchD.mTimestamp.mPosition) {
2382 mLatchD.mUnpresentedFrames = totalFramesWritten - mLatchD.mTimestamp.mPosition;
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002383 // mLatchD.mFramesReleased is set immediately before D is clocked into Q
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002384 mLatchDValid = true;
2385 }
2386 }
Eric Laurent81784c32012-11-19 14:55:58 -08002387 // otherwise use the HAL / AudioStreamOut directly
2388 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002389 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002390
Eric Laurentbfb1b832013-01-07 09:53:42 -08002391 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002392 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2393 mWriteAckSequence += 2;
2394 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002395 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002396 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002397 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002398 // FIXME We should have an implementation of timestamps for direct output threads.
2399 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002400 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002401 if (mUseAsyncWrite &&
2402 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2403 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002404 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002405 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002406 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002407 }
Eric Laurent81784c32012-11-19 14:55:58 -08002408 }
2409
Eric Laurent81784c32012-11-19 14:55:58 -08002410 mNumWrites++;
2411 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002412 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002413 return bytesWritten;
2414}
2415
2416void AudioFlinger::PlaybackThread::threadLoop_drain()
2417{
2418 if (mOutput->stream->drain) {
2419 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2420 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002421 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2422 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002423 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002424 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002425 }
2426 mOutput->stream->drain(mOutput->stream,
2427 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
2428 : AUDIO_DRAIN_ALL);
2429 }
2430}
2431
2432void AudioFlinger::PlaybackThread::threadLoop_exit()
2433{
Eric Laurent275e8e92014-11-30 15:14:47 -08002434 {
2435 Mutex::Autolock _l(mLock);
2436 for (size_t i = 0; i < mTracks.size(); i++) {
2437 sp<Track> track = mTracks[i];
2438 track->invalidate();
2439 }
2440 }
Eric Laurent81784c32012-11-19 14:55:58 -08002441}
2442
2443/*
2444The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002445 - mSinkBufferSize from frame count * frame size
Eric Laurent81784c32012-11-19 14:55:58 -08002446 - activeSleepTime from activeSleepTimeUs()
2447 - idleSleepTime from idleSleepTimeUs()
2448 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
2449 - maxPeriod from frame count and sample rate (MIXER only)
2450
2451The parameters that affect these derived values are:
2452 - frame count
2453 - frame size
2454 - sample rate
2455 - device type: A2DP or not
2456 - device latency
2457 - format: PCM or not
2458 - active sleep time
2459 - idle sleep time
2460*/
2461
2462void AudioFlinger::PlaybackThread::cacheParameters_l()
2463{
Andy Hung25c2dac2014-02-27 14:56:00 -08002464 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002465 activeSleepTime = activeSleepTimeUs();
2466 idleSleepTime = idleSleepTimeUs();
2467}
2468
2469void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2470{
Glenn Kasten7c027242012-12-26 14:43:16 -08002471 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurent81784c32012-11-19 14:55:58 -08002472 this, streamType, mTracks.size());
2473 Mutex::Autolock _l(mLock);
2474
2475 size_t size = mTracks.size();
2476 for (size_t i = 0; i < size; i++) {
2477 sp<Track> t = mTracks[i];
2478 if (t->streamType() == streamType) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002479 t->invalidate();
Eric Laurent81784c32012-11-19 14:55:58 -08002480 }
2481 }
2482}
2483
2484status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2485{
2486 int session = chain->sessionId();
Andy Hung010a1a12014-03-13 13:57:33 -07002487 int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled
2488 ? mEffectBuffer : mSinkBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002489 bool ownsBuffer = false;
2490
2491 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
2492 if (session > 0) {
2493 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002494 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002495 if (mType != DIRECT) {
2496 size_t numSamples = mNormalFrameCount * mChannelCount;
2497 buffer = new int16_t[numSamples];
2498 memset(buffer, 0, numSamples * sizeof(int16_t));
2499 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2500 ownsBuffer = true;
2501 }
2502
2503 // Attach all tracks with same session ID to this chain.
2504 for (size_t i = 0; i < mTracks.size(); ++i) {
2505 sp<Track> track = mTracks[i];
2506 if (session == track->sessionId()) {
2507 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2508 buffer);
2509 track->setMainBuffer(buffer);
2510 chain->incTrackCnt();
2511 }
2512 }
2513
2514 // indicate all active tracks in the chain
2515 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2516 sp<Track> track = mActiveTracks[i].promote();
2517 if (track == 0) {
2518 continue;
2519 }
2520 if (session == track->sessionId()) {
2521 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2522 chain->incActiveTrackCnt();
2523 }
2524 }
2525 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002526 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08002527 chain->setInBuffer(buffer, ownsBuffer);
Andy Hung010a1a12014-03-13 13:57:33 -07002528 chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled
2529 ? mEffectBuffer : mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002530 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
2531 // chains list in order to be processed last as it contains output stage effects
2532 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2533 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
2534 // after track specific effects and before output stage
2535 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
2536 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
2537 // Effect chain for other sessions are inserted at beginning of effect
2538 // chains list to be processed before output mix effects. Relative order between other
2539 // sessions is not important
2540 size_t size = mEffectChains.size();
2541 size_t i = 0;
2542 for (i = 0; i < size; i++) {
2543 if (mEffectChains[i]->sessionId() < session) {
2544 break;
2545 }
2546 }
2547 mEffectChains.insertAt(chain, i);
2548 checkSuspendOnAddEffectChain_l(chain);
2549
2550 return NO_ERROR;
2551}
2552
2553size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2554{
2555 int session = chain->sessionId();
2556
2557 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2558
2559 for (size_t i = 0; i < mEffectChains.size(); i++) {
2560 if (chain == mEffectChains[i]) {
2561 mEffectChains.removeAt(i);
2562 // detach all active tracks from the chain
2563 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2564 sp<Track> track = mActiveTracks[i].promote();
2565 if (track == 0) {
2566 continue;
2567 }
2568 if (session == track->sessionId()) {
2569 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2570 chain.get(), session);
2571 chain->decActiveTrackCnt();
2572 }
2573 }
2574
2575 // detach all tracks with same session ID from this chain
2576 for (size_t i = 0; i < mTracks.size(); ++i) {
2577 sp<Track> track = mTracks[i];
2578 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002579 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002580 chain->decTrackCnt();
2581 }
2582 }
2583 break;
2584 }
2585 }
2586 return mEffectChains.size();
2587}
2588
2589status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2590 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2591{
2592 Mutex::Autolock _l(mLock);
2593 return attachAuxEffect_l(track, EffectId);
2594}
2595
2596status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2597 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2598{
2599 status_t status = NO_ERROR;
2600
2601 if (EffectId == 0) {
2602 track->setAuxBuffer(0, NULL);
2603 } else {
2604 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2605 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2606 if (effect != 0) {
2607 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2608 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2609 } else {
2610 status = INVALID_OPERATION;
2611 }
2612 } else {
2613 status = BAD_VALUE;
2614 }
2615 }
2616 return status;
2617}
2618
2619void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2620{
2621 for (size_t i = 0; i < mTracks.size(); ++i) {
2622 sp<Track> track = mTracks[i];
2623 if (track->auxEffectId() == effectId) {
2624 attachAuxEffect_l(track, 0);
2625 }
2626 }
2627}
2628
2629bool AudioFlinger::PlaybackThread::threadLoop()
2630{
2631 Vector< sp<Track> > tracksToRemove;
2632
2633 standbyTime = systemTime();
2634
2635 // MIXER
2636 nsecs_t lastWarning = 0;
2637
2638 // DUPLICATING
2639 // FIXME could this be made local to while loop?
2640 writeFrames = 0;
2641
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002642 int lastGeneration = 0;
2643
Eric Laurent81784c32012-11-19 14:55:58 -08002644 cacheParameters_l();
2645 sleepTime = idleSleepTime;
2646
2647 if (mType == MIXER) {
2648 sleepTimeShift = 0;
2649 }
2650
2651 CpuStats cpuStats;
2652 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2653
2654 acquireWakeLock();
2655
Glenn Kasten9e58b552013-01-18 15:09:48 -08002656 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2657 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2658 // and then that string will be logged at the next convenient opportunity.
2659 const char *logString = NULL;
2660
Eric Laurent664539d2013-09-23 18:24:31 -07002661 checkSilentMode_l();
2662
Eric Laurent81784c32012-11-19 14:55:58 -08002663 while (!exitPending())
2664 {
2665 cpuStats.sample(myName);
2666
2667 Vector< sp<EffectChain> > effectChains;
2668
Eric Laurent81784c32012-11-19 14:55:58 -08002669 { // scope for mLock
2670
2671 Mutex::Autolock _l(mLock);
2672
Eric Laurent021cf962014-05-13 10:18:14 -07002673 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07002674
Glenn Kasten9e58b552013-01-18 15:09:48 -08002675 if (logString != NULL) {
2676 mNBLogWriter->logTimestamp();
2677 mNBLogWriter->log(logString);
2678 logString = NULL;
2679 }
2680
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002681 // Gather the framesReleased counters for all active tracks,
2682 // and latch them atomically with the timestamp.
2683 // FIXME We're using raw pointers as indices. A unique track ID would be a better index.
2684 mLatchD.mFramesReleased.clear();
2685 size_t size = mActiveTracks.size();
2686 for (size_t i = 0; i < size; i++) {
2687 sp<Track> t = mActiveTracks[i].promote();
2688 if (t != 0) {
2689 mLatchD.mFramesReleased.add(t.get(),
2690 t->mAudioTrackServerProxy->framesReleased());
2691 }
2692 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002693 if (mLatchDValid) {
2694 mLatchQ = mLatchD;
2695 mLatchDValid = false;
2696 mLatchQValid = true;
2697 }
2698
Eric Laurent81784c32012-11-19 14:55:58 -08002699 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002700 if (mSignalPending) {
2701 // A signal was raised while we were unlocked
2702 mSignalPending = false;
2703 } else if (waitingAsyncCallback_l()) {
2704 if (exitPending()) {
2705 break;
2706 }
Marco Nelissen078538c2015-05-12 09:17:57 -07002707 bool released = false;
2708 // The following works around a bug in the offload driver. Ideally we would release
2709 // the wake lock every time, but that causes the last offload buffer(s) to be
2710 // dropped while the device is on battery, so we need to hold a wake lock during
2711 // the drain phase.
2712 if (mBytesRemaining && !(mDrainSequence & 1)) {
2713 releaseWakeLock_l();
2714 released = true;
2715 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002716 mWakeLockUids.clear();
2717 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002718 ALOGV("wait async completion");
2719 mWaitWorkCV.wait(mLock);
2720 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07002721 if (released) {
2722 acquireWakeLock_l();
2723 }
Eric Laurent972a1732013-09-04 09:42:59 -07002724 standbyTime = systemTime() + standbyDelay;
2725 sleepTime = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002726
2727 continue;
2728 }
2729 if ((!mActiveTracks.size() && systemTime() > standbyTime) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08002730 isSuspended()) {
2731 // put audio hardware into standby after short delay
2732 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002733
2734 threadLoop_standby();
2735
2736 mStandby = true;
2737 }
2738
2739 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2740 // we're about to wait, flush the binder command buffer
2741 IPCThreadState::self()->flushCommands();
2742
2743 clearOutputTracks();
2744
2745 if (exitPending()) {
2746 break;
2747 }
2748
2749 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002750 mWakeLockUids.clear();
2751 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002752 // wait until we have something to do...
2753 ALOGV("%s going to sleep", myName.string());
2754 mWaitWorkCV.wait(mLock);
2755 ALOGV("%s waking up", myName.string());
2756 acquireWakeLock_l();
2757
2758 mMixerStatus = MIXER_IDLE;
2759 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2760 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002761 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002762 checkSilentMode_l();
2763
2764 standbyTime = systemTime() + standbyDelay;
2765 sleepTime = idleSleepTime;
2766 if (mType == MIXER) {
2767 sleepTimeShift = 0;
2768 }
2769
2770 continue;
2771 }
2772 }
Eric Laurent81784c32012-11-19 14:55:58 -08002773 // mMixerStatusIgnoringFastTracks is also updated internally
2774 mMixerStatus = prepareTracks_l(&tracksToRemove);
2775
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002776 // compare with previously applied list
2777 if (lastGeneration != mActiveTracksGeneration) {
2778 // update wakelock
2779 updateWakeLockUids_l(mWakeLockUids);
2780 lastGeneration = mActiveTracksGeneration;
2781 }
2782
Eric Laurent81784c32012-11-19 14:55:58 -08002783 // prevent any changes in effect chain list and in each effect chain
2784 // during mixing and effect process as the audio buffers could be deleted
2785 // or modified if an effect is created or deleted
2786 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002787 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08002788
Eric Laurentbfb1b832013-01-07 09:53:42 -08002789 if (mBytesRemaining == 0) {
2790 mCurrentWriteLength = 0;
2791 if (mMixerStatus == MIXER_TRACKS_READY) {
2792 // threadLoop_mix() sets mCurrentWriteLength
2793 threadLoop_mix();
2794 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
2795 && (mMixerStatus != MIXER_DRAIN_ALL)) {
2796 // threadLoop_sleepTime sets sleepTime to 0 if data
2797 // must be written to HAL
2798 threadLoop_sleepTime();
2799 if (sleepTime == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08002800 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002801 }
2802 }
Andy Hung98ef9782014-03-04 14:46:50 -08002803 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
2804 // mMixerBuffer with data if mMixerBufferValid is true and sleepTime == 0.
2805 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
2806 // or mSinkBuffer (if there are no effects).
2807 //
2808 // This is done pre-effects computation; if effects change to
2809 // support higher precision, this needs to move.
2810 //
2811 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
2812 // TODO use sleepTime == 0 as an additional condition.
2813 if (mMixerBufferValid) {
2814 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
2815 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
2816
2817 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
2818 mNormalFrameCount * mChannelCount);
2819 }
2820
Eric Laurentbfb1b832013-01-07 09:53:42 -08002821 mBytesRemaining = mCurrentWriteLength;
2822 if (isSuspended()) {
2823 sleepTime = suspendSleepTimeUs();
2824 // simulate write to HAL when suspended
Andy Hung25c2dac2014-02-27 14:56:00 -08002825 mBytesWritten += mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002826 mBytesRemaining = 0;
2827 }
Eric Laurent81784c32012-11-19 14:55:58 -08002828
Eric Laurentbfb1b832013-01-07 09:53:42 -08002829 // only process effects if we're going to write
Eric Laurent59fe0102013-09-27 18:48:26 -07002830 if (sleepTime == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002831 for (size_t i = 0; i < effectChains.size(); i ++) {
2832 effectChains[i]->process_l();
2833 }
Eric Laurent81784c32012-11-19 14:55:58 -08002834 }
2835 }
Eric Laurent59fe0102013-09-27 18:48:26 -07002836 // Process effect chains for offloaded thread even if no audio
2837 // was read from audio track: process only updates effect state
2838 // and thus does have to be synchronized with audio writes but may have
2839 // to be called while waiting for async write callback
2840 if (mType == OFFLOAD) {
2841 for (size_t i = 0; i < effectChains.size(); i ++) {
2842 effectChains[i]->process_l();
2843 }
2844 }
Eric Laurent81784c32012-11-19 14:55:58 -08002845
Andy Hung98ef9782014-03-04 14:46:50 -08002846 // Only if the Effects buffer is enabled and there is data in the
2847 // Effects buffer (buffer valid), we need to
2848 // copy into the sink buffer.
2849 // TODO use sleepTime == 0 as an additional condition.
2850 if (mEffectBufferValid) {
2851 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
2852 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
2853 mNormalFrameCount * mChannelCount);
2854 }
2855
Eric Laurent81784c32012-11-19 14:55:58 -08002856 // enable changes in effect chain
2857 unlockEffectChains(effectChains);
2858
Eric Laurentbfb1b832013-01-07 09:53:42 -08002859 if (!waitingAsyncCallback()) {
2860 // sleepTime == 0 means we must write to audio hardware
2861 if (sleepTime == 0) {
2862 if (mBytesRemaining) {
2863 ssize_t ret = threadLoop_write();
2864 if (ret < 0) {
2865 mBytesRemaining = 0;
2866 } else {
2867 mBytesWritten += ret;
2868 mBytesRemaining -= ret;
2869 }
2870 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
2871 (mMixerStatus == MIXER_DRAIN_ALL)) {
2872 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08002873 }
Glenn Kasten4944acb2013-08-19 08:39:20 -07002874 if (mType == MIXER) {
2875 // write blocked detection
2876 nsecs_t now = systemTime();
2877 nsecs_t delta = now - mLastWriteTime;
2878 if (!mStandby && delta > maxPeriod) {
2879 mNumDelayedWrites++;
2880 if ((now - lastWarning) > kWarningThrottleNs) {
2881 ATRACE_NAME("underrun");
2882 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2883 ns2ms(delta), mNumDelayedWrites, this);
2884 lastWarning = now;
2885 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002886 }
2887 }
Eric Laurent81784c32012-11-19 14:55:58 -08002888
Eric Laurentbfb1b832013-01-07 09:53:42 -08002889 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07002890 ATRACE_BEGIN("sleep");
Eric Laurentbfb1b832013-01-07 09:53:42 -08002891 usleep(sleepTime);
Glenn Kastene7754022014-10-31 12:11:26 -07002892 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002893 }
Eric Laurent81784c32012-11-19 14:55:58 -08002894 }
2895
2896 // Finally let go of removed track(s), without the lock held
2897 // since we can't guarantee the destructors won't acquire that
2898 // same lock. This will also mutate and push a new fast mixer state.
2899 threadLoop_removeTracks(tracksToRemove);
2900 tracksToRemove.clear();
2901
2902 // FIXME I don't understand the need for this here;
2903 // it was in the original code but maybe the
2904 // assignment in saveOutputTracks() makes this unnecessary?
2905 clearOutputTracks();
2906
2907 // Effect chains will be actually deleted here if they were removed from
2908 // mEffectChains list during mixing or effects processing
2909 effectChains.clear();
2910
2911 // FIXME Note that the above .clear() is no longer necessary since effectChains
2912 // is now local to this block, but will keep it for now (at least until merge done).
2913 }
2914
Eric Laurentbfb1b832013-01-07 09:53:42 -08002915 threadLoop_exit();
2916
Eric Laurentcf817a22014-08-04 20:36:31 -07002917 if (!mStandby) {
2918 threadLoop_standby();
2919 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08002920 }
2921
2922 releaseWakeLock();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002923 mWakeLockUids.clear();
2924 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002925
2926 ALOGV("Thread %p type %d exiting", this, mType);
2927 return false;
2928}
2929
Eric Laurentbfb1b832013-01-07 09:53:42 -08002930// removeTracks_l() must be called with ThreadBase::mLock held
2931void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
2932{
2933 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002934 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002935 for (size_t i=0 ; i<count ; i++) {
2936 const sp<Track>& track = tracksToRemove.itemAt(i);
2937 mActiveTracks.remove(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002938 mWakeLockUids.remove(track->uid());
2939 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002940 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
2941 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2942 if (chain != 0) {
2943 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
2944 track->sessionId());
2945 chain->decActiveTrackCnt();
2946 }
2947 if (track->isTerminated()) {
2948 removeTrack_l(track);
2949 }
2950 }
2951 }
2952
2953}
Eric Laurent81784c32012-11-19 14:55:58 -08002954
Eric Laurentaccc1472013-09-20 09:36:34 -07002955status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
2956{
2957 if (mNormalSink != 0) {
2958 return mNormalSink->getTimestamp(timestamp);
2959 }
Andy Hung9a1c8892014-12-03 11:37:42 -08002960 if ((mType == OFFLOAD || mType == DIRECT)
2961 && mOutput != NULL && mOutput->stream->get_presentation_position) {
Eric Laurentaccc1472013-09-20 09:36:34 -07002962 uint64_t position64;
Phil Burk062e67a2015-02-11 13:40:50 -08002963 int ret = mOutput->getPresentationPosition(&position64, &timestamp.mTime);
Eric Laurentaccc1472013-09-20 09:36:34 -07002964 if (ret == 0) {
2965 timestamp.mPosition = (uint32_t)position64;
2966 return NO_ERROR;
2967 }
2968 }
2969 return INVALID_OPERATION;
2970}
Eric Laurent1c333e22014-05-20 10:48:17 -07002971
Eric Laurent054d9d32015-04-24 08:48:48 -07002972status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
2973 audio_patch_handle_t *handle)
2974{
2975 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
2976 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
2977 if (mFastMixer != 0) {
2978 FastMixerStateQueue *sq = mFastMixer->sq();
2979 FastMixerState *state = sq->begin();
2980 if (!(state->mCommand & FastMixerState::IDLE)) {
2981 previousCommand = state->mCommand;
2982 state->mCommand = FastMixerState::HOT_IDLE;
2983 sq->end();
2984 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
2985 } else {
2986 sq->end(false /*didModify*/);
2987 }
2988 }
2989 status_t status = PlaybackThread::createAudioPatch_l(patch, handle);
2990
2991 if (!(previousCommand & FastMixerState::IDLE)) {
2992 ALOG_ASSERT(mFastMixer != 0);
2993 FastMixerStateQueue *sq = mFastMixer->sq();
2994 FastMixerState *state = sq->begin();
2995 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
2996 state->mCommand = previousCommand;
2997 sq->end();
2998 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2999 }
3000
3001 return status;
3002}
3003
Eric Laurent1c333e22014-05-20 10:48:17 -07003004status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3005 audio_patch_handle_t *handle)
3006{
3007 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003008
3009 // store new device and send to effects
3010 audio_devices_t type = AUDIO_DEVICE_NONE;
3011 for (unsigned int i = 0; i < patch->num_sinks; i++) {
3012 type |= patch->sinks[i].ext.device.type;
3013 }
3014
3015#ifdef ADD_BATTERY_DATA
3016 // when changing the audio output device, call addBatteryData to notify
3017 // the change
3018 if (mOutDevice != type) {
3019 uint32_t params = 0;
3020 // check whether speaker is on
3021 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3022 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003023 }
3024
Eric Laurent054d9d32015-04-24 08:48:48 -07003025 audio_devices_t deviceWithoutSpeaker
3026 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3027 // check if any other device (except speaker) is on
3028 if (type & deviceWithoutSpeaker) {
3029 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3030 }
3031
3032 if (params != 0) {
3033 addBatteryData(params);
3034 }
3035 }
3036#endif
3037
3038 for (size_t i = 0; i < mEffectChains.size(); i++) {
3039 mEffectChains[i]->setDevice_l(type);
3040 }
3041 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003042 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003043
3044 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003045 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
3046 status = hwDevice->create_audio_patch(hwDevice,
3047 patch->num_sources,
3048 patch->sources,
3049 patch->num_sinks,
3050 patch->sinks,
3051 handle);
3052 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003053 char *address;
3054 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3055 //FIXME: we only support address on first sink with HAL version < 3.0
3056 address = audio_device_address_to_parameter(
3057 patch->sinks[0].ext.device.type,
3058 patch->sinks[0].ext.device.address);
3059 } else {
3060 address = (char *)calloc(1, 1);
3061 }
3062 AudioParameter param = AudioParameter(String8(address));
3063 free(address);
3064 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), (int)type);
3065 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3066 param.toString().string());
3067 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003068 }
Eric Laurent296fb132015-05-01 11:38:42 -07003069 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent1c333e22014-05-20 10:48:17 -07003070 return status;
3071}
3072
Eric Laurent054d9d32015-04-24 08:48:48 -07003073status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3074{
3075 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3076 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3077 if (mFastMixer != 0) {
3078 FastMixerStateQueue *sq = mFastMixer->sq();
3079 FastMixerState *state = sq->begin();
3080 if (!(state->mCommand & FastMixerState::IDLE)) {
3081 previousCommand = state->mCommand;
3082 state->mCommand = FastMixerState::HOT_IDLE;
3083 sq->end();
3084 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3085 } else {
3086 sq->end(false /*didModify*/);
3087 }
3088 }
3089
3090 status_t status = PlaybackThread::releaseAudioPatch_l(handle);
3091
3092 if (!(previousCommand & FastMixerState::IDLE)) {
3093 ALOG_ASSERT(mFastMixer != 0);
3094 FastMixerStateQueue *sq = mFastMixer->sq();
3095 FastMixerState *state = sq->begin();
3096 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3097 state->mCommand = previousCommand;
3098 sq->end();
3099 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3100 }
3101
3102 return status;
3103}
3104
Eric Laurent1c333e22014-05-20 10:48:17 -07003105status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3106{
3107 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003108
3109 mOutDevice = AUDIO_DEVICE_NONE;
3110
Eric Laurent1c333e22014-05-20 10:48:17 -07003111 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
3112 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
3113 status = hwDevice->release_audio_patch(hwDevice, handle);
3114 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003115 AudioParameter param;
3116 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
3117 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3118 param.toString().string());
Eric Laurent1c333e22014-05-20 10:48:17 -07003119 }
3120 return status;
3121}
3122
Eric Laurent83b88082014-06-20 18:31:16 -07003123void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3124{
3125 Mutex::Autolock _l(mLock);
3126 mTracks.add(track);
3127}
3128
3129void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3130{
3131 Mutex::Autolock _l(mLock);
3132 destroyTrack_l(track);
3133}
3134
3135void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
3136{
3137 ThreadBase::getAudioPortConfig(config);
3138 config->role = AUDIO_PORT_ROLE_SOURCE;
3139 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3140 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
3141}
3142
Eric Laurent81784c32012-11-19 14:55:58 -08003143// ----------------------------------------------------------------------------
3144
3145AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurent72e3f392015-05-20 14:43:50 -07003146 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
3147 : PlaybackThread(audioFlinger, output, id, device, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08003148 // mAudioMixer below
3149 // mFastMixer below
3150 mFastMixerFutex(0)
3151 // mOutputSink below
3152 // mPipeSink below
3153 // mNormalSink below
3154{
3155 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07003156 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, "
Eric Laurent81784c32012-11-19 14:55:58 -08003157 "mFrameCount=%d, mNormalFrameCount=%d",
3158 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3159 mNormalFrameCount);
3160 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3161
Andy Hungfbfc3952015-01-15 13:33:51 -08003162 if (type == DUPLICATING) {
3163 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3164 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3165 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3166 return;
3167 }
Eric Laurent81784c32012-11-19 14:55:58 -08003168 // create an NBAIO sink for the HAL output stream, and negotiate
3169 mOutputSink = new AudioStreamOutSink(output->stream);
3170 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003171 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Eric Laurent81784c32012-11-19 14:55:58 -08003172 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
3173 ALOG_ASSERT(index == 0);
3174
3175 // initialize fast mixer depending on configuration
3176 bool initFastMixer;
3177 switch (kUseFastMixer) {
3178 case FastMixer_Never:
3179 initFastMixer = false;
3180 break;
3181 case FastMixer_Always:
3182 initFastMixer = true;
3183 break;
3184 case FastMixer_Static:
3185 case FastMixer_Dynamic:
3186 initFastMixer = mFrameCount < mNormalFrameCount;
3187 break;
3188 }
3189 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003190 audio_format_t fastMixerFormat;
3191 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3192 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3193 } else {
3194 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3195 }
3196 if (mFormat != fastMixerFormat) {
3197 // change our Sink format to accept our intermediate precision
3198 mFormat = fastMixerFormat;
3199 free(mSinkBuffer);
3200 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3201 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3202 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3203 }
Eric Laurent81784c32012-11-19 14:55:58 -08003204
3205 // create a MonoPipe to connect our submix to FastMixer
3206 NBAIO_Format format = mOutputSink->format();
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003207 NBAIO_Format origformat = format;
Andy Hung1258c1a2014-05-23 21:22:17 -07003208 // adjust format to match that of the Fast Mixer
Glenn Kasten97b7b752014-09-28 13:04:24 -07003209 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003210 format.mFormat = fastMixerFormat;
3211 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3212
Eric Laurent81784c32012-11-19 14:55:58 -08003213 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3214 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3215 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3216 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3217 const NBAIO_Format offers[1] = {format};
3218 size_t numCounterOffers = 0;
3219 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
3220 ALOG_ASSERT(index == 0);
3221 monoPipe->setAvgFrames((mScreenState & 1) ?
3222 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3223 mPipeSink = monoPipe;
3224
Glenn Kasten46909e72013-02-26 09:20:22 -08003225#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08003226 if (mTeeSinkOutputEnabled) {
3227 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003228 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
3229 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08003230 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003231 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003232 ALOG_ASSERT(index == 0);
3233 mTeeSink = teeSink;
3234 PipeReader *teeSource = new PipeReader(*teeSink);
3235 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003236 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003237 ALOG_ASSERT(index == 0);
3238 mTeeSource = teeSource;
3239 }
Glenn Kasten46909e72013-02-26 09:20:22 -08003240#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003241
3242 // create fast mixer and configure it initially with just one fast track for our submix
3243 mFastMixer = new FastMixer();
3244 FastMixerStateQueue *sq = mFastMixer->sq();
3245#ifdef STATE_QUEUE_DUMP
3246 sq->setObserverDump(&mStateQueueObserverDump);
3247 sq->setMutatorDump(&mStateQueueMutatorDump);
3248#endif
3249 FastMixerState *state = sq->begin();
3250 FastTrack *fastTrack = &state->mFastTracks[0];
3251 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3252 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3253 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003254 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3255 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003256 fastTrack->mGeneration++;
3257 state->mFastTracksGen++;
3258 state->mTrackMask = 1;
3259 // fast mixer will use the HAL output sink
3260 state->mOutputSink = mOutputSink.get();
3261 state->mOutputSinkGen++;
3262 state->mFrameCount = mFrameCount;
3263 state->mCommand = FastMixerState::COLD_IDLE;
3264 // already done in constructor initialization list
3265 //mFastMixerFutex = 0;
3266 state->mColdFutexAddr = &mFastMixerFutex;
3267 state->mColdGen++;
3268 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08003269#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003270 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08003271#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08003272 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3273 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003274 sq->end();
3275 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3276
3277 // start the fast mixer
3278 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3279 pid_t tid = mFastMixer->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003280 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003281
3282#ifdef AUDIO_WATCHDOG
3283 // create and start the watchdog
3284 mAudioWatchdog = new AudioWatchdog();
3285 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3286 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3287 tid = mAudioWatchdog->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003288 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003289#endif
3290
Eric Laurent81784c32012-11-19 14:55:58 -08003291 }
3292
3293 switch (kUseFastMixer) {
3294 case FastMixer_Never:
3295 case FastMixer_Dynamic:
3296 mNormalSink = mOutputSink;
3297 break;
3298 case FastMixer_Always:
3299 mNormalSink = mPipeSink;
3300 break;
3301 case FastMixer_Static:
3302 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3303 break;
3304 }
3305}
3306
3307AudioFlinger::MixerThread::~MixerThread()
3308{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003309 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003310 FastMixerStateQueue *sq = mFastMixer->sq();
3311 FastMixerState *state = sq->begin();
3312 if (state->mCommand == FastMixerState::COLD_IDLE) {
3313 int32_t old = android_atomic_inc(&mFastMixerFutex);
3314 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003315 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003316 }
3317 }
3318 state->mCommand = FastMixerState::EXIT;
3319 sq->end();
3320 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3321 mFastMixer->join();
3322 // Though the fast mixer thread has exited, it's state queue is still valid.
3323 // We'll use that extract the final state which contains one remaining fast track
3324 // corresponding to our sub-mix.
3325 state = sq->begin();
3326 ALOG_ASSERT(state->mTrackMask == 1);
3327 FastTrack *fastTrack = &state->mFastTracks[0];
3328 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3329 delete fastTrack->mBufferProvider;
3330 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003331 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003332#ifdef AUDIO_WATCHDOG
3333 if (mAudioWatchdog != 0) {
3334 mAudioWatchdog->requestExit();
3335 mAudioWatchdog->requestExitAndWait();
3336 mAudioWatchdog.clear();
3337 }
3338#endif
3339 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003340 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003341 delete mAudioMixer;
3342}
3343
3344
3345uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3346{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003347 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003348 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3349 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3350 }
3351 return latency;
3352}
3353
3354
3355void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3356{
3357 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3358}
3359
Eric Laurentbfb1b832013-01-07 09:53:42 -08003360ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003361{
3362 // FIXME we should only do one push per cycle; confirm this is true
3363 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003364 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003365 FastMixerStateQueue *sq = mFastMixer->sq();
3366 FastMixerState *state = sq->begin();
3367 if (state->mCommand != FastMixerState::MIX_WRITE &&
3368 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3369 if (state->mCommand == FastMixerState::COLD_IDLE) {
3370 int32_t old = android_atomic_inc(&mFastMixerFutex);
3371 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003372 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003373 }
3374#ifdef AUDIO_WATCHDOG
3375 if (mAudioWatchdog != 0) {
3376 mAudioWatchdog->resume();
3377 }
3378#endif
3379 }
3380 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08003381#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003382 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08003383 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08003384#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003385 sq->end();
3386 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3387 if (kUseFastMixer == FastMixer_Dynamic) {
3388 mNormalSink = mPipeSink;
3389 }
3390 } else {
3391 sq->end(false /*didModify*/);
3392 }
3393 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003394 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003395}
3396
3397void AudioFlinger::MixerThread::threadLoop_standby()
3398{
3399 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003400 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003401 FastMixerStateQueue *sq = mFastMixer->sq();
3402 FastMixerState *state = sq->begin();
3403 if (!(state->mCommand & FastMixerState::IDLE)) {
3404 state->mCommand = FastMixerState::COLD_IDLE;
3405 state->mColdFutexAddr = &mFastMixerFutex;
3406 state->mColdGen++;
3407 mFastMixerFutex = 0;
3408 sq->end();
3409 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3410 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3411 if (kUseFastMixer == FastMixer_Dynamic) {
3412 mNormalSink = mOutputSink;
3413 }
3414#ifdef AUDIO_WATCHDOG
3415 if (mAudioWatchdog != 0) {
3416 mAudioWatchdog->pause();
3417 }
3418#endif
3419 } else {
3420 sq->end(false /*didModify*/);
3421 }
3422 }
3423 PlaybackThread::threadLoop_standby();
3424}
3425
Eric Laurentbfb1b832013-01-07 09:53:42 -08003426bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3427{
3428 return false;
3429}
3430
3431bool AudioFlinger::PlaybackThread::shouldStandby_l()
3432{
3433 return !mStandby;
3434}
3435
3436bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3437{
3438 Mutex::Autolock _l(mLock);
3439 return waitingAsyncCallback_l();
3440}
3441
Eric Laurent81784c32012-11-19 14:55:58 -08003442// shared by MIXER and DIRECT, overridden by DUPLICATING
3443void AudioFlinger::PlaybackThread::threadLoop_standby()
3444{
3445 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08003446 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003447 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003448 // discard any pending drain or write ack by incrementing sequence
3449 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3450 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003451 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003452 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3453 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003454 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003455 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003456}
3457
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003458void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3459{
3460 ALOGV("signal playback thread");
3461 broadcast_l();
3462}
3463
Eric Laurent81784c32012-11-19 14:55:58 -08003464void AudioFlinger::MixerThread::threadLoop_mix()
3465{
3466 // obtain the presentation timestamp of the next output buffer
3467 int64_t pts;
3468 status_t status = INVALID_OPERATION;
3469
3470 if (mNormalSink != 0) {
3471 status = mNormalSink->getNextWriteTimestamp(&pts);
3472 } else {
3473 status = mOutputSink->getNextWriteTimestamp(&pts);
3474 }
3475
3476 if (status != NO_ERROR) {
3477 pts = AudioBufferProvider::kInvalidPTS;
3478 }
3479
3480 // mix buffers...
3481 mAudioMixer->process(pts);
Andy Hung25c2dac2014-02-27 14:56:00 -08003482 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003483 // increase sleep time progressively when application underrun condition clears.
3484 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3485 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3486 // such that we would underrun the audio HAL.
3487 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
3488 sleepTimeShift--;
3489 }
3490 sleepTime = 0;
3491 standbyTime = systemTime() + standbyDelay;
3492 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003493
Eric Laurent81784c32012-11-19 14:55:58 -08003494}
3495
3496void AudioFlinger::MixerThread::threadLoop_sleepTime()
3497{
3498 // If no tracks are ready, sleep once for the duration of an output
3499 // buffer size, then write 0s to the output
3500 if (sleepTime == 0) {
3501 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3502 sleepTime = activeSleepTime >> sleepTimeShift;
3503 if (sleepTime < kMinThreadSleepTimeUs) {
3504 sleepTime = kMinThreadSleepTimeUs;
3505 }
3506 // reduce sleep time in case of consecutive application underruns to avoid
3507 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3508 // duration we would end up writing less data than needed by the audio HAL if
3509 // the condition persists.
3510 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3511 sleepTimeShift++;
3512 }
3513 } else {
3514 sleepTime = idleSleepTime;
3515 }
3516 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003517 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3518 // before effects processing or output.
3519 if (mMixerBufferValid) {
3520 memset(mMixerBuffer, 0, mMixerBufferSize);
3521 } else {
3522 memset(mSinkBuffer, 0, mSinkBufferSize);
3523 }
Eric Laurent81784c32012-11-19 14:55:58 -08003524 sleepTime = 0;
3525 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3526 "anticipated start");
3527 }
3528 // TODO add standby time extension fct of effect tail
3529}
3530
3531// prepareTracks_l() must be called with ThreadBase::mLock held
3532AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3533 Vector< sp<Track> > *tracksToRemove)
3534{
3535
3536 mixer_state mixerStatus = MIXER_IDLE;
3537 // find out which tracks need to be processed
3538 size_t count = mActiveTracks.size();
3539 size_t mixedTracks = 0;
3540 size_t tracksWithEffect = 0;
3541 // counts only _active_ fast tracks
3542 size_t fastTracks = 0;
3543 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
3544
3545 float masterVolume = mMasterVolume;
3546 bool masterMute = mMasterMute;
3547
3548 if (masterMute) {
3549 masterVolume = 0;
3550 }
3551 // Delegate master volume control to effect in output mix effect chain if needed
3552 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3553 if (chain != 0) {
3554 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
3555 chain->setVolume_l(&v, &v);
3556 masterVolume = (float)((v + (1 << 23)) >> 24);
3557 chain.clear();
3558 }
3559
3560 // prepare a new state to push
3561 FastMixerStateQueue *sq = NULL;
3562 FastMixerState *state = NULL;
3563 bool didModify = false;
3564 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003565 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003566 sq = mFastMixer->sq();
3567 state = sq->begin();
3568 }
3569
Andy Hung69aed5f2014-02-25 17:24:40 -08003570 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08003571 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08003572
Eric Laurent81784c32012-11-19 14:55:58 -08003573 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003574 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003575 if (t == 0) {
3576 continue;
3577 }
3578
3579 // this const just means the local variable doesn't change
3580 Track* const track = t.get();
3581
3582 // process fast tracks
3583 if (track->isFastTrack()) {
3584
3585 // It's theoretically possible (though unlikely) for a fast track to be created
3586 // and then removed within the same normal mix cycle. This is not a problem, as
3587 // the track never becomes active so it's fast mixer slot is never touched.
3588 // The converse, of removing an (active) track and then creating a new track
3589 // at the identical fast mixer slot within the same normal mix cycle,
3590 // is impossible because the slot isn't marked available until the end of each cycle.
3591 int j = track->mFastIndex;
3592 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
3593 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
3594 FastTrack *fastTrack = &state->mFastTracks[j];
3595
3596 // Determine whether the track is currently in underrun condition,
3597 // and whether it had a recent underrun.
3598 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
3599 FastTrackUnderruns underruns = ftDump->mUnderruns;
3600 uint32_t recentFull = (underruns.mBitFields.mFull -
3601 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
3602 uint32_t recentPartial = (underruns.mBitFields.mPartial -
3603 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
3604 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
3605 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
3606 uint32_t recentUnderruns = recentPartial + recentEmpty;
3607 track->mObservedUnderruns = underruns;
3608 // don't count underruns that occur while stopping or pausing
3609 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07003610 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
3611 recentUnderruns > 0) {
3612 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
3613 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003614 }
3615
3616 // This is similar to the state machine for normal tracks,
3617 // with a few modifications for fast tracks.
3618 bool isActive = true;
3619 switch (track->mState) {
3620 case TrackBase::STOPPING_1:
3621 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08003622 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003623 track->mState = TrackBase::STOPPING_2;
3624 }
3625 break;
3626 case TrackBase::PAUSING:
3627 // ramp down is not yet implemented
3628 track->setPaused();
3629 break;
3630 case TrackBase::RESUMING:
3631 // ramp up is not yet implemented
3632 track->mState = TrackBase::ACTIVE;
3633 break;
3634 case TrackBase::ACTIVE:
3635 if (recentFull > 0 || recentPartial > 0) {
3636 // track has provided at least some frames recently: reset retry count
3637 track->mRetryCount = kMaxTrackRetries;
3638 }
3639 if (recentUnderruns == 0) {
3640 // no recent underruns: stay active
3641 break;
3642 }
3643 // there has recently been an underrun of some kind
3644 if (track->sharedBuffer() == 0) {
3645 // were any of the recent underruns "empty" (no frames available)?
3646 if (recentEmpty == 0) {
3647 // no, then ignore the partial underruns as they are allowed indefinitely
3648 break;
3649 }
3650 // there has recently been an "empty" underrun: decrement the retry counter
3651 if (--(track->mRetryCount) > 0) {
3652 break;
3653 }
3654 // indicate to client process that the track was disabled because of underrun;
3655 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003656 android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003657 // remove from active list, but state remains ACTIVE [confusing but true]
3658 isActive = false;
3659 break;
3660 }
3661 // fall through
3662 case TrackBase::STOPPING_2:
3663 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003664 case TrackBase::STOPPED:
3665 case TrackBase::FLUSHED: // flush() while active
3666 // Check for presentation complete if track is inactive
3667 // We have consumed all the buffers of this track.
3668 // This would be incomplete if we auto-paused on underrun
3669 {
3670 size_t audioHALFrames =
3671 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3672 size_t framesWritten = mBytesWritten / mFrameSize;
3673 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
3674 // track stays in active list until presentation is complete
3675 break;
3676 }
3677 }
3678 if (track->isStopping_2()) {
3679 track->mState = TrackBase::STOPPED;
3680 }
3681 if (track->isStopped()) {
3682 // Can't reset directly, as fast mixer is still polling this track
3683 // track->reset();
3684 // So instead mark this track as needing to be reset after push with ack
3685 resetMask |= 1 << i;
3686 }
3687 isActive = false;
3688 break;
3689 case TrackBase::IDLE:
3690 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08003691 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08003692 }
3693
3694 if (isActive) {
3695 // was it previously inactive?
3696 if (!(state->mTrackMask & (1 << j))) {
3697 ExtendedAudioBufferProvider *eabp = track;
3698 VolumeProvider *vp = track;
3699 fastTrack->mBufferProvider = eabp;
3700 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08003701 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003702 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08003703 fastTrack->mGeneration++;
3704 state->mTrackMask |= 1 << j;
3705 didModify = true;
3706 // no acknowledgement required for newly active tracks
3707 }
3708 // cache the combined master volume and stream type volume for fast mixer; this
3709 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08003710 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08003711 ++fastTracks;
3712 } else {
3713 // was it previously active?
3714 if (state->mTrackMask & (1 << j)) {
3715 fastTrack->mBufferProvider = NULL;
3716 fastTrack->mGeneration++;
3717 state->mTrackMask &= ~(1 << j);
3718 didModify = true;
3719 // If any fast tracks were removed, we must wait for acknowledgement
3720 // because we're about to decrement the last sp<> on those tracks.
3721 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3722 } else {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003723 LOG_ALWAYS_FATAL("fast track %d should have been active", j);
Eric Laurent81784c32012-11-19 14:55:58 -08003724 }
3725 tracksToRemove->add(track);
3726 // Avoids a misleading display in dumpsys
3727 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
3728 }
3729 continue;
3730 }
3731
3732 { // local variable scope to avoid goto warning
3733
3734 audio_track_cblk_t* cblk = track->cblk();
3735
3736 // The first time a track is added we wait
3737 // for all its buffers to be filled before processing it
3738 int name = track->name();
3739 // make sure that we have enough frames to mix one full buffer.
3740 // enforce this condition only once to enable draining the buffer in case the client
3741 // app does not call stop() and relies on underrun to stop:
3742 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
3743 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003744 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07003745 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07003746 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07003747
3748 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07003749 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07003750 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
3751 // add frames already consumed but not yet released by the resampler
3752 // because mAudioTrackServerProxy->framesReady() will include these frames
3753 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
3754
Eric Laurent81784c32012-11-19 14:55:58 -08003755 uint32_t minFrames = 1;
3756 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
3757 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003758 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08003759 }
Eric Laurent13e4c962013-12-20 17:36:01 -08003760
3761 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07003762 if (ATRACE_ENABLED()) {
3763 // I wish we had formatted trace names
3764 char traceName[16];
3765 strcpy(traceName, "nRdy");
3766 int name = track->name();
3767 if (AudioMixer::TRACK0 <= name &&
3768 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
3769 name -= AudioMixer::TRACK0;
3770 traceName[4] = (name / 10) + '0';
3771 traceName[5] = (name % 10) + '0';
3772 } else {
3773 traceName[4] = '?';
3774 traceName[5] = '?';
3775 }
3776 traceName[6] = '\0';
3777 ATRACE_INT(traceName, framesReady);
3778 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003779 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08003780 !track->isPaused() && !track->isTerminated())
3781 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003782 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003783
3784 mixedTracks++;
3785
Andy Hung69aed5f2014-02-25 17:24:40 -08003786 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
3787 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08003788 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08003789 if (track->mainBuffer() != mSinkBuffer &&
3790 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08003791 if (mEffectBufferEnabled) {
3792 mEffectBufferValid = true; // Later can set directly.
3793 }
Eric Laurent81784c32012-11-19 14:55:58 -08003794 chain = getEffectChain_l(track->sessionId());
3795 // Delegate volume control to effect in track effect chain if needed
3796 if (chain != 0) {
3797 tracksWithEffect++;
3798 } else {
3799 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
3800 "session %d",
3801 name, track->sessionId());
3802 }
3803 }
3804
3805
3806 int param = AudioMixer::VOLUME;
3807 if (track->mFillingUpStatus == Track::FS_FILLED) {
3808 // no ramp for the first volume setting
3809 track->mFillingUpStatus = Track::FS_ACTIVE;
3810 if (track->mState == TrackBase::RESUMING) {
3811 track->mState = TrackBase::ACTIVE;
3812 param = AudioMixer::RAMP_VOLUME;
3813 }
3814 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003815 // FIXME should not make a decision based on mServer
3816 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003817 // If the track is stopped before the first frame was mixed,
3818 // do not apply ramp
3819 param = AudioMixer::RAMP_VOLUME;
3820 }
3821
3822 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07003823 uint32_t vl, vr; // in U8.24 integer format
3824 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08003825 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07003826 vl = vr = 0;
3827 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08003828 if (track->isPausing()) {
3829 track->setPaused();
3830 }
3831 } else {
3832
3833 // read original volumes with volume control
3834 float typeVolume = mStreamTypes[track->streamType()].volume;
3835 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003836 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07003837 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07003838 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
3839 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08003840 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07003841 if (vlf > GAIN_FLOAT_UNITY) {
3842 ALOGV("Track left volume out of range: %.3g", vlf);
3843 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003844 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07003845 if (vrf > GAIN_FLOAT_UNITY) {
3846 ALOGV("Track right volume out of range: %.3g", vrf);
3847 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003848 }
3849 // now apply the master volume and stream type volume
Andy Hung6be49402014-05-30 10:42:03 -07003850 vlf *= v;
3851 vrf *= v;
Eric Laurent81784c32012-11-19 14:55:58 -08003852 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07003853 // then derive vl and vr as U8.24 versions for the effect chain
3854 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
3855 vl = (uint32_t) (scaleto8_24 * vlf);
3856 vr = (uint32_t) (scaleto8_24 * vrf);
3857 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08003858 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08003859 // send level comes from shared memory and so may be corrupt
3860 if (sendLevel > MAX_GAIN_INT) {
3861 ALOGV("Track send level out of range: %04X", sendLevel);
3862 sendLevel = MAX_GAIN_INT;
3863 }
Andy Hung6be49402014-05-30 10:42:03 -07003864 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
3865 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08003866 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003867
Eric Laurent81784c32012-11-19 14:55:58 -08003868 // Delegate volume control to effect in track effect chain if needed
3869 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3870 // Do not ramp volume if volume is controlled by effect
3871 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08003872 // Update remaining floating point volume levels
3873 vlf = (float)vl / (1 << 24);
3874 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08003875 track->mHasVolumeController = true;
3876 } else {
3877 // force no volume ramp when volume controller was just disabled or removed
3878 // from effect chain to avoid volume spike
3879 if (track->mHasVolumeController) {
3880 param = AudioMixer::VOLUME;
3881 }
3882 track->mHasVolumeController = false;
3883 }
3884
Eric Laurent81784c32012-11-19 14:55:58 -08003885 // XXX: these things DON'T need to be done each time
3886 mAudioMixer->setBufferProvider(name, track);
3887 mAudioMixer->enable(name);
3888
Andy Hung6be49402014-05-30 10:42:03 -07003889 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
3890 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
3891 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08003892 mAudioMixer->setParameter(
3893 name,
3894 AudioMixer::TRACK,
3895 AudioMixer::FORMAT, (void *)track->format());
3896 mAudioMixer->setParameter(
3897 name,
3898 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003899 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07003900 mAudioMixer->setParameter(
3901 name,
3902 AudioMixer::TRACK,
3903 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08003904 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07003905 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003906 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08003907 if (reqSampleRate == 0) {
3908 reqSampleRate = mSampleRate;
3909 } else if (reqSampleRate > maxSampleRate) {
3910 reqSampleRate = maxSampleRate;
3911 }
Eric Laurent81784c32012-11-19 14:55:58 -08003912 mAudioMixer->setParameter(
3913 name,
3914 AudioMixer::RESAMPLE,
3915 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003916 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07003917
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07003918 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07003919 mAudioMixer->setParameter(
3920 name,
3921 AudioMixer::TIMESTRETCH,
3922 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07003923 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07003924
Andy Hung69aed5f2014-02-25 17:24:40 -08003925 /*
3926 * Select the appropriate output buffer for the track.
3927 *
Andy Hung98ef9782014-03-04 14:46:50 -08003928 * Tracks with effects go into their own effects chain buffer
3929 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08003930 *
3931 * Other tracks can use mMixerBuffer for higher precision
3932 * channel accumulation. If this buffer is enabled
3933 * (mMixerBufferEnabled true), then selected tracks will accumulate
3934 * into it.
3935 *
3936 */
3937 if (mMixerBufferEnabled
3938 && (track->mainBuffer() == mSinkBuffer
3939 || track->mainBuffer() == mMixerBuffer)) {
3940 mAudioMixer->setParameter(
3941 name,
3942 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08003943 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08003944 mAudioMixer->setParameter(
3945 name,
3946 AudioMixer::TRACK,
3947 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
3948 // TODO: override track->mainBuffer()?
3949 mMixerBufferValid = true;
3950 } else {
3951 mAudioMixer->setParameter(
3952 name,
3953 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08003954 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08003955 mAudioMixer->setParameter(
3956 name,
3957 AudioMixer::TRACK,
3958 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3959 }
Eric Laurent81784c32012-11-19 14:55:58 -08003960 mAudioMixer->setParameter(
3961 name,
3962 AudioMixer::TRACK,
3963 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3964
3965 // reset retry count
3966 track->mRetryCount = kMaxTrackRetries;
3967
3968 // If one track is ready, set the mixer ready if:
3969 // - the mixer was not ready during previous round OR
3970 // - no other track is not ready
3971 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
3972 mixerStatus != MIXER_TRACKS_ENABLED) {
3973 mixerStatus = MIXER_TRACKS_READY;
3974 }
3975 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003976 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Glenn Kasten82aaf942013-07-17 16:05:07 -07003977 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003978 }
Eric Laurent81784c32012-11-19 14:55:58 -08003979 // clear effect chain input buffer if an active track underruns to avoid sending
3980 // previous audio buffer again to effects
3981 chain = getEffectChain_l(track->sessionId());
3982 if (chain != 0) {
3983 chain->clearInputBuffer();
3984 }
3985
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003986 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003987 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3988 track->isStopped() || track->isPaused()) {
3989 // We have consumed all the buffers of this track.
3990 // Remove it from the list of active tracks.
3991 // TODO: use actual buffer filling status instead of latency when available from
3992 // audio HAL
3993 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3994 size_t framesWritten = mBytesWritten / mFrameSize;
3995 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
3996 if (track->isStopped()) {
3997 track->reset();
3998 }
3999 tracksToRemove->add(track);
4000 }
4001 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08004002 // No buffers for this track. Give it a few chances to
4003 // fill a buffer, then remove it from active list.
4004 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004005 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004006 tracksToRemove->add(track);
4007 // indicate to client process that the track was disabled because of underrun;
4008 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07004009 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08004010 // If one track is not ready, mark the mixer also not ready if:
4011 // - the mixer was ready during previous round OR
4012 // - no other track is ready
4013 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
4014 mixerStatus != MIXER_TRACKS_READY) {
4015 mixerStatus = MIXER_TRACKS_ENABLED;
4016 }
4017 }
4018 mAudioMixer->disable(name);
4019 }
4020
4021 } // local variable scope to avoid goto warning
4022track_is_ready: ;
4023
4024 }
4025
4026 // Push the new FastMixer state if necessary
4027 bool pauseAudioWatchdog = false;
4028 if (didModify) {
4029 state->mFastTracksGen++;
4030 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4031 if (kUseFastMixer == FastMixer_Dynamic &&
4032 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4033 state->mCommand = FastMixerState::COLD_IDLE;
4034 state->mColdFutexAddr = &mFastMixerFutex;
4035 state->mColdGen++;
4036 mFastMixerFutex = 0;
4037 if (kUseFastMixer == FastMixer_Dynamic) {
4038 mNormalSink = mOutputSink;
4039 }
4040 // If we go into cold idle, need to wait for acknowledgement
4041 // so that fast mixer stops doing I/O.
4042 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4043 pauseAudioWatchdog = true;
4044 }
Eric Laurent81784c32012-11-19 14:55:58 -08004045 }
4046 if (sq != NULL) {
4047 sq->end(didModify);
4048 sq->push(block);
4049 }
4050#ifdef AUDIO_WATCHDOG
4051 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4052 mAudioWatchdog->pause();
4053 }
4054#endif
4055
4056 // Now perform the deferred reset on fast tracks that have stopped
4057 while (resetMask != 0) {
4058 size_t i = __builtin_ctz(resetMask);
4059 ALOG_ASSERT(i < count);
4060 resetMask &= ~(1 << i);
4061 sp<Track> t = mActiveTracks[i].promote();
4062 if (t == 0) {
4063 continue;
4064 }
4065 Track* track = t.get();
4066 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
4067 track->reset();
4068 }
4069
4070 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004071 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004072
Eric Laurent97d547d2014-09-02 14:45:53 -07004073 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
4074 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07004075 }
4076
4077 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07004078 // as long as there are effects we should clear the effects buffer, to avoid
4079 // passing a non-clean buffer to the effect chain
4080 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07004081 }
Andy Hung69aed5f2014-02-25 17:24:40 -08004082 // sink or mix buffer must be cleared if all tracks are connected to an
4083 // effect chain as in this case the mixer will not write to the sink or mix buffer
4084 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08004085 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4086 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08004087 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08004088 if (mMixerBufferValid) {
4089 memset(mMixerBuffer, 0, mMixerBufferSize);
4090 // TODO: In testing, mSinkBuffer below need not be cleared because
4091 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
4092 // after mixing.
4093 //
4094 // To enforce this guarantee:
4095 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4096 // (mixedTracks == 0 && fastTracks > 0))
4097 // must imply MIXER_TRACKS_READY.
4098 // Later, we may clear buffers regardless, and skip much of this logic.
4099 }
Andy Hung98ef9782014-03-04 14:46:50 -08004100 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07004101 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004102 }
4103
4104 // if any fast tracks, then status is ready
4105 mMixerStatusIgnoringFastTracks = mixerStatus;
4106 if (fastTracks > 0) {
4107 mixerStatus = MIXER_TRACKS_READY;
4108 }
4109 return mixerStatus;
4110}
4111
4112// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07004113int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
4114 audio_format_t format, int sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08004115{
Andy Hunge8a1ced2014-05-09 15:02:21 -07004116 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08004117}
4118
4119// deleteTrackName_l() must be called with ThreadBase::mLock held
4120void AudioFlinger::MixerThread::deleteTrackName_l(int name)
4121{
4122 ALOGV("remove track (%d) and delete from mixer", name);
4123 mAudioMixer->deleteTrackName(name);
4124}
4125
Eric Laurent10351942014-05-08 18:49:52 -07004126// checkForNewParameter_l() must be called with ThreadBase::mLock held
4127bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
4128 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004129{
Eric Laurent81784c32012-11-19 14:55:58 -08004130 bool reconfig = false;
4131
Eric Laurent10351942014-05-08 18:49:52 -07004132 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004133
Eric Laurent10351942014-05-08 18:49:52 -07004134 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
4135 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004136 if (mFastMixer != 0) {
Eric Laurent10351942014-05-08 18:49:52 -07004137 FastMixerStateQueue *sq = mFastMixer->sq();
4138 FastMixerState *state = sq->begin();
4139 if (!(state->mCommand & FastMixerState::IDLE)) {
4140 previousCommand = state->mCommand;
4141 state->mCommand = FastMixerState::HOT_IDLE;
4142 sq->end();
4143 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
4144 } else {
4145 sq->end(false /*didModify*/);
Eric Laurent81784c32012-11-19 14:55:58 -08004146 }
Eric Laurent10351942014-05-08 18:49:52 -07004147 }
Eric Laurent81784c32012-11-19 14:55:58 -08004148
Eric Laurent10351942014-05-08 18:49:52 -07004149 AudioParameter param = AudioParameter(keyValuePair);
4150 int value;
4151 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4152 reconfig = true;
4153 }
4154 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004155 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004156 status = BAD_VALUE;
4157 } else {
4158 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08004159 reconfig = true;
4160 }
Eric Laurent10351942014-05-08 18:49:52 -07004161 }
4162 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004163 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004164 status = BAD_VALUE;
4165 } else {
4166 // no need to save value, since it's constant
4167 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004168 }
Eric Laurent10351942014-05-08 18:49:52 -07004169 }
4170 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4171 // do not accept frame count changes if tracks are open as the track buffer
4172 // size depends on frame count and correct behavior would not be guaranteed
4173 // if frame count is changed after track creation
4174 if (!mTracks.isEmpty()) {
4175 status = INVALID_OPERATION;
4176 } else {
4177 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004178 }
Eric Laurent10351942014-05-08 18:49:52 -07004179 }
4180 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004181#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07004182 // when changing the audio output device, call addBatteryData to notify
4183 // the change
4184 if (mOutDevice != value) {
4185 uint32_t params = 0;
4186 // check whether speaker is on
4187 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
4188 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08004189 }
Eric Laurent10351942014-05-08 18:49:52 -07004190
4191 audio_devices_t deviceWithoutSpeaker
4192 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
4193 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07004194 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07004195 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4196 }
4197
4198 if (params != 0) {
4199 addBatteryData(params);
4200 }
4201 }
Eric Laurent81784c32012-11-19 14:55:58 -08004202#endif
4203
Eric Laurent10351942014-05-08 18:49:52 -07004204 // forward device change to effects that have requested to be
4205 // aware of attached audio device.
4206 if (value != AUDIO_DEVICE_NONE) {
4207 mOutDevice = value;
4208 for (size_t i = 0; i < mEffectChains.size(); i++) {
4209 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08004210 }
4211 }
Eric Laurent10351942014-05-08 18:49:52 -07004212 }
Eric Laurent81784c32012-11-19 14:55:58 -08004213
Eric Laurent10351942014-05-08 18:49:52 -07004214 if (status == NO_ERROR) {
4215 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4216 keyValuePair.string());
4217 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004218 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004219 mStandby = true;
4220 mBytesWritten = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004221 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Eric Laurent10351942014-05-08 18:49:52 -07004222 keyValuePair.string());
Eric Laurent81784c32012-11-19 14:55:58 -08004223 }
Eric Laurent10351942014-05-08 18:49:52 -07004224 if (status == NO_ERROR && reconfig) {
4225 readOutputParameters_l();
4226 delete mAudioMixer;
4227 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4228 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07004229 int name = getTrackName_l(mTracks[i]->mChannelMask,
4230 mTracks[i]->mFormat, mTracks[i]->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07004231 if (name < 0) {
4232 break;
4233 }
4234 mTracks[i]->mName = name;
4235 }
Eric Laurent73e26b62015-04-27 16:55:58 -07004236 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004237 }
Eric Laurent81784c32012-11-19 14:55:58 -08004238 }
4239
4240 if (!(previousCommand & FastMixerState::IDLE)) {
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004241 ALOG_ASSERT(mFastMixer != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08004242 FastMixerStateQueue *sq = mFastMixer->sq();
4243 FastMixerState *state = sq->begin();
4244 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
4245 state->mCommand = previousCommand;
4246 sq->end();
4247 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4248 }
4249
4250 return reconfig;
4251}
4252
4253
4254void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
4255{
4256 const size_t SIZE = 256;
4257 char buffer[SIZE];
4258 String8 result;
4259
4260 PlaybackThread::dumpInternals(fd, args);
4261
Elliott Hughes87cebad2014-05-22 10:14:43 -07004262 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Eric Laurent81784c32012-11-19 14:55:58 -08004263
4264 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten4182c4e2013-07-15 14:45:07 -07004265 const FastMixerDumpState copy(mFastMixerDumpState);
Eric Laurent81784c32012-11-19 14:55:58 -08004266 copy.dump(fd);
4267
4268#ifdef STATE_QUEUE_DUMP
4269 // Similar for state queue
4270 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4271 observerCopy.dump(fd);
4272 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4273 mutatorCopy.dump(fd);
4274#endif
4275
Glenn Kasten46909e72013-02-26 09:20:22 -08004276#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08004277 // Write the tee output to a .wav file
4278 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08004279#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004280
4281#ifdef AUDIO_WATCHDOG
4282 if (mAudioWatchdog != 0) {
4283 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4284 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4285 wdCopy.dump(fd);
4286 }
4287#endif
4288}
4289
4290uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4291{
4292 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4293}
4294
4295uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4296{
4297 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4298}
4299
4300void AudioFlinger::MixerThread::cacheParameters_l()
4301{
4302 PlaybackThread::cacheParameters_l();
4303
4304 // FIXME: Relaxed timing because of a certain device that can't meet latency
4305 // Should be reduced to 2x after the vendor fixes the driver issue
4306 // increase threshold again due to low power audio mode. The way this warning
4307 // threshold is calculated and its usefulness should be reconsidered anyway.
4308 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4309}
4310
4311// ----------------------------------------------------------------------------
4312
4313AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07004314 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device, bool systemReady)
4315 : PlaybackThread(audioFlinger, output, id, device, DIRECT, systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08004316 // mLeftVolFloat, mRightVolFloat
4317{
4318}
4319
Eric Laurentbfb1b832013-01-07 09:53:42 -08004320AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4321 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07004322 ThreadBase::type_t type, bool systemReady)
4323 : PlaybackThread(audioFlinger, output, id, device, type, systemReady)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004324 // mLeftVolFloat, mRightVolFloat
4325{
4326}
4327
Eric Laurent81784c32012-11-19 14:55:58 -08004328AudioFlinger::DirectOutputThread::~DirectOutputThread()
4329{
4330}
4331
Eric Laurentbfb1b832013-01-07 09:53:42 -08004332void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
4333{
4334 audio_track_cblk_t* cblk = track->cblk();
4335 float left, right;
4336
4337 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4338 left = right = 0;
4339 } else {
4340 float typeVolume = mStreamTypes[track->streamType()].volume;
4341 float v = mMasterVolume * typeVolume;
4342 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004343 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4344 left = float_from_gain(gain_minifloat_unpack_left(vlr));
4345 if (left > GAIN_FLOAT_UNITY) {
4346 left = GAIN_FLOAT_UNITY;
4347 }
4348 left *= v;
4349 right = float_from_gain(gain_minifloat_unpack_right(vlr));
4350 if (right > GAIN_FLOAT_UNITY) {
4351 right = GAIN_FLOAT_UNITY;
4352 }
4353 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004354 }
4355
4356 if (lastTrack) {
4357 if (left != mLeftVolFloat || right != mRightVolFloat) {
4358 mLeftVolFloat = left;
4359 mRightVolFloat = right;
4360
4361 // Convert volumes from float to 8.24
4362 uint32_t vl = (uint32_t)(left * (1 << 24));
4363 uint32_t vr = (uint32_t)(right * (1 << 24));
4364
4365 // Delegate volume control to effect in track effect chain if needed
4366 // only one effect chain can be present on DirectOutputThread, so if
4367 // there is one, the track is connected to it
4368 if (!mEffectChains.isEmpty()) {
4369 mEffectChains[0]->setVolume_l(&vl, &vr);
4370 left = (float)vl / (1 << 24);
4371 right = (float)vr / (1 << 24);
4372 }
4373 if (mOutput->stream->set_volume) {
4374 mOutput->stream->set_volume(mOutput->stream, left, right);
4375 }
4376 }
4377 }
4378}
4379
4380
Eric Laurent81784c32012-11-19 14:55:58 -08004381AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4382 Vector< sp<Track> > *tracksToRemove
4383)
4384{
Eric Laurentd595b7c2013-04-03 17:27:56 -07004385 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08004386 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004387 bool doHwPause = false;
4388 bool doHwResume = false;
4389 bool flushPending = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004390
4391 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07004392 for (size_t i = 0; i < count; i++) {
4393 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08004394 // The track died recently
4395 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004396 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08004397 }
4398
4399 Track* const track = t.get();
4400 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07004401 // Only consider last track started for volume and mixer state control.
4402 // In theory an older track could underrun and restart after the new one starts
4403 // but as we only care about the transition phase between two tracks on a
4404 // direct output, it is not a problem to ignore the underrun case.
4405 sp<Track> l = mLatestActiveTrack.promote();
4406 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08004407
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004408 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004409 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004410 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004411 doHwPause = true;
4412 mHwPaused = true;
4413 }
4414 tracksToRemove->add(track);
4415 } else if (track->isFlushPending()) {
4416 track->flushAck();
4417 if (last) {
4418 flushPending = true;
4419 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004420 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004421 track->resumeAck();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004422 if (last && mHwPaused) {
4423 doHwResume = true;
4424 mHwPaused = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004425 }
4426 }
4427
Eric Laurent81784c32012-11-19 14:55:58 -08004428 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08004429 // for all its buffers to be filled before processing it.
4430 // Allow draining the buffer in case the client
4431 // app does not call stop() and relies on underrun to stop:
4432 // hence the test on (track->mRetryCount > 1).
4433 // If retryCount<=1 then track is about to underrun and be removed.
Eric Laurent81784c32012-11-19 14:55:58 -08004434 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08004435 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
4436 && (track->mRetryCount > 1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004437 minFrames = mNormalFrameCount;
4438 } else {
4439 minFrames = 1;
4440 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004441
Eric Laurentab5cdba2014-06-09 17:22:27 -07004442 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4443 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08004444 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004445 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08004446
4447 if (track->mFillingUpStatus == Track::FS_FILLED) {
4448 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004449 // make sure processVolume_l() will apply new volume even if 0
4450 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004451 if (!mHwSupportsPause) {
4452 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08004453 }
4454 }
4455
4456 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004457 processVolume_l(track, last);
4458 if (last) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004459 // reset retry count
4460 track->mRetryCount = kMaxTrackRetriesDirect;
4461 mActiveTrack = t;
4462 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004463 if (usesHwAvSync() && mHwPaused) {
4464 doHwResume = true;
4465 mHwPaused = false;
4466 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004467 }
Eric Laurent81784c32012-11-19 14:55:58 -08004468 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004469 // clear effect chain input buffer if the last active track started underruns
4470 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07004471 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004472 mEffectChains[0]->clearInputBuffer();
4473 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004474 if (track->isStopping_1()) {
4475 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07004476 if (last && mHwPaused) {
4477 doHwResume = true;
4478 mHwPaused = false;
4479 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004480 }
4481 if ((track->sharedBuffer() != 0) || track->isStopped() ||
4482 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004483 // We have consumed all the buffers of this track.
4484 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07004485 size_t audioHALFrames;
4486 if (audio_is_linear_pcm(mFormat)) {
4487 audioHALFrames = (latency_l() * mSampleRate) / 1000;
4488 } else {
4489 audioHALFrames = 0;
4490 }
4491
Eric Laurent81784c32012-11-19 14:55:58 -08004492 size_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07004493 if (mStandby || !last ||
4494 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004495 if (track->isStopping_2()) {
4496 track->mState = TrackBase::STOPPED;
4497 }
Eric Laurent81784c32012-11-19 14:55:58 -08004498 if (track->isStopped()) {
4499 track->reset();
4500 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004501 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08004502 }
4503 } else {
4504 // No buffers for this track. Give it a few chances to
4505 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07004506 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08004507 if (--(track->mRetryCount) <= 0) {
4508 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07004509 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004510 // indicate to client process that the track was disabled because of underrun;
4511 // it will then automatically call start() when data is available
4512 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004513 } else if (last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004514 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004515 if (usesHwAvSync() && !mHwPaused && !mStandby) {
4516 doHwPause = true;
4517 mHwPaused = true;
4518 }
Eric Laurent81784c32012-11-19 14:55:58 -08004519 }
4520 }
4521 }
4522 }
4523
Eric Laurentd1f69b02014-12-15 14:33:13 -08004524 // if an active track did not command a flush, check for pending flush on stopped tracks
4525 if (!flushPending) {
4526 for (size_t i = 0; i < mTracks.size(); i++) {
4527 if (mTracks[i]->isFlushPending()) {
4528 mTracks[i]->flushAck();
4529 flushPending = true;
4530 }
4531 }
4532 }
4533
4534 // make sure the pause/flush/resume sequence is executed in the right order.
4535 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4536 // before flush and then resume HW. This can happen in case of pause/flush/resume
4537 // if resume is received before pause is executed.
4538 if (mHwSupportsPause && !mStandby &&
4539 (doHwPause || (flushPending && !mHwPaused && (count != 0)))) {
4540 mOutput->stream->pause(mOutput->stream);
4541 }
4542 if (flushPending) {
4543 flushHw_l();
4544 }
4545 if (mHwSupportsPause && !mStandby && doHwResume) {
4546 mOutput->stream->resume(mOutput->stream);
4547 }
Eric Laurent81784c32012-11-19 14:55:58 -08004548 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004549 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004550
4551 return mixerStatus;
4552}
4553
4554void AudioFlinger::DirectOutputThread::threadLoop_mix()
4555{
Eric Laurent81784c32012-11-19 14:55:58 -08004556 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08004557 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004558 // output audio to hardware
4559 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07004560 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004561 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08004562 status_t status = mActiveTrack->getNextBuffer(&buffer);
4563 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08004564 memset(curBuf, 0, frameCount * mFrameSize);
4565 break;
4566 }
4567 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
4568 frameCount -= buffer.frameCount;
4569 curBuf += buffer.frameCount * mFrameSize;
4570 mActiveTrack->releaseBuffer(&buffer);
4571 }
Andy Hung2098f272014-02-27 14:00:06 -08004572 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004573 sleepTime = 0;
4574 standbyTime = systemTime() + standbyDelay;
4575 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004576}
4577
4578void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
4579{
Eric Laurentd1f69b02014-12-15 14:33:13 -08004580 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004581 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004582 sleepTime = idleSleepTime;
4583 return;
4584 }
Eric Laurent81784c32012-11-19 14:55:58 -08004585 if (sleepTime == 0) {
4586 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4587 sleepTime = activeSleepTime;
4588 } else {
4589 sleepTime = idleSleepTime;
4590 }
4591 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08004592 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004593 sleepTime = 0;
4594 }
4595}
4596
Eric Laurentd1f69b02014-12-15 14:33:13 -08004597void AudioFlinger::DirectOutputThread::threadLoop_exit()
4598{
4599 {
4600 Mutex::Autolock _l(mLock);
4601 bool flushPending = false;
4602 for (size_t i = 0; i < mTracks.size(); i++) {
4603 if (mTracks[i]->isFlushPending()) {
4604 mTracks[i]->flushAck();
4605 flushPending = true;
4606 }
4607 }
4608 if (flushPending) {
4609 flushHw_l();
4610 }
4611 }
4612 PlaybackThread::threadLoop_exit();
4613}
4614
4615// must be called with thread mutex locked
4616bool AudioFlinger::DirectOutputThread::shouldStandby_l()
4617{
4618 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07004619 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004620
4621 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4622 // after a timeout and we will enter standby then.
4623 if (mTracks.size() > 0) {
4624 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07004625 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
4626 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004627 }
4628
Eric Laurentb369caf2015-03-30 20:51:47 -07004629 return !mStandby && !(trackPaused || (usesHwAvSync() && mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08004630}
4631
Eric Laurent81784c32012-11-19 14:55:58 -08004632// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004633int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Andy Hunge8a1ced2014-05-09 15:02:21 -07004634 audio_format_t format __unused, int sessionId __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004635{
4636 return 0;
4637}
4638
4639// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004640void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004641{
4642}
4643
Eric Laurent10351942014-05-08 18:49:52 -07004644// checkForNewParameter_l() must be called with ThreadBase::mLock held
4645bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
4646 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004647{
4648 bool reconfig = false;
4649
Eric Laurent10351942014-05-08 18:49:52 -07004650 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004651
Eric Laurent10351942014-05-08 18:49:52 -07004652 AudioParameter param = AudioParameter(keyValuePair);
4653 int value;
4654 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4655 // forward device change to effects that have requested to be
4656 // aware of attached audio device.
4657 if (value != AUDIO_DEVICE_NONE) {
4658 mOutDevice = value;
4659 for (size_t i = 0; i < mEffectChains.size(); i++) {
4660 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07004661 }
4662 }
Eric Laurent81784c32012-11-19 14:55:58 -08004663 }
Eric Laurent10351942014-05-08 18:49:52 -07004664 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4665 // do not accept frame count changes if tracks are open as the track buffer
4666 // size depends on frame count and correct behavior would not be garantied
4667 // if frame count is changed after track creation
4668 if (!mTracks.isEmpty()) {
4669 status = INVALID_OPERATION;
4670 } else {
4671 reconfig = true;
4672 }
4673 }
4674 if (status == NO_ERROR) {
4675 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4676 keyValuePair.string());
4677 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004678 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004679 mStandby = true;
4680 mBytesWritten = 0;
4681 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4682 keyValuePair.string());
4683 }
4684 if (status == NO_ERROR && reconfig) {
4685 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07004686 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004687 }
4688 }
4689
Eric Laurent81784c32012-11-19 14:55:58 -08004690 return reconfig;
4691}
4692
4693uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
4694{
4695 uint32_t time;
4696 if (audio_is_linear_pcm(mFormat)) {
4697 time = PlaybackThread::activeSleepTimeUs();
4698 } else {
4699 time = 10000;
4700 }
4701 return time;
4702}
4703
4704uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
4705{
4706 uint32_t time;
4707 if (audio_is_linear_pcm(mFormat)) {
4708 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
4709 } else {
4710 time = 10000;
4711 }
4712 return time;
4713}
4714
4715uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
4716{
4717 uint32_t time;
4718 if (audio_is_linear_pcm(mFormat)) {
4719 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
4720 } else {
4721 time = 10000;
4722 }
4723 return time;
4724}
4725
4726void AudioFlinger::DirectOutputThread::cacheParameters_l()
4727{
4728 PlaybackThread::cacheParameters_l();
4729
4730 // use shorter standby delay as on normal output to release
4731 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07004732 // no delay on outputs with HW A/V sync
4733 if (usesHwAvSync()) {
4734 standbyDelay = 0;
4735 } else if (audio_is_linear_pcm(mFormat)) {
Eric Laurent972a1732013-09-04 09:42:59 -07004736 standbyDelay = microseconds(activeSleepTime*2);
4737 } else {
4738 standbyDelay = kOffloadStandbyDelayNs;
4739 }
Eric Laurent81784c32012-11-19 14:55:58 -08004740}
4741
Eric Laurente659ef42014-09-29 13:06:46 -07004742void AudioFlinger::DirectOutputThread::flushHw_l()
4743{
Phil Burk062e67a2015-02-11 13:40:50 -08004744 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08004745 mHwPaused = false;
Eric Laurente659ef42014-09-29 13:06:46 -07004746}
4747
Eric Laurent81784c32012-11-19 14:55:58 -08004748// ----------------------------------------------------------------------------
4749
Eric Laurentbfb1b832013-01-07 09:53:42 -08004750AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07004751 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004752 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07004753 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07004754 mWriteAckSequence(0),
4755 mDrainSequence(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004756{
4757}
4758
4759AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
4760{
4761}
4762
4763void AudioFlinger::AsyncCallbackThread::onFirstRef()
4764{
4765 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
4766}
4767
4768bool AudioFlinger::AsyncCallbackThread::threadLoop()
4769{
4770 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004771 uint32_t writeAckSequence;
4772 uint32_t drainSequence;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004773
4774 {
4775 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08004776 while (!((mWriteAckSequence & 1) ||
4777 (mDrainSequence & 1) ||
4778 exitPending())) {
4779 mWaitWorkCV.wait(mLock);
4780 }
4781
Eric Laurentbfb1b832013-01-07 09:53:42 -08004782 if (exitPending()) {
4783 break;
4784 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004785 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
4786 mWriteAckSequence, mDrainSequence);
4787 writeAckSequence = mWriteAckSequence;
4788 mWriteAckSequence &= ~1;
4789 drainSequence = mDrainSequence;
4790 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004791 }
4792 {
Eric Laurent4de95592013-09-26 15:28:21 -07004793 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
4794 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004795 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004796 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004797 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004798 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004799 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004800 }
4801 }
4802 }
4803 }
4804 return false;
4805}
4806
4807void AudioFlinger::AsyncCallbackThread::exit()
4808{
4809 ALOGV("AsyncCallbackThread::exit");
4810 Mutex::Autolock _l(mLock);
4811 requestExit();
4812 mWaitWorkCV.broadcast();
4813}
4814
Eric Laurent3b4529e2013-09-05 18:09:19 -07004815void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004816{
4817 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004818 // bit 0 is cleared
4819 mWriteAckSequence = sequence << 1;
4820}
4821
4822void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
4823{
4824 Mutex::Autolock _l(mLock);
4825 // ignore unexpected callbacks
4826 if (mWriteAckSequence & 2) {
4827 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004828 mWaitWorkCV.signal();
4829 }
4830}
4831
Eric Laurent3b4529e2013-09-05 18:09:19 -07004832void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004833{
4834 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004835 // bit 0 is cleared
4836 mDrainSequence = sequence << 1;
4837}
4838
4839void AudioFlinger::AsyncCallbackThread::resetDraining()
4840{
4841 Mutex::Autolock _l(mLock);
4842 // ignore unexpected callbacks
4843 if (mDrainSequence & 2) {
4844 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004845 mWaitWorkCV.signal();
4846 }
4847}
4848
4849
4850// ----------------------------------------------------------------------------
4851AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07004852 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady)
4853 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady),
Eric Laurentd7e59222013-11-15 12:02:28 -08004854 mPausedBytesRemaining(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004855{
Eric Laurentfd477972013-10-25 18:10:40 -07004856 //FIXME: mStandby should be set to true by ThreadBase constructor
4857 mStandby = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004858}
4859
Eric Laurentbfb1b832013-01-07 09:53:42 -08004860void AudioFlinger::OffloadThread::threadLoop_exit()
4861{
4862 if (mFlushPending || mHwPaused) {
4863 // If a flush is pending or track was paused, just discard buffered data
4864 flushHw_l();
4865 } else {
4866 mMixerStatus = MIXER_DRAIN_ALL;
4867 threadLoop_drain();
4868 }
Uday Gupta56604aa2014-05-13 11:19:17 -07004869 if (mUseAsyncWrite) {
4870 ALOG_ASSERT(mCallbackThread != 0);
4871 mCallbackThread->exit();
4872 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004873 PlaybackThread::threadLoop_exit();
4874}
4875
4876AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
4877 Vector< sp<Track> > *tracksToRemove
4878)
4879{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004880 size_t count = mActiveTracks.size();
4881
4882 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07004883 bool doHwPause = false;
4884 bool doHwResume = false;
4885
Eric Laurentede6c3b2013-09-19 14:37:46 -07004886 ALOGV("OffloadThread::prepareTracks_l active tracks %d", count);
4887
Eric Laurentbfb1b832013-01-07 09:53:42 -08004888 // find out which tracks need to be processed
4889 for (size_t i = 0; i < count; i++) {
4890 sp<Track> t = mActiveTracks[i].promote();
4891 // The track died recently
4892 if (t == 0) {
4893 continue;
4894 }
4895 Track* const track = t.get();
4896 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07004897 // Only consider last track started for volume and mixer state control.
4898 // In theory an older track could underrun and restart after the new one starts
4899 // but as we only care about the transition phase between two tracks on a
4900 // direct output, it is not a problem to ignore the underrun case.
4901 sp<Track> l = mLatestActiveTrack.promote();
4902 bool last = l.get() == track;
4903
Haynes Mathew George7844f672014-01-15 12:32:55 -08004904 if (track->isInvalid()) {
4905 ALOGW("An invalidated track shouldn't be in active list");
4906 tracksToRemove->add(track);
4907 continue;
4908 }
4909
4910 if (track->mState == TrackBase::IDLE) {
4911 ALOGW("An idle track shouldn't be in active list");
4912 continue;
4913 }
4914
Eric Laurentbfb1b832013-01-07 09:53:42 -08004915 if (track->isPausing()) {
4916 track->setPaused();
4917 if (last) {
4918 if (!mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07004919 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004920 mHwPaused = true;
4921 }
4922 // If we were part way through writing the mixbuffer to
4923 // the HAL we must save this until we resume
4924 // BUG - this will be wrong if a different track is made active,
4925 // in that case we want to discard the pending data in the
4926 // mixbuffer and tell the client to present it again when the
4927 // track is resumed
4928 mPausedWriteLength = mCurrentWriteLength;
4929 mPausedBytesRemaining = mBytesRemaining;
4930 mBytesRemaining = 0; // stop writing
4931 }
4932 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08004933 } else if (track->isFlushPending()) {
4934 track->flushAck();
4935 if (last) {
4936 mFlushPending = true;
4937 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08004938 } else if (track->isResumePending()){
4939 track->resumeAck();
4940 if (last) {
4941 if (mPausedBytesRemaining) {
4942 // Need to continue write that was interrupted
4943 mCurrentWriteLength = mPausedWriteLength;
4944 mBytesRemaining = mPausedBytesRemaining;
4945 mPausedBytesRemaining = 0;
4946 }
4947 if (mHwPaused) {
4948 doHwResume = true;
4949 mHwPaused = false;
4950 // threadLoop_mix() will handle the case that we need to
4951 // resume an interrupted write
4952 }
4953 // enable write to audio HAL
4954 sleepTime = 0;
4955
4956 // Do not handle new data in this iteration even if track->framesReady()
4957 mixerStatus = MIXER_TRACKS_ENABLED;
4958 }
4959 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07004960 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004961 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004962 if (track->mFillingUpStatus == Track::FS_FILLED) {
4963 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004964 // make sure processVolume_l() will apply new volume even if 0
4965 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004966 }
4967
4968 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08004969 sp<Track> previousTrack = mPreviousTrack.promote();
4970 if (previousTrack != 0) {
4971 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08004972 // Flush any data still being written from last track
4973 mBytesRemaining = 0;
4974 if (mPausedBytesRemaining) {
4975 // Last track was paused so we also need to flush saved
4976 // mixbuffer state and invalidate track so that it will
4977 // re-submit that unwritten data when it is next resumed
4978 mPausedBytesRemaining = 0;
4979 // Invalidate is a bit drastic - would be more efficient
4980 // to have a flag to tell client that some of the
4981 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08004982 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004983 }
4984 // flush data already sent to the DSP if changing audio session as audio
4985 // comes from a different source. Also invalidate previous track to force a
4986 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08004987 if (previousTrack->sessionId() != track->sessionId()) {
4988 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004989 }
4990 }
4991 }
4992 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004993 // reset retry count
4994 track->mRetryCount = kMaxTrackRetriesOffload;
4995 mActiveTrack = t;
4996 mixerStatus = MIXER_TRACKS_READY;
4997 }
4998 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004999 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005000 if (track->isStopping_1()) {
5001 // Hardware buffer can hold a large amount of audio so we must
5002 // wait for all current track's data to drain before we say
5003 // that the track is stopped.
5004 if (mBytesRemaining == 0) {
5005 // Only start draining when all data in mixbuffer
5006 // has been written
5007 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
5008 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005009 // do not drain if no data was ever sent to HAL (mStandby == true)
5010 if (last && !mStandby) {
Eric Laurent1b9f9b12013-11-12 19:10:17 -08005011 // do not modify drain sequence if we are already draining. This happens
5012 // when resuming from pause after drain.
5013 if ((mDrainSequence & 1) == 0) {
5014 sleepTime = 0;
5015 standbyTime = systemTime() + standbyDelay;
5016 mixerStatus = MIXER_DRAIN_TRACK;
5017 mDrainSequence += 2;
5018 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005019 if (mHwPaused) {
5020 // It is possible to move from PAUSED to STOPPING_1 without
5021 // a resume so we must ensure hardware is running
Eric Laurent1b9f9b12013-11-12 19:10:17 -08005022 doHwResume = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005023 mHwPaused = false;
5024 }
5025 }
5026 }
5027 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005028 // Drain has completed or we are in standby, signal presentation complete
5029 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005030 track->mState = TrackBase::STOPPED;
5031 size_t audioHALFrames =
5032 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
5033 size_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08005034 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005035 track->presentationComplete(framesWritten, audioHALFrames);
5036 track->reset();
5037 tracksToRemove->add(track);
5038 }
5039 } else {
5040 // No buffers for this track. Give it a few chances to
5041 // fill a buffer, then remove it from active list.
5042 if (--(track->mRetryCount) <= 0) {
5043 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
5044 track->name());
5045 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08005046 // indicate to client process that the track was disabled because of underrun;
5047 // it will then automatically call start() when data is available
5048 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005049 } else if (last){
5050 mixerStatus = MIXER_TRACKS_ENABLED;
5051 }
5052 }
5053 }
5054 // compute volume for this track
5055 processVolume_l(track, last);
5056 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005057
Eric Laurentea0fade2013-10-04 16:23:48 -07005058 // make sure the pause/flush/resume sequence is executed in the right order.
5059 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5060 // before flush and then resume HW. This can happen in case of pause/flush/resume
5061 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07005062 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurent972a1732013-09-04 09:42:59 -07005063 mOutput->stream->pause(mOutput->stream);
5064 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005065 if (mFlushPending) {
5066 flushHw_l();
5067 mFlushPending = false;
5068 }
Eric Laurentfd477972013-10-25 18:10:40 -07005069 if (!mStandby && doHwResume) {
Eric Laurent972a1732013-09-04 09:42:59 -07005070 mOutput->stream->resume(mOutput->stream);
5071 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005072
Eric Laurentbfb1b832013-01-07 09:53:42 -08005073 // remove all the tracks that need to be...
5074 removeTracks_l(*tracksToRemove);
5075
5076 return mixerStatus;
5077}
5078
Eric Laurentbfb1b832013-01-07 09:53:42 -08005079// must be called with thread mutex locked
5080bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
5081{
Eric Laurent3b4529e2013-09-05 18:09:19 -07005082 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
5083 mWriteAckSequence, mDrainSequence);
5084 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005085 return true;
5086 }
5087 return false;
5088}
5089
Eric Laurentbfb1b832013-01-07 09:53:42 -08005090bool AudioFlinger::OffloadThread::waitingAsyncCallback()
5091{
5092 Mutex::Autolock _l(mLock);
5093 return waitingAsyncCallback_l();
5094}
5095
5096void AudioFlinger::OffloadThread::flushHw_l()
5097{
Eric Laurente659ef42014-09-29 13:06:46 -07005098 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005099 // Flush anything still waiting in the mixbuffer
5100 mCurrentWriteLength = 0;
5101 mBytesRemaining = 0;
5102 mPausedWriteLength = 0;
5103 mPausedBytesRemaining = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08005104
Eric Laurentbfb1b832013-01-07 09:53:42 -08005105 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005106 // discard any pending drain or write ack by incrementing sequence
5107 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5108 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005109 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005110 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5111 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005112 }
5113}
5114
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08005115void AudioFlinger::OffloadThread::onAddNewTrack_l()
5116{
5117 sp<Track> previousTrack = mPreviousTrack.promote();
5118 sp<Track> latestTrack = mLatestActiveTrack.promote();
5119
5120 if (previousTrack != 0 && latestTrack != 0 &&
5121 (previousTrack->sessionId() != latestTrack->sessionId())) {
5122 mFlushPending = true;
5123 }
5124 PlaybackThread::onAddNewTrack_l();
5125}
5126
Eric Laurentbfb1b832013-01-07 09:53:42 -08005127// ----------------------------------------------------------------------------
5128
Eric Laurent81784c32012-11-19 14:55:58 -08005129AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07005130 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08005131 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
Eric Laurent72e3f392015-05-20 14:43:50 -07005132 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08005133 mWaitTimeMs(UINT_MAX)
5134{
5135 addOutputTrack(mainThread);
5136}
5137
5138AudioFlinger::DuplicatingThread::~DuplicatingThread()
5139{
5140 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5141 mOutputTracks[i]->destroy();
5142 }
5143}
5144
5145void AudioFlinger::DuplicatingThread::threadLoop_mix()
5146{
5147 // mix buffers...
5148 if (outputsReady(outputTracks)) {
5149 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
5150 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08005151 if (mMixerBufferValid) {
5152 memset(mMixerBuffer, 0, mMixerBufferSize);
5153 } else {
5154 memset(mSinkBuffer, 0, mSinkBufferSize);
5155 }
Eric Laurent81784c32012-11-19 14:55:58 -08005156 }
5157 sleepTime = 0;
5158 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005159 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005160 standbyTime = systemTime() + standbyDelay;
5161}
5162
5163void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
5164{
5165 if (sleepTime == 0) {
5166 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5167 sleepTime = activeSleepTime;
5168 } else {
5169 sleepTime = idleSleepTime;
5170 }
5171 } else if (mBytesWritten != 0) {
5172 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5173 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005174 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005175 } else {
5176 // flush remaining overflow buffers in output tracks
5177 writeFrames = 0;
5178 }
5179 sleepTime = 0;
5180 }
5181}
5182
Eric Laurentbfb1b832013-01-07 09:53:42 -08005183ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005184{
5185 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08005186 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005187 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07005188 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08005189 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005190}
5191
5192void AudioFlinger::DuplicatingThread::threadLoop_standby()
5193{
5194 // DuplicatingThread implements standby by stopping all tracks
5195 for (size_t i = 0; i < outputTracks.size(); i++) {
5196 outputTracks[i]->stop();
5197 }
5198}
5199
5200void AudioFlinger::DuplicatingThread::saveOutputTracks()
5201{
5202 outputTracks = mOutputTracks;
5203}
5204
5205void AudioFlinger::DuplicatingThread::clearOutputTracks()
5206{
5207 outputTracks.clear();
5208}
5209
5210void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
5211{
5212 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08005213 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
5214 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
5215 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
5216 const size_t frameCount =
5217 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
5218 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
5219 // from different OutputTracks and their associated MixerThreads (e.g. one may
5220 // nearly empty and the other may be dropping data).
5221
5222 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08005223 this,
5224 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08005225 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08005226 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005227 frameCount,
5228 IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08005229 if (outputTrack->cblk() != NULL) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005230 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
Eric Laurent81784c32012-11-19 14:55:58 -08005231 mOutputTracks.add(outputTrack);
Andy Hungc25b84a2015-01-14 19:04:10 -08005232 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005233 updateWaitTime_l();
5234 }
5235}
5236
5237void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
5238{
5239 Mutex::Autolock _l(mLock);
5240 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5241 if (mOutputTracks[i]->thread() == thread) {
5242 mOutputTracks[i]->destroy();
5243 mOutputTracks.removeAt(i);
5244 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07005245 if (thread->getOutput() == mOutput) {
5246 mOutput = NULL;
5247 }
Eric Laurent81784c32012-11-19 14:55:58 -08005248 return;
5249 }
5250 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07005251 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005252}
5253
5254// caller must hold mLock
5255void AudioFlinger::DuplicatingThread::updateWaitTime_l()
5256{
5257 mWaitTimeMs = UINT_MAX;
5258 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5259 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
5260 if (strong != 0) {
5261 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
5262 if (waitTimeMs < mWaitTimeMs) {
5263 mWaitTimeMs = waitTimeMs;
5264 }
5265 }
5266 }
5267}
5268
5269
5270bool AudioFlinger::DuplicatingThread::outputsReady(
5271 const SortedVector< sp<OutputTrack> > &outputTracks)
5272{
5273 for (size_t i = 0; i < outputTracks.size(); i++) {
5274 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
5275 if (thread == 0) {
5276 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
5277 outputTracks[i].get());
5278 return false;
5279 }
5280 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5281 // see note at standby() declaration
5282 if (playbackThread->standby() && !playbackThread->isSuspended()) {
5283 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
5284 thread.get());
5285 return false;
5286 }
5287 }
5288 return true;
5289}
5290
5291uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
5292{
5293 return (mWaitTimeMs * 1000) / 2;
5294}
5295
5296void AudioFlinger::DuplicatingThread::cacheParameters_l()
5297{
5298 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
5299 updateWaitTime_l();
5300
5301 MixerThread::cacheParameters_l();
5302}
5303
5304// ----------------------------------------------------------------------------
5305// Record
5306// ----------------------------------------------------------------------------
5307
5308AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5309 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08005310 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08005311 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07005312 audio_devices_t inDevice,
5313 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08005314#ifdef TEE_SINK
5315 , const sp<NBAIO_Sink>& teeSink
5316#endif
5317 ) :
Eric Laurent72e3f392015-05-20 14:43:50 -07005318 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005319 mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005320 // mRsmpInFrames and mRsmpInFramesP2 are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005321 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08005322#ifdef TEE_SINK
5323 , mTeeSink(teeSink)
5324#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07005325 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
5326 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005327 // mFastCapture below
5328 , mFastCaptureFutex(0)
5329 // mInputSource
5330 // mPipeSink
5331 // mPipeSource
5332 , mPipeFramesP2(0)
5333 // mPipeMemory
5334 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005335 , mFastTrackAvail(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005336{
Glenn Kastend7dca052015-03-05 16:05:54 -08005337 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
5338 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08005339
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005340 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005341
5342 // create an NBAIO source for the HAL input stream, and negotiate
5343 mInputSource = new AudioStreamInSource(input->stream);
5344 size_t numCounterOffers = 0;
5345 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
5346 ssize_t index = mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
5347 ALOG_ASSERT(index == 0);
5348
5349 // initialize fast capture depending on configuration
5350 bool initFastCapture;
5351 switch (kUseFastCapture) {
5352 case FastCapture_Never:
5353 initFastCapture = false;
5354 break;
5355 case FastCapture_Always:
5356 initFastCapture = true;
5357 break;
5358 case FastCapture_Static:
5359 uint32_t primaryOutputSampleRate;
5360 {
5361 AutoMutex _l(audioFlinger->mHardwareLock);
5362 primaryOutputSampleRate = audioFlinger->mPrimaryOutputSampleRate;
5363 }
5364 initFastCapture =
5365 // either capture sample rate is same as (a reasonable) primary output sample rate
Andy Hungdb4c0312015-05-06 08:46:52 -07005366 ((isMusicRate(primaryOutputSampleRate) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005367 (mSampleRate == primaryOutputSampleRate)) ||
5368 // or primary output sample rate is unknown, and capture sample rate is reasonable
5369 ((primaryOutputSampleRate == 0) &&
Andy Hungdb4c0312015-05-06 08:46:52 -07005370 isMusicRate(mSampleRate))) &&
Glenn Kasten9f81de32014-07-27 15:02:23 -07005371 // and the buffer size is < 12 ms
5372 (mFrameCount * 1000) / mSampleRate < 12;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005373 break;
5374 // case FastCapture_Dynamic:
5375 }
5376
5377 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07005378 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005379 NBAIO_Format format = mInputSource->format();
Glenn Kasten49d00ad2014-07-21 11:22:03 -07005380 size_t pipeFramesP2 = roundup(mSampleRate / 25); // double-buffering of 20 ms each
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005381 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
5382 void *pipeBuffer;
5383 const sp<MemoryDealer> roHeap(readOnlyHeap());
5384 sp<IMemory> pipeMemory;
5385 if ((roHeap == 0) ||
5386 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
5387 (pipeBuffer = pipeMemory->pointer()) == NULL) {
5388 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
5389 goto failed;
5390 }
5391 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
5392 memset(pipeBuffer, 0, pipeSize);
5393 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
5394 const NBAIO_Format offers[1] = {format};
5395 size_t numCounterOffers = 0;
5396 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
5397 ALOG_ASSERT(index == 0);
5398 mPipeSink = pipe;
5399 PipeReader *pipeReader = new PipeReader(*pipe);
5400 numCounterOffers = 0;
5401 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
5402 ALOG_ASSERT(index == 0);
5403 mPipeSource = pipeReader;
5404 mPipeFramesP2 = pipeFramesP2;
5405 mPipeMemory = pipeMemory;
5406
5407 // create fast capture
5408 mFastCapture = new FastCapture();
5409 FastCaptureStateQueue *sq = mFastCapture->sq();
5410#ifdef STATE_QUEUE_DUMP
5411 // FIXME
5412#endif
5413 FastCaptureState *state = sq->begin();
5414 state->mCblk = NULL;
5415 state->mInputSource = mInputSource.get();
5416 state->mInputSourceGen++;
5417 state->mPipeSink = pipe;
5418 state->mPipeSinkGen++;
5419 state->mFrameCount = mFrameCount;
5420 state->mCommand = FastCaptureState::COLD_IDLE;
5421 // already done in constructor initialization list
5422 //mFastCaptureFutex = 0;
5423 state->mColdFutexAddr = &mFastCaptureFutex;
5424 state->mColdGen++;
5425 state->mDumpState = &mFastCaptureDumpState;
5426#ifdef TEE_SINK
5427 // FIXME
5428#endif
5429 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
5430 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
5431 sq->end();
5432 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5433
5434 // start the fast capture
5435 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
5436 pid_t tid = mFastCapture->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07005437 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005438#ifdef AUDIO_WATCHDOG
5439 // FIXME
5440#endif
5441
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005442 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005443 }
5444failed: ;
5445
5446 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08005447}
5448
Eric Laurent81784c32012-11-19 14:55:58 -08005449AudioFlinger::RecordThread::~RecordThread()
5450{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005451 if (mFastCapture != 0) {
5452 FastCaptureStateQueue *sq = mFastCapture->sq();
5453 FastCaptureState *state = sq->begin();
5454 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5455 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5456 if (old == -1) {
5457 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5458 }
5459 }
5460 state->mCommand = FastCaptureState::EXIT;
5461 sq->end();
5462 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5463 mFastCapture->join();
5464 mFastCapture.clear();
5465 }
5466 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07005467 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07005468 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08005469}
5470
5471void AudioFlinger::RecordThread::onFirstRef()
5472{
Glenn Kastend7dca052015-03-05 16:05:54 -08005473 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08005474}
5475
Eric Laurent81784c32012-11-19 14:55:58 -08005476bool AudioFlinger::RecordThread::threadLoop()
5477{
Eric Laurent81784c32012-11-19 14:55:58 -08005478 nsecs_t lastWarning = 0;
5479
5480 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08005481
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005482reacquire_wakelock:
5483 sp<RecordTrack> activeTrack;
Glenn Kasten2b806402013-11-20 16:37:38 -08005484 int activeTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005485 {
5486 Mutex::Autolock _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005487 size_t size = mActiveTracks.size();
5488 activeTracksGen = mActiveTracksGen;
5489 if (size > 0) {
5490 // FIXME an arbitrary choice
5491 activeTrack = mActiveTracks[0];
5492 acquireWakeLock_l(activeTrack->uid());
5493 if (size > 1) {
5494 SortedVector<int> tmp;
5495 for (size_t i = 0; i < size; i++) {
5496 tmp.add(mActiveTracks[i]->uid());
5497 }
5498 updateWakeLockUids_l(tmp);
5499 }
5500 } else {
5501 acquireWakeLock_l(-1);
5502 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005503 }
5504
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005505 // used to request a deferred sleep, to be executed later while mutex is unlocked
5506 uint32_t sleepUs = 0;
5507
5508 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005509 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005510 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07005511
Glenn Kasten5edadd42013-08-14 16:30:49 -07005512 // sleep with mutex unlocked
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005513 if (sleepUs > 0) {
Glenn Kastene7754022014-10-31 12:11:26 -07005514 ATRACE_BEGIN("sleep");
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005515 usleep(sleepUs);
Glenn Kastene7754022014-10-31 12:11:26 -07005516 ATRACE_END();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005517 sleepUs = 0;
Glenn Kasten5edadd42013-08-14 16:30:49 -07005518 }
5519
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005520 // activeTracks accumulates a copy of a subset of mActiveTracks
5521 Vector< sp<RecordTrack> > activeTracks;
5522
Glenn Kasten735f45f2014-08-18 15:51:59 -07005523 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005524 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07005525
Glenn Kasten735f45f2014-08-18 15:51:59 -07005526 // reference to a fast track which is about to be removed
5527 sp<RecordTrack> fastTrackToRemove;
5528
Eric Laurent81784c32012-11-19 14:55:58 -08005529 { // scope for mLock
5530 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08005531
Eric Laurent021cf962014-05-13 10:18:14 -07005532 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005533
Eric Laurent000a4192014-01-29 15:17:32 -08005534 // check exitPending here because checkForNewParameters_l() and
5535 // checkForNewParameters_l() can temporarily release mLock
5536 if (exitPending()) {
5537 break;
5538 }
5539
Glenn Kasten2b806402013-11-20 16:37:38 -08005540 // if no active track(s), then standby and release wakelock
5541 size_t size = mActiveTracks.size();
5542 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07005543 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005544 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08005545 releaseWakeLock_l();
5546 ALOGV("RecordThread: loop stopping");
5547 // go to sleep
5548 mWaitWorkCV.wait(mLock);
5549 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005550 goto reacquire_wakelock;
5551 }
5552
Glenn Kasten2b806402013-11-20 16:37:38 -08005553 if (mActiveTracksGen != activeTracksGen) {
5554 activeTracksGen = mActiveTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005555 SortedVector<int> tmp;
Glenn Kasten2b806402013-11-20 16:37:38 -08005556 for (size_t i = 0; i < size; i++) {
5557 tmp.add(mActiveTracks[i]->uid());
5558 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005559 updateWakeLockUids_l(tmp);
Eric Laurent81784c32012-11-19 14:55:58 -08005560 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005561
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005562 bool doBroadcast = false;
5563 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07005564
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005565 activeTrack = mActiveTracks[i];
5566 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07005567 if (activeTrack->isFastTrack()) {
5568 ALOG_ASSERT(fastTrackToRemove == 0);
5569 fastTrackToRemove = activeTrack;
5570 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005571 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08005572 mActiveTracks.remove(activeTrack);
5573 mActiveTracksGen++;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005574 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07005575 continue;
5576 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005577
5578 TrackBase::track_state activeTrackState = activeTrack->mState;
5579 switch (activeTrackState) {
5580
5581 case TrackBase::PAUSING:
5582 mActiveTracks.remove(activeTrack);
5583 mActiveTracksGen++;
5584 doBroadcast = true;
5585 size--;
5586 continue;
5587
5588 case TrackBase::STARTING_1:
5589 sleepUs = 10000;
5590 i++;
5591 continue;
5592
5593 case TrackBase::STARTING_2:
5594 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005595 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07005596 activeTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005597 break;
5598
5599 case TrackBase::ACTIVE:
5600 break;
5601
5602 case TrackBase::IDLE:
5603 i++;
5604 continue;
5605
5606 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08005607 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07005608 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005609
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005610 activeTracks.add(activeTrack);
5611 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07005612
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005613 if (activeTrack->isFastTrack()) {
5614 ALOG_ASSERT(!mFastTrackAvail);
5615 ALOG_ASSERT(fastTrack == 0);
5616 fastTrack = activeTrack;
5617 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005618 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005619 if (doBroadcast) {
5620 mStartStopCond.broadcast();
5621 }
5622
5623 // sleep if there are no active tracks to process
5624 if (activeTracks.size() == 0) {
5625 if (sleepUs == 0) {
5626 sleepUs = kRecordThreadSleepUs;
5627 }
5628 continue;
5629 }
5630 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07005631
Eric Laurent81784c32012-11-19 14:55:58 -08005632 lockEffectChains_l(effectChains);
5633 }
5634
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005635 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07005636
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005637 size_t size = effectChains.size();
5638 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005639 // thread mutex is not locked, but effect chain is locked
5640 effectChains[i]->process_l();
5641 }
5642
Glenn Kasten735f45f2014-08-18 15:51:59 -07005643 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005644 if (mFastCapture != 0) {
5645 FastCaptureStateQueue *sq = mFastCapture->sq();
5646 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07005647 bool didModify = false;
5648 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005649 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
5650 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
5651 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5652 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5653 if (old == -1) {
5654 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5655 }
5656 }
5657 state->mCommand = FastCaptureState::READ_WRITE;
5658#if 0 // FIXME
5659 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08005660 FastThreadDumpState::kSamplingNforLowRamDevice :
5661 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005662#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07005663 didModify = true;
5664 }
5665 audio_track_cblk_t *cblkOld = state->mCblk;
5666 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
5667 if (cblkNew != cblkOld) {
5668 state->mCblk = cblkNew;
5669 // block until acked if removing a fast track
5670 if (cblkOld != NULL) {
5671 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
5672 }
5673 didModify = true;
5674 }
5675 sq->end(didModify);
5676 if (didModify) {
5677 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005678#if 0
5679 if (kUseFastCapture == FastCapture_Dynamic) {
5680 mNormalSource = mPipeSource;
5681 }
5682#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005683 }
5684 }
5685
Glenn Kasten735f45f2014-08-18 15:51:59 -07005686 // now run the fast track destructor with thread mutex unlocked
5687 fastTrackToRemove.clear();
5688
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005689 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
5690 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
5691 // slow, then this RecordThread will overrun by not calling HAL read often enough.
5692 // If destination is non-contiguous, first read past the nominal end of buffer, then
5693 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005694
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005695 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005696 ssize_t framesRead;
5697
5698 // If an NBAIO source is present, use it to read the normal capture's data
5699 if (mPipeSource != 0) {
5700 size_t framesToRead = mBufferSize / mFrameSize;
Andy Hung57446612015-04-19 23:56:46 -07005701 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005702 framesToRead, AudioBufferProvider::kInvalidPTS);
5703 if (framesRead == 0) {
5704 // since pipe is non-blocking, simulate blocking input
5705 sleepUs = (framesToRead * 1000000LL) / mSampleRate;
5706 }
5707 // otherwise use the HAL / AudioStreamIn directly
5708 } else {
5709 ssize_t bytesRead = mInput->stream->read(mInput->stream,
Andy Hung57446612015-04-19 23:56:46 -07005710 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005711 if (bytesRead < 0) {
5712 framesRead = bytesRead;
5713 } else {
5714 framesRead = bytesRead / mFrameSize;
5715 }
5716 }
5717
5718 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
5719 ALOGE("read failed: framesRead=%d", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005720 // Force input into standby so that it tries to recover at next read attempt
5721 inputStandBy();
5722 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005723 }
5724 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005725 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005726 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005727 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005728
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005729 if (mTeeSink != 0) {
Andy Hung57446612015-04-19 23:56:46 -07005730 (void) mTeeSink->write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005731 }
5732 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005733 {
5734 size_t part1 = mRsmpInFramesP2 - rear;
5735 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07005736 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005737 (framesRead - part1) * mFrameSize);
5738 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005739 }
5740 rear = mRsmpInRear += framesRead;
5741
5742 size = activeTracks.size();
5743 // loop over each active track
5744 for (size_t i = 0; i < size; i++) {
5745 activeTrack = activeTracks[i];
5746
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005747 // skip fast tracks, as those are handled directly by FastCapture
5748 if (activeTrack->isFastTrack()) {
5749 continue;
5750 }
5751
Andy Hung73c02e42015-03-29 01:13:58 -07005752 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07005753 // TODO: Update the activeTrack buffer converter in case of reconfigure.
5754
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005755 enum {
5756 OVERRUN_UNKNOWN,
5757 OVERRUN_TRUE,
5758 OVERRUN_FALSE
5759 } overrun = OVERRUN_UNKNOWN;
5760
5761 // loop over getNextBuffer to handle circular sink
5762 for (;;) {
5763
5764 activeTrack->mSink.frameCount = ~0;
5765 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
5766 size_t framesOut = activeTrack->mSink.frameCount;
5767 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
5768
Andy Hung73c02e42015-03-29 01:13:58 -07005769 // check available frames and handle overrun conditions
5770 // if the record track isn't draining fast enough.
5771 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005772 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07005773 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
5774 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005775 overrun = OVERRUN_TRUE;
5776 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005777 if (framesOut == 0 || framesIn == 0) {
5778 break;
5779 }
5780
Andy Hung6770c6f2015-04-07 13:43:36 -07005781 // Don't allow framesOut to be larger than what is possible with resampling
5782 // from framesIn.
5783 // This isn't strictly necessary but helps limit buffer resizing in
5784 // RecordBufferConverter. TODO: remove when no longer needed.
5785 framesOut = min(framesOut,
5786 destinationFramesPossible(
5787 framesIn, mSampleRate, activeTrack->mSampleRate));
Andy Hung97a893e2015-03-29 01:03:07 -07005788 // process frames from the RecordThread buffer provider to the RecordTrack buffer
5789 framesOut = activeTrack->mRecordBufferConverter->convert(
5790 activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005791
5792 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
5793 overrun = OVERRUN_FALSE;
5794 }
5795
5796 if (activeTrack->mFramesToDrop == 0) {
5797 if (framesOut > 0) {
5798 activeTrack->mSink.frameCount = framesOut;
5799 activeTrack->releaseBuffer(&activeTrack->mSink);
5800 }
5801 } else {
5802 // FIXME could do a partial drop of framesOut
5803 if (activeTrack->mFramesToDrop > 0) {
5804 activeTrack->mFramesToDrop -= framesOut;
5805 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005806 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005807 }
5808 } else {
5809 activeTrack->mFramesToDrop += framesOut;
5810 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
5811 activeTrack->mSyncStartEvent->isCancelled()) {
5812 ALOGW("Synced record %s, session %d, trigger session %d",
5813 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
5814 activeTrack->sessionId(),
5815 (activeTrack->mSyncStartEvent != 0) ?
5816 activeTrack->mSyncStartEvent->triggerSession() : 0);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005817 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005818 }
5819 }
5820 }
5821
5822 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005823 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005824 }
5825 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005826
5827 switch (overrun) {
5828 case OVERRUN_TRUE:
5829 // client isn't retrieving buffers fast enough
5830 if (!activeTrack->setOverflow()) {
5831 nsecs_t now = systemTime();
5832 // FIXME should lastWarning per track?
5833 if ((now - lastWarning) > kWarningThrottleNs) {
5834 ALOGW("RecordThread: buffer overflow");
5835 lastWarning = now;
5836 }
5837 }
5838 break;
5839 case OVERRUN_FALSE:
5840 activeTrack->clearOverflow();
5841 break;
5842 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005843 break;
5844 }
5845
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005846 }
5847
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005848unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08005849 // enable changes in effect chain
5850 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005851 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08005852 }
5853
Glenn Kasten93e471f2013-08-19 08:40:07 -07005854 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08005855
5856 {
5857 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07005858 for (size_t i = 0; i < mTracks.size(); i++) {
5859 sp<RecordTrack> track = mTracks[i];
5860 track->invalidate();
5861 }
Glenn Kasten2b806402013-11-20 16:37:38 -08005862 mActiveTracks.clear();
5863 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08005864 mStartStopCond.broadcast();
5865 }
5866
5867 releaseWakeLock();
5868
5869 ALOGV("RecordThread %p exiting", this);
5870 return false;
5871}
5872
Glenn Kasten93e471f2013-08-19 08:40:07 -07005873void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08005874{
5875 if (!mStandby) {
5876 inputStandBy();
5877 mStandby = true;
5878 }
5879}
5880
5881void AudioFlinger::RecordThread::inputStandBy()
5882{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005883 // Idle the fast capture if it's currently running
5884 if (mFastCapture != 0) {
5885 FastCaptureStateQueue *sq = mFastCapture->sq();
5886 FastCaptureState *state = sq->begin();
5887 if (!(state->mCommand & FastCaptureState::IDLE)) {
5888 state->mCommand = FastCaptureState::COLD_IDLE;
5889 state->mColdFutexAddr = &mFastCaptureFutex;
5890 state->mColdGen++;
5891 mFastCaptureFutex = 0;
5892 sq->end();
5893 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
5894 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
5895#if 0
5896 if (kUseFastCapture == FastCapture_Dynamic) {
5897 // FIXME
5898 }
5899#endif
5900#ifdef AUDIO_WATCHDOG
5901 // FIXME
5902#endif
5903 } else {
5904 sq->end(false /*didModify*/);
5905 }
5906 }
Eric Laurent81784c32012-11-19 14:55:58 -08005907 mInput->stream->common.standby(&mInput->stream->common);
5908}
5909
Glenn Kasten05997e22014-03-13 15:08:33 -07005910// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07005911sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08005912 const sp<AudioFlinger::Client>& client,
5913 uint32_t sampleRate,
5914 audio_format_t format,
5915 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08005916 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08005917 int sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07005918 size_t *notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005919 int uid,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07005920 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08005921 pid_t tid,
5922 status_t *status)
5923{
Glenn Kasten74935e42013-12-19 08:56:45 -08005924 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005925 sp<RecordTrack> track;
5926 status_t lStatus;
5927
Glenn Kasten90e58b12013-07-31 16:16:02 -07005928 // client expresses a preference for FAST, but we get the final say
5929 if (*flags & IAudioFlinger::TRACK_FAST) {
5930 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07005931 // we formerly checked for a callback handler (non-0 tid),
5932 // but that is no longer required for TRANSFER_OBTAIN mode
5933 //
Glenn Kasten74105912014-07-03 12:28:53 -07005934 // frame count is not specified, or is exactly the pipe depth
5935 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005936 // PCM data
5937 audio_is_linear_pcm(format) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005938 // native format
5939 (format == mFormat) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005940 // native channel mask
5941 (channelMask == mChannelMask) &&
5942 // native hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07005943 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005944 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005945 hasFastCapture() &&
5946 // there are sufficient fast track slots available
5947 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07005948 ) {
Glenn Kasten74105912014-07-03 12:28:53 -07005949 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%u mFrameCount=%u",
Glenn Kasten90e58b12013-07-31 16:16:02 -07005950 frameCount, mFrameCount);
5951 } else {
Glenn Kasten74105912014-07-03 12:28:53 -07005952 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%u mFrameCount=%u mPipeFramesP2=%u "
5953 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005954 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Glenn Kasten74105912014-07-03 12:28:53 -07005955 frameCount, mFrameCount, mPipeFramesP2,
5956 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
5957 hasFastCapture(), tid, mFastTrackAvail);
Glenn Kasten90e58b12013-07-31 16:16:02 -07005958 *flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kasten74105912014-07-03 12:28:53 -07005959 }
5960 }
5961
5962 // compute track buffer size in frames, and suggest the notification frame count
5963 if (*flags & IAudioFlinger::TRACK_FAST) {
5964 // fast track: frame count is exactly the pipe depth
5965 frameCount = mPipeFramesP2;
5966 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
5967 *notificationFrames = mFrameCount;
5968 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07005969 // not fast track: max notification period is resampled equivalent of one HAL buffer time
5970 // or 20 ms if there is a fast capture
5971 // TODO This could be a roundupRatio inline, and const
5972 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
5973 * sampleRate + mSampleRate - 1) / mSampleRate;
5974 // minimum number of notification periods is at least kMinNotifications,
5975 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
5976 static const size_t kMinNotifications = 3;
5977 static const uint32_t kMinMs = 30;
5978 // TODO This could be a roundupRatio inline
5979 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
5980 // TODO This could be a roundupRatio inline
5981 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
5982 maxNotificationFrames;
5983 const size_t minFrameCount = maxNotificationFrames *
5984 max(kMinNotifications, minNotificationsByMs);
5985 frameCount = max(frameCount, minFrameCount);
5986 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
5987 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07005988 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07005989 }
Glenn Kasten74935e42013-12-19 08:56:45 -08005990 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07005991
Glenn Kasten15e57982013-09-24 11:52:37 -07005992 lStatus = initCheck();
5993 if (lStatus != NO_ERROR) {
5994 ALOGE("createRecordTrack_l() audio driver not initialized");
5995 goto Exit;
5996 }
Eric Laurent81784c32012-11-19 14:55:58 -08005997
5998 { // scope for mLock
5999 Mutex::Autolock _l(mLock);
6000
6001 track = new RecordTrack(this, client, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07006002 format, channelMask, frameCount, NULL, sessionId, uid,
6003 *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08006004
Glenn Kasten03003332013-08-06 15:40:54 -07006005 lStatus = track->initCheck();
6006 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07006007 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08006008 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08006009 goto Exit;
6010 }
6011 mTracks.add(track);
6012
6013 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6014 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6015 mAudioFlinger->btNrecIsOff();
6016 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6017 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006018
6019 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
6020 pid_t callingPid = IPCThreadState::self()->getCallingPid();
6021 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
6022 // so ask activity manager to do this on our behalf
6023 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
6024 }
Eric Laurent81784c32012-11-19 14:55:58 -08006025 }
Glenn Kasten05997e22014-03-13 15:08:33 -07006026
Eric Laurent81784c32012-11-19 14:55:58 -08006027 lStatus = NO_ERROR;
6028
6029Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07006030 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08006031 return track;
6032}
6033
6034status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
6035 AudioSystem::sync_event_t event,
6036 int triggerSession)
6037{
6038 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
6039 sp<ThreadBase> strongMe = this;
6040 status_t status = NO_ERROR;
6041
6042 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006043 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006044 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006045 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08006046 triggerSession,
6047 recordTrack->sessionId(),
6048 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006049 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08006050 // Sync event can be cancelled by the trigger session if the track is not in a
6051 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006052 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006053 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006054 } else {
6055 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006056 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006057 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08006058 }
6059 }
6060
6061 {
Glenn Kasten47c20702013-08-13 15:37:35 -07006062 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08006063 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006064 if (mActiveTracks.indexOf(recordTrack) >= 0) {
6065 if (recordTrack->mState == TrackBase::PAUSING) {
6066 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006067 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006068 } else {
6069 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08006070 }
6071 return status;
6072 }
6073
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006074 // TODO consider other ways of handling this, such as changing the state to :STARTING and
6075 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
6076 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006077 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08006078 mActiveTracks.add(recordTrack);
6079 mActiveTracksGen++;
Eric Laurent83b88082014-06-20 18:31:16 -07006080 status_t status = NO_ERROR;
6081 if (recordTrack->isExternalTrack()) {
6082 mLock.unlock();
Eric Laurent4dc68062014-07-28 17:26:49 -07006083 status = AudioSystem::startInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006084 mLock.lock();
6085 // FIXME should verify that recordTrack is still in mActiveTracks
6086 if (status != NO_ERROR) {
6087 mActiveTracks.remove(recordTrack);
6088 mActiveTracksGen++;
6089 recordTrack->clearSyncStartEvent();
6090 ALOGV("RecordThread::start error %d", status);
6091 return status;
6092 }
Eric Laurent81784c32012-11-19 14:55:58 -08006093 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006094 // Catch up with current buffer indices if thread is already running.
6095 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
6096 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
6097 // see previously buffered data before it called start(), but with greater risk of overrun.
6098
Andy Hung73c02e42015-03-29 01:13:58 -07006099 recordTrack->mResamplerBufferProvider->reset();
Andy Hung97a893e2015-03-29 01:03:07 -07006100 // clear any converter state as new data will be discontinuous
6101 recordTrack->mRecordBufferConverter->reset();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006102 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08006103 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08006104 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08006105 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006106 ALOGV("Record failed to start");
6107 status = BAD_VALUE;
6108 goto startError;
6109 }
Eric Laurent81784c32012-11-19 14:55:58 -08006110 return status;
6111 }
Glenn Kasten7c027242012-12-26 14:43:16 -08006112
Eric Laurent81784c32012-11-19 14:55:58 -08006113startError:
Eric Laurent83b88082014-06-20 18:31:16 -07006114 if (recordTrack->isExternalTrack()) {
Eric Laurent4dc68062014-07-28 17:26:49 -07006115 AudioSystem::stopInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006116 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006117 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006118 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08006119 return status;
6120}
6121
Eric Laurent81784c32012-11-19 14:55:58 -08006122void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6123{
6124 sp<SyncEvent> strongEvent = event.promote();
6125
6126 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08006127 sp<RefBase> ptr = strongEvent->cookie().promote();
6128 if (ptr != 0) {
6129 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
6130 recordTrack->handleSyncStartEvent(strongEvent);
6131 }
Eric Laurent81784c32012-11-19 14:55:58 -08006132 }
6133}
6134
Glenn Kastena8356f62013-07-25 14:37:52 -07006135bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08006136 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07006137 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006138 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08006139 return false;
6140 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006141 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08006142 recordTrack->mState = TrackBase::PAUSING;
6143 // do not wait for mStartStopCond if exiting
6144 if (exitPending()) {
6145 return true;
6146 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006147 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08006148 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006149 // if we have been restarted, recordTrack is in mActiveTracks here
6150 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006151 ALOGV("Record stopped OK");
6152 return true;
6153 }
6154 return false;
6155}
6156
Glenn Kasten0f11b512014-01-31 16:18:54 -08006157bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08006158{
6159 return false;
6160}
6161
Glenn Kasten0f11b512014-01-31 16:18:54 -08006162status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006163{
6164#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
6165 if (!isValidSyncEvent(event)) {
6166 return BAD_VALUE;
6167 }
6168
6169 int eventSession = event->triggerSession();
6170 status_t ret = NAME_NOT_FOUND;
6171
6172 Mutex::Autolock _l(mLock);
6173
6174 for (size_t i = 0; i < mTracks.size(); i++) {
6175 sp<RecordTrack> track = mTracks[i];
6176 if (eventSession == track->sessionId()) {
6177 (void) track->setSyncEvent(event);
6178 ret = NO_ERROR;
6179 }
6180 }
6181 return ret;
6182#else
6183 return BAD_VALUE;
6184#endif
6185}
6186
6187// destroyTrack_l() must be called with ThreadBase::mLock held
6188void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6189{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006190 track->terminate();
6191 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08006192 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08006193 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006194 removeTrack_l(track);
6195 }
6196}
6197
6198void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6199{
6200 mTracks.remove(track);
6201 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006202 if (track->isFastTrack()) {
6203 ALOG_ASSERT(!mFastTrackAvail);
6204 mFastTrackAvail = true;
6205 }
Eric Laurent81784c32012-11-19 14:55:58 -08006206}
6207
6208void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6209{
6210 dumpInternals(fd, args);
6211 dumpTracks(fd, args);
6212 dumpEffectChains(fd, args);
6213}
6214
6215void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6216{
Elliott Hughes87cebad2014-05-22 10:14:43 -07006217 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08006218
Glenn Kasten44182c22015-03-05 17:12:23 -08006219 dumpBase(fd, args);
6220
6221 if (mActiveTracks.size() == 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006222 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006223 }
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006224 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006225 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08006226
6227 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
6228 const FastCaptureDumpState copy(mFastCaptureDumpState);
6229 copy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006230}
6231
Glenn Kasten0f11b512014-01-31 16:18:54 -08006232void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006233{
6234 const size_t SIZE = 256;
6235 char buffer[SIZE];
6236 String8 result;
6237
Marco Nelissenb2208842014-02-07 14:00:50 -08006238 size_t numtracks = mTracks.size();
6239 size_t numactive = mActiveTracks.size();
6240 size_t numactiveseen = 0;
Elliott Hughes87cebad2014-05-22 10:14:43 -07006241 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08006242 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006243 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08006244 RecordTrack::appendDumpHeader(result);
6245 for (size_t i = 0; i < numtracks ; ++i) {
6246 sp<RecordTrack> track = mTracks[i];
6247 if (track != 0) {
6248 bool active = mActiveTracks.indexOf(track) >= 0;
6249 if (active) {
6250 numactiveseen++;
6251 }
6252 track->dump(buffer, SIZE, active);
6253 result.append(buffer);
6254 }
Eric Laurent81784c32012-11-19 14:55:58 -08006255 }
Marco Nelissenb2208842014-02-07 14:00:50 -08006256 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006257 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006258 }
6259
Marco Nelissenb2208842014-02-07 14:00:50 -08006260 if (numactiveseen != numactive) {
6261 snprintf(buffer, SIZE, " The following tracks are in the active list but"
6262 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006263 result.append(buffer);
6264 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08006265 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08006266 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08006267 if (mTracks.indexOf(track) < 0) {
6268 track->dump(buffer, SIZE, true);
6269 result.append(buffer);
6270 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006271 }
Eric Laurent81784c32012-11-19 14:55:58 -08006272
6273 }
6274 write(fd, result.string(), result.size());
6275}
6276
Andy Hung73c02e42015-03-29 01:13:58 -07006277
6278void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
6279{
6280 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6281 RecordThread *recordThread = (RecordThread *) threadBase.get();
6282 mRsmpInFront = recordThread->mRsmpInRear;
6283 mRsmpInUnrel = 0;
6284}
6285
6286void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
6287 size_t *framesAvailable, bool *hasOverrun)
6288{
6289 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6290 RecordThread *recordThread = (RecordThread *) threadBase.get();
6291 const int32_t rear = recordThread->mRsmpInRear;
6292 const int32_t front = mRsmpInFront;
6293 const ssize_t filled = rear - front;
6294
6295 size_t framesIn;
6296 bool overrun = false;
6297 if (filled < 0) {
6298 // should not happen, but treat like a massive overrun and re-sync
6299 framesIn = 0;
6300 mRsmpInFront = rear;
6301 overrun = true;
6302 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
6303 framesIn = (size_t) filled;
6304 } else {
6305 // client is not keeping up with server, but give it latest data
6306 framesIn = recordThread->mRsmpInFrames;
6307 mRsmpInFront = /* front = */ rear - framesIn;
6308 overrun = true;
6309 }
6310 if (framesAvailable != NULL) {
6311 *framesAvailable = framesIn;
6312 }
6313 if (hasOverrun != NULL) {
6314 *hasOverrun = overrun;
6315 }
6316}
6317
Eric Laurent81784c32012-11-19 14:55:58 -08006318// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006319status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
6320 AudioBufferProvider::Buffer* buffer, int64_t pts __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006321{
Andy Hung73c02e42015-03-29 01:13:58 -07006322 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006323 if (threadBase == 0) {
6324 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006325 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006326 return NOT_ENOUGH_DATA;
6327 }
6328 RecordThread *recordThread = (RecordThread *) threadBase.get();
6329 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07006330 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07006331 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006332 // FIXME should not be P2 (don't want to increase latency)
6333 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006334 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07006335 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006336 front &= recordThread->mRsmpInFramesP2 - 1;
6337 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07006338 if (part1 > (size_t) filled) {
6339 part1 = filled;
6340 }
6341 size_t ask = buffer->frameCount;
6342 ALOG_ASSERT(ask > 0);
6343 if (part1 > ask) {
6344 part1 = ask;
6345 }
6346 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07006347 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07006348 buffer->raw = NULL;
6349 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07006350 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07006351 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08006352 }
6353
Andy Hung57446612015-04-19 23:56:46 -07006354 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07006355 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07006356 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08006357 return NO_ERROR;
6358}
6359
6360// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006361void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
6362 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006363{
Glenn Kasten85948432013-08-19 12:09:05 -07006364 size_t stepCount = buffer->frameCount;
6365 if (stepCount == 0) {
6366 return;
6367 }
Andy Hung73c02e42015-03-29 01:13:58 -07006368 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
6369 mRsmpInUnrel -= stepCount;
6370 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07006371 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006372 buffer->frameCount = 0;
6373}
6374
Andy Hung97a893e2015-03-29 01:03:07 -07006375AudioFlinger::RecordThread::RecordBufferConverter::RecordBufferConverter(
6376 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6377 uint32_t srcSampleRate,
6378 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6379 uint32_t dstSampleRate) :
6380 mSrcChannelMask(AUDIO_CHANNEL_INVALID), // updateParameters will set following vars
6381 // mSrcFormat
6382 // mSrcSampleRate
6383 // mDstChannelMask
6384 // mDstFormat
6385 // mDstSampleRate
6386 // mSrcChannelCount
6387 // mDstChannelCount
6388 // mDstFrameSize
6389 mBuf(NULL), mBufFrames(0), mBufFrameSize(0),
Andy Hungd330ee42015-04-20 13:23:41 -07006390 mResampler(NULL),
6391 mIsLegacyDownmix(false),
6392 mIsLegacyUpmix(false),
6393 mRequiresFloat(false),
6394 mInputConverterProvider(NULL)
Andy Hung97a893e2015-03-29 01:03:07 -07006395{
6396 (void)updateParameters(srcChannelMask, srcFormat, srcSampleRate,
6397 dstChannelMask, dstFormat, dstSampleRate);
6398}
6399
6400AudioFlinger::RecordThread::RecordBufferConverter::~RecordBufferConverter() {
6401 free(mBuf);
6402 delete mResampler;
Andy Hungd330ee42015-04-20 13:23:41 -07006403 delete mInputConverterProvider;
Andy Hung97a893e2015-03-29 01:03:07 -07006404}
6405
6406size_t AudioFlinger::RecordThread::RecordBufferConverter::convert(void *dst,
6407 AudioBufferProvider *provider, size_t frames)
6408{
Andy Hungd330ee42015-04-20 13:23:41 -07006409 if (mInputConverterProvider != NULL) {
6410 mInputConverterProvider->setBufferProvider(provider);
6411 provider = mInputConverterProvider;
6412 }
6413
6414 if (mResampler == NULL) {
Andy Hung97a893e2015-03-29 01:03:07 -07006415 ALOGVV("NO RESAMPLING sampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6416 mSrcSampleRate, mSrcFormat, mDstFormat);
6417
6418 AudioBufferProvider::Buffer buffer;
6419 for (size_t i = frames; i > 0; ) {
6420 buffer.frameCount = i;
6421 status_t status = provider->getNextBuffer(&buffer, 0);
6422 if (status != OK || buffer.frameCount == 0) {
6423 frames -= i; // cannot fill request.
6424 break;
6425 }
Andy Hungd330ee42015-04-20 13:23:41 -07006426 // format convert to destination buffer
6427 convertNoResampler(dst, buffer.raw, buffer.frameCount);
Andy Hung97a893e2015-03-29 01:03:07 -07006428
6429 dst = (int8_t*)dst + buffer.frameCount * mDstFrameSize;
6430 i -= buffer.frameCount;
6431 provider->releaseBuffer(&buffer);
6432 }
6433 } else {
6434 ALOGVV("RESAMPLING mSrcSampleRate:%u mDstSampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6435 mSrcSampleRate, mDstSampleRate, mSrcFormat, mDstFormat);
6436
Andy Hungd330ee42015-04-20 13:23:41 -07006437 // reallocate buffer if needed
6438 if (mBufFrameSize != 0 && mBufFrames < frames) {
6439 free(mBuf);
6440 mBufFrames = frames;
6441 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
6442 }
Andy Hung97a893e2015-03-29 01:03:07 -07006443 // resampler accumulates, but we only have one source track
Andy Hungd330ee42015-04-20 13:23:41 -07006444 memset(mBuf, 0, frames * mBufFrameSize);
6445 frames = mResampler->resample((int32_t*)mBuf, frames, provider);
6446 // format convert to destination buffer
6447 convertResampler(dst, mBuf, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006448 }
6449 return frames;
6450}
6451
6452status_t AudioFlinger::RecordThread::RecordBufferConverter::updateParameters(
6453 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6454 uint32_t srcSampleRate,
6455 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6456 uint32_t dstSampleRate)
6457{
6458 // quick evaluation if there is any change.
6459 if (mSrcFormat == srcFormat
6460 && mSrcChannelMask == srcChannelMask
6461 && mSrcSampleRate == srcSampleRate
6462 && mDstFormat == dstFormat
6463 && mDstChannelMask == dstChannelMask
6464 && mDstSampleRate == dstSampleRate) {
6465 return NO_ERROR;
6466 }
6467
Andy Hungdb4c0312015-05-06 08:46:52 -07006468 ALOGV("RecordBufferConverter updateParameters srcMask:%#x dstMask:%#x"
6469 " srcFormat:%#x dstFormat:%#x srcRate:%u dstRate:%u",
6470 srcChannelMask, dstChannelMask, srcFormat, dstFormat, srcSampleRate, dstSampleRate);
Andy Hung97a893e2015-03-29 01:03:07 -07006471 const bool valid =
6472 audio_is_input_channel(srcChannelMask)
6473 && audio_is_input_channel(dstChannelMask)
6474 && audio_is_valid_format(srcFormat) && audio_is_linear_pcm(srcFormat)
6475 && audio_is_valid_format(dstFormat) && audio_is_linear_pcm(dstFormat)
6476 && (srcSampleRate <= dstSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX)
6477 ; // no upsampling checks for now
6478 if (!valid) {
6479 return BAD_VALUE;
6480 }
6481
6482 mSrcFormat = srcFormat;
6483 mSrcChannelMask = srcChannelMask;
6484 mSrcSampleRate = srcSampleRate;
6485 mDstFormat = dstFormat;
6486 mDstChannelMask = dstChannelMask;
6487 mDstSampleRate = dstSampleRate;
6488
6489 // compute derived parameters
6490 mSrcChannelCount = audio_channel_count_from_in_mask(srcChannelMask);
6491 mDstChannelCount = audio_channel_count_from_in_mask(dstChannelMask);
6492 mDstFrameSize = mDstChannelCount * audio_bytes_per_sample(mDstFormat);
6493
Andy Hungd330ee42015-04-20 13:23:41 -07006494 // do we need to resample?
6495 delete mResampler;
6496 mResampler = NULL;
6497 if (mSrcSampleRate != mDstSampleRate) {
6498 mResampler = AudioResampler::create(AUDIO_FORMAT_PCM_FLOAT,
6499 mSrcChannelCount, mDstSampleRate);
6500 mResampler->setSampleRate(mSrcSampleRate);
6501 mResampler->setVolume(AudioMixer::UNITY_GAIN_FLOAT, AudioMixer::UNITY_GAIN_FLOAT);
6502 }
6503
6504 // are we running legacy channel conversion modes?
6505 mIsLegacyDownmix = (mSrcChannelMask == AUDIO_CHANNEL_IN_STEREO
6506 || mSrcChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK)
6507 && mDstChannelMask == AUDIO_CHANNEL_IN_MONO;
6508 mIsLegacyUpmix = mSrcChannelMask == AUDIO_CHANNEL_IN_MONO
6509 && (mDstChannelMask == AUDIO_CHANNEL_IN_STEREO
6510 || mDstChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK);
6511
6512 // do we need to process in float?
6513 mRequiresFloat = mResampler != NULL || mIsLegacyDownmix || mIsLegacyUpmix;
6514
6515 // do we need a staging buffer to convert for destination (we can still optimize this)?
6516 // we use mBufFrameSize > 0 to indicate both frame size as well as buffer necessity
6517 if (mResampler != NULL) {
6518 mBufFrameSize = max(mSrcChannelCount, FCC_2)
6519 * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
6520 } else if ((mIsLegacyUpmix || mIsLegacyDownmix) && mDstFormat != AUDIO_FORMAT_PCM_FLOAT) {
6521 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
6522 } else if (mSrcChannelMask != mDstChannelMask && mDstFormat != mSrcFormat) {
Andy Hung97a893e2015-03-29 01:03:07 -07006523 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(mSrcFormat);
6524 } else {
6525 mBufFrameSize = 0;
6526 }
6527 mBufFrames = 0; // force the buffer to be resized.
6528
Andy Hungd330ee42015-04-20 13:23:41 -07006529 // do we need an input converter buffer provider to give us float?
6530 delete mInputConverterProvider;
6531 mInputConverterProvider = NULL;
6532 if (mRequiresFloat && mSrcFormat != AUDIO_FORMAT_PCM_FLOAT) {
6533 mInputConverterProvider = new ReformatBufferProvider(
6534 audio_channel_count_from_in_mask(mSrcChannelMask),
6535 mSrcFormat,
6536 AUDIO_FORMAT_PCM_FLOAT,
6537 256 /* provider buffer frame count */);
6538 }
6539
6540 // do we need a remixer to do channel mask conversion
6541 if (!mIsLegacyDownmix && !mIsLegacyUpmix && mSrcChannelMask != mDstChannelMask) {
6542 (void) memcpy_by_index_array_initialization_from_channel_mask(
6543 mIdxAry, ARRAY_SIZE(mIdxAry), mDstChannelMask, mSrcChannelMask);
Andy Hung97a893e2015-03-29 01:03:07 -07006544 }
6545 return NO_ERROR;
6546}
6547
Andy Hungd330ee42015-04-20 13:23:41 -07006548void AudioFlinger::RecordThread::RecordBufferConverter::convertNoResampler(
6549 void *dst, const void *src, size_t frames)
Andy Hung97a893e2015-03-29 01:03:07 -07006550{
Andy Hungd330ee42015-04-20 13:23:41 -07006551 // src is native type unless there is legacy upmix or downmix, whereupon it is float.
Andy Hung97a893e2015-03-29 01:03:07 -07006552 if (mBufFrameSize != 0 && mBufFrames < frames) {
6553 free(mBuf);
6554 mBufFrames = frames;
6555 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
6556 }
Andy Hungd330ee42015-04-20 13:23:41 -07006557 // do we need to do legacy upmix and downmix?
6558 if (mIsLegacyUpmix || mIsLegacyDownmix) {
Andy Hung97a893e2015-03-29 01:03:07 -07006559 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07006560 if (mIsLegacyUpmix) {
6561 upmix_to_stereo_float_from_mono_float((float *)dstBuf,
6562 (const float *)src, frames);
6563 } else /*mIsLegacyDownmix */ {
6564 downmix_to_mono_float_from_stereo_float((float *)dstBuf,
6565 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006566 }
Andy Hungd330ee42015-04-20 13:23:41 -07006567 if (mBuf != NULL) {
6568 memcpy_by_audio_format(dst, mDstFormat, mBuf, AUDIO_FORMAT_PCM_FLOAT,
6569 frames * mDstChannelCount);
6570 }
6571 return;
6572 }
6573 // do we need to do channel mask conversion?
6574 if (mSrcChannelMask != mDstChannelMask) {
Andy Hung97a893e2015-03-29 01:03:07 -07006575 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07006576 memcpy_by_index_array(dstBuf, mDstChannelCount,
6577 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mSrcFormat), frames);
6578 if (dstBuf == dst) {
6579 return; // format is the same
6580 }
6581 }
6582 // convert to destination buffer
6583 const void *convertBuf = mBuf != NULL ? mBuf : src;
6584 memcpy_by_audio_format(dst, mDstFormat, convertBuf, mSrcFormat,
6585 frames * mDstChannelCount);
6586}
6587
6588void AudioFlinger::RecordThread::RecordBufferConverter::convertResampler(
6589 void *dst, /*not-a-const*/ void *src, size_t frames)
6590{
6591 // src buffer format is ALWAYS float when entering this routine
6592 if (mIsLegacyUpmix) {
6593 ; // mono to stereo already handled by resampler
6594 } else if (mIsLegacyDownmix
6595 || (mSrcChannelMask == mDstChannelMask && mSrcChannelCount == 1)) {
6596 // the resampler outputs stereo for mono input channel (a feature?)
6597 // must convert to mono
6598 downmix_to_mono_float_from_stereo_float((float *)src,
6599 (const float *)src, frames);
6600 } else if (mSrcChannelMask != mDstChannelMask) {
6601 // convert to mono channel again for channel mask conversion (could be skipped
6602 // with further optimization).
Andy Hung97a893e2015-03-29 01:03:07 -07006603 if (mSrcChannelCount == 1) {
Andy Hungd330ee42015-04-20 13:23:41 -07006604 downmix_to_mono_float_from_stereo_float((float *)src,
6605 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006606 }
Andy Hungd330ee42015-04-20 13:23:41 -07006607 // convert to destination format (in place, OK as float is larger than other types)
6608 if (mDstFormat != AUDIO_FORMAT_PCM_FLOAT) {
6609 memcpy_by_audio_format(src, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
6610 frames * mSrcChannelCount);
6611 }
6612 // channel convert and save to dst
6613 memcpy_by_index_array(dst, mDstChannelCount,
6614 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mDstFormat), frames);
6615 return;
Andy Hung97a893e2015-03-29 01:03:07 -07006616 }
Andy Hungd330ee42015-04-20 13:23:41 -07006617 // convert to destination format and save to dst
6618 memcpy_by_audio_format(dst, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
6619 frames * mDstChannelCount);
Andy Hung97a893e2015-03-29 01:03:07 -07006620}
6621
Eric Laurent10351942014-05-08 18:49:52 -07006622bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
6623 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006624{
6625 bool reconfig = false;
6626
Eric Laurent10351942014-05-08 18:49:52 -07006627 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006628
Eric Laurent10351942014-05-08 18:49:52 -07006629 audio_format_t reqFormat = mFormat;
6630 uint32_t samplingRate = mSampleRate;
6631 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
Andy Hungd330ee42015-04-20 13:23:41 -07006632 // possible that we are > 2 channels, use channel index mask
6633 if (channelMask == AUDIO_CHANNEL_INVALID && mChannelCount <= FCC_8) {
6634 audio_channel_mask_for_index_assignment_from_count(mChannelCount);
6635 }
Eric Laurent10351942014-05-08 18:49:52 -07006636
6637 AudioParameter param = AudioParameter(keyValuePair);
6638 int value;
6639 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
6640 // channel count change can be requested. Do we mandate the first client defines the
6641 // HAL sampling rate and channel count or do we allow changes on the fly?
6642 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6643 samplingRate = value;
6644 reconfig = true;
6645 }
6646 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07006647 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07006648 status = BAD_VALUE;
6649 } else {
6650 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08006651 reconfig = true;
6652 }
Eric Laurent10351942014-05-08 18:49:52 -07006653 }
6654 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
6655 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07006656 if (!audio_is_input_channel(mask) ||
6657 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07006658 status = BAD_VALUE;
6659 } else {
6660 channelMask = mask;
6661 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006662 }
Eric Laurent10351942014-05-08 18:49:52 -07006663 }
6664 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6665 // do not accept frame count changes if tracks are open as the track buffer
6666 // size depends on frame count and correct behavior would not be guaranteed
6667 // if frame count is changed after track creation
6668 if (mActiveTracks.size() > 0) {
6669 status = INVALID_OPERATION;
6670 } else {
6671 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006672 }
Eric Laurent10351942014-05-08 18:49:52 -07006673 }
6674 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6675 // forward device change to effects that have requested to be
6676 // aware of attached audio device.
6677 for (size_t i = 0; i < mEffectChains.size(); i++) {
6678 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08006679 }
Eric Laurent81784c32012-11-19 14:55:58 -08006680
Eric Laurent10351942014-05-08 18:49:52 -07006681 // store input device and output device but do not forward output device to audio HAL.
6682 // Note that status is ignored by the caller for output device
6683 // (see AudioFlinger::setParameters()
6684 if (audio_is_output_devices(value)) {
6685 mOutDevice = value;
6686 status = BAD_VALUE;
6687 } else {
6688 mInDevice = value;
6689 // disable AEC and NS if the device is a BT SCO headset supporting those
6690 // pre processings
6691 if (mTracks.size() > 0) {
6692 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6693 mAudioFlinger->btNrecIsOff();
6694 for (size_t i = 0; i < mTracks.size(); i++) {
6695 sp<RecordTrack> track = mTracks[i];
6696 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
6697 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08006698 }
6699 }
6700 }
Eric Laurent10351942014-05-08 18:49:52 -07006701 }
6702 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
6703 mAudioSource != (audio_source_t)value) {
6704 // forward device change to effects that have requested to be
6705 // aware of attached audio device.
6706 for (size_t i = 0; i < mEffectChains.size(); i++) {
6707 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08006708 }
Eric Laurent10351942014-05-08 18:49:52 -07006709 mAudioSource = (audio_source_t)value;
6710 }
Glenn Kastene198c362013-08-13 09:13:36 -07006711
Eric Laurent10351942014-05-08 18:49:52 -07006712 if (status == NO_ERROR) {
6713 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6714 keyValuePair.string());
6715 if (status == INVALID_OPERATION) {
6716 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006717 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6718 keyValuePair.string());
Eric Laurent10351942014-05-08 18:49:52 -07006719 }
6720 if (reconfig) {
6721 if (status == BAD_VALUE &&
Andy Hung97a893e2015-03-29 01:03:07 -07006722 audio_is_linear_pcm(mInput->stream->common.get_format(&mInput->stream->common)) &&
6723 audio_is_linear_pcm(reqFormat) &&
Eric Laurent10351942014-05-08 18:49:52 -07006724 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
Andy Hung97a893e2015-03-29 01:03:07 -07006725 <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate)) &&
Andy Hunge5412692014-05-16 11:25:07 -07006726 audio_channel_count_from_in_mask(
Andy Hungd1abb8f2015-05-05 23:42:34 -07006727 mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07006728 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006729 }
Eric Laurent10351942014-05-08 18:49:52 -07006730 if (status == NO_ERROR) {
6731 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07006732 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08006733 }
6734 }
Eric Laurent81784c32012-11-19 14:55:58 -08006735 }
Eric Laurent10351942014-05-08 18:49:52 -07006736
Eric Laurent81784c32012-11-19 14:55:58 -08006737 return reconfig;
6738}
6739
6740String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6741{
Eric Laurent81784c32012-11-19 14:55:58 -08006742 Mutex::Autolock _l(mLock);
6743 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07006744 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08006745 }
6746
Glenn Kastend8ea6992013-07-16 14:17:15 -07006747 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
6748 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08006749 free(s);
6750 return out_s8;
6751}
6752
Eric Laurent73e26b62015-04-27 16:55:58 -07006753void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event) {
6754 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
6755
6756 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08006757
6758 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07006759 case AUDIO_INPUT_OPENED:
6760 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07006761 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07006762 desc->mChannelMask = mChannelMask;
6763 desc->mSamplingRate = mSampleRate;
6764 desc->mFormat = mFormat;
6765 desc->mFrameCount = mFrameCount;
6766 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006767 break;
6768
Eric Laurent73e26b62015-04-27 16:55:58 -07006769 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08006770 default:
6771 break;
6772 }
Eric Laurent73e26b62015-04-27 16:55:58 -07006773 mAudioFlinger->ioConfigChanged(event, desc);
Eric Laurent81784c32012-11-19 14:55:58 -08006774}
6775
Glenn Kastendeca2ae2014-02-07 10:25:56 -08006776void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006777{
Eric Laurent81784c32012-11-19 14:55:58 -08006778 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
6779 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Andy Hunge5412692014-05-16 11:25:07 -07006780 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Andy Hungd330ee42015-04-20 13:23:41 -07006781 if (mChannelCount > FCC_8) {
6782 ALOGE("HAL channel count %d > %d", mChannelCount, FCC_8);
6783 }
Andy Hung463be252014-07-10 16:56:07 -07006784 mHALFormat = mInput->stream->common.get_format(&mInput->stream->common);
6785 mFormat = mHALFormat;
Andy Hungd330ee42015-04-20 13:23:41 -07006786 if (!audio_is_linear_pcm(mFormat)) {
6787 ALOGE("HAL format %#x is not linear pcm", mFormat);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07006788 }
Eric Laurent665470b2014-07-03 16:37:08 -07006789 mFrameSize = audio_stream_in_frame_size(mInput->stream);
Glenn Kasten548efc92012-11-29 08:48:51 -08006790 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
6791 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006792 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08006793 // 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 -07006794 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08006795 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006796 // A larger value should allow more old data to be read after a track calls start(),
6797 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07006798 //
6799 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08006800 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07006801 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07006802 free(mRsmpInBuffer);
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006803
6804 // TODO optimize audio capture buffer sizes ...
6805 // Here we calculate the size of the sliding buffer used as a source
6806 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
6807 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
6808 // be better to have it derived from the pipe depth in the long term.
6809 // The current value is higher than necessary. However it should not add to latency.
6810
Glenn Kasten85948432013-08-19 12:09:05 -07006811 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Andy Hung57446612015-04-19 23:56:46 -07006812 (void)posix_memalign(&mRsmpInBuffer, 32, (mRsmpInFramesP2 + mFrameCount - 1) * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006813
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006814 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
6815 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08006816}
6817
Glenn Kasten5f972c02014-01-13 09:59:31 -08006818uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08006819{
6820 Mutex::Autolock _l(mLock);
6821 if (initCheck() != NO_ERROR) {
6822 return 0;
6823 }
6824
6825 return mInput->stream->get_input_frames_lost(mInput->stream);
6826}
6827
6828uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
6829{
6830 Mutex::Autolock _l(mLock);
6831 uint32_t result = 0;
6832 if (getEffectChain_l(sessionId) != 0) {
6833 result = EFFECT_SESSION;
6834 }
6835
6836 for (size_t i = 0; i < mTracks.size(); ++i) {
6837 if (sessionId == mTracks[i]->sessionId()) {
6838 result |= TRACK_SESSION;
6839 break;
6840 }
6841 }
6842
6843 return result;
6844}
6845
6846KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
6847{
6848 KeyedVector<int, bool> ids;
6849 Mutex::Autolock _l(mLock);
6850 for (size_t j = 0; j < mTracks.size(); ++j) {
6851 sp<RecordThread::RecordTrack> track = mTracks[j];
6852 int sessionId = track->sessionId();
6853 if (ids.indexOfKey(sessionId) < 0) {
6854 ids.add(sessionId, true);
6855 }
6856 }
6857 return ids;
6858}
6859
6860AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
6861{
6862 Mutex::Autolock _l(mLock);
6863 AudioStreamIn *input = mInput;
6864 mInput = NULL;
6865 return input;
6866}
6867
6868// this method must always be called either with ThreadBase mLock held or inside the thread loop
6869audio_stream_t* AudioFlinger::RecordThread::stream() const
6870{
6871 if (mInput == NULL) {
6872 return NULL;
6873 }
6874 return &mInput->stream->common;
6875}
6876
6877status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6878{
6879 // only one chain per input thread
6880 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07006881 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08006882 return INVALID_OPERATION;
6883 }
6884 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07006885 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08006886 chain->setInBuffer(NULL);
6887 chain->setOutBuffer(NULL);
6888
6889 checkSuspendOnAddEffectChain_l(chain);
6890
Eric Laurent1b928682014-10-02 19:41:47 -07006891 // make sure enabled pre processing effects state is communicated to the HAL as we
6892 // just moved them to a new input stream.
6893 chain->syncHalEffectsState();
6894
Eric Laurent81784c32012-11-19 14:55:58 -08006895 mEffectChains.add(chain);
6896
6897 return NO_ERROR;
6898}
6899
6900size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6901{
6902 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
6903 ALOGW_IF(mEffectChains.size() != 1,
6904 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6905 chain.get(), mEffectChains.size(), this);
6906 if (mEffectChains.size() == 1) {
6907 mEffectChains.removeAt(0);
6908 }
6909 return 0;
6910}
6911
Eric Laurent1c333e22014-05-20 10:48:17 -07006912status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
6913 audio_patch_handle_t *handle)
6914{
6915 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07006916
6917 // store new device and send to effects
6918 mInDevice = patch->sources[0].ext.device.type;
Eric Laurent296fb132015-05-01 11:38:42 -07006919 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07006920 for (size_t i = 0; i < mEffectChains.size(); i++) {
6921 mEffectChains[i]->setDevice_l(mInDevice);
6922 }
6923
6924 // disable AEC and NS if the device is a BT SCO headset supporting those
6925 // pre processings
6926 if (mTracks.size() > 0) {
6927 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6928 mAudioFlinger->btNrecIsOff();
6929 for (size_t i = 0; i < mTracks.size(); i++) {
6930 sp<RecordTrack> track = mTracks[i];
6931 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
6932 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
6933 }
6934 }
6935
6936 // store new source and send to effects
6937 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
6938 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07006939 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07006940 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07006941 }
Eric Laurent054d9d32015-04-24 08:48:48 -07006942 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006943
Eric Laurent054d9d32015-04-24 08:48:48 -07006944 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006945 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
6946 status = hwDevice->create_audio_patch(hwDevice,
6947 patch->num_sources,
6948 patch->sources,
6949 patch->num_sinks,
6950 patch->sinks,
6951 handle);
6952 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07006953 char *address;
6954 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
6955 address = audio_device_address_to_parameter(
6956 patch->sources[0].ext.device.type,
6957 patch->sources[0].ext.device.address);
6958 } else {
6959 address = (char *)calloc(1, 1);
6960 }
6961 AudioParameter param = AudioParameter(String8(address));
6962 free(address);
6963 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING),
6964 (int)patch->sources[0].ext.device.type);
6965 param.addInt(String8(AUDIO_PARAMETER_STREAM_INPUT_SOURCE),
6966 (int)patch->sinks[0].ext.mix.usecase.source);
6967 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6968 param.toString().string());
6969 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07006970 }
Eric Laurent054d9d32015-04-24 08:48:48 -07006971
Eric Laurent296fb132015-05-01 11:38:42 -07006972 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
6973
Eric Laurent1c333e22014-05-20 10:48:17 -07006974 return status;
6975}
6976
6977status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
6978{
6979 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07006980
6981 mInDevice = AUDIO_DEVICE_NONE;
6982
Eric Laurent1c333e22014-05-20 10:48:17 -07006983 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
6984 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
6985 status = hwDevice->release_audio_patch(hwDevice, handle);
6986 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07006987 AudioParameter param;
6988 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
6989 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6990 param.toString().string());
Eric Laurent1c333e22014-05-20 10:48:17 -07006991 }
6992 return status;
6993}
6994
Eric Laurent83b88082014-06-20 18:31:16 -07006995void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
6996{
6997 Mutex::Autolock _l(mLock);
6998 mTracks.add(record);
6999}
7000
7001void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
7002{
7003 Mutex::Autolock _l(mLock);
7004 destroyTrack_l(record);
7005}
7006
7007void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
7008{
7009 ThreadBase::getAudioPortConfig(config);
7010 config->role = AUDIO_PORT_ROLE_SINK;
7011 config->ext.mix.hw_module = mInput->audioHwDev->handle();
7012 config->ext.mix.usecase.source = mAudioSource;
7013}
Eric Laurent1c333e22014-05-20 10:48:17 -07007014
Glenn Kasten63238ef2015-03-02 15:50:29 -08007015} // namespace android