blob: 0593e1b8692629821d54d223461df3e4baa6a5c6 [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;
Andy Hungf98ec8d2015-05-19 12:53:24 -0700712 const audio_channel_representation_t representation = audio_channel_mask_get_representation(mask);
713
714 switch (representation) {
715 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
716 if (output) {
717 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
718 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
719 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
720 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
721 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
722 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
723 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
724 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
725 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
726 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
727 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
728 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
729 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
730 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
731 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
732 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
733 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
734 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
735 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
736 } else {
737 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
738 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
739 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
740 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
741 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
742 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
743 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
744 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
745 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
746 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
747 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
748 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
749 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
750 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
751 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
752 }
753 const int len = s.length();
754 if (len > 2) {
755 char *str = s.lockBuffer(len); // needed?
756 s.unlockBuffer(len - 2); // remove trailing ", "
757 }
758 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800759 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700760 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
761 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
762 return s;
763 default:
764 s.appendFormat("unknown mask, representation:%d bits:%#x",
765 representation, audio_channel_mask_get_bits(mask));
766 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800767 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800768}
769
Glenn Kasten0f11b512014-01-31 16:18:54 -0800770void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800771{
772 const size_t SIZE = 256;
773 char buffer[SIZE];
774 String8 result;
775
776 bool locked = AudioFlinger::dumpTryLock(mLock);
777 if (!locked) {
Glenn Kasten97b7b752014-09-28 13:04:24 -0700778 dprintf(fd, "thread %p may be deadlocked\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -0800779 }
780
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800781 dprintf(fd, " Thread name: %s\n", mThreadName);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700782 dprintf(fd, " I/O handle: %d\n", mId);
783 dprintf(fd, " TID: %d\n", getTid());
784 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700785 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700786 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700787 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat));
Elliott Hughes87cebad2014-05-22 10:14:43 -0700788 dprintf(fd, " HAL buffer size: %u bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700789 dprintf(fd, " Channel count: %u\n", mChannelCount);
790 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800791 channelMaskToString(mChannelMask, mType != RECORD).string());
Glenn Kasten97b7b752014-09-28 13:04:24 -0700792 dprintf(fd, " Format: 0x%x (%s)\n", mFormat, formatToString(mFormat));
793 dprintf(fd, " Frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700794 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800795 size_t numConfig = mConfigEvents.size();
796 if (numConfig) {
797 for (size_t i = 0; i < numConfig; i++) {
798 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700799 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800800 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700801 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800802 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700803 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800804 }
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800805 dprintf(fd, " Output device: %#x (%s)\n", mOutDevice, devicesToString(mOutDevice).string());
806 dprintf(fd, " Input device: %#x (%s)\n", mInDevice, devicesToString(mInDevice).string());
807 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, sourceToString(mAudioSource));
Eric Laurent81784c32012-11-19 14:55:58 -0800808
809 if (locked) {
810 mLock.unlock();
811 }
812}
813
814void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
815{
816 const size_t SIZE = 256;
817 char buffer[SIZE];
818 String8 result;
819
Marco Nelissenb2208842014-02-07 14:00:50 -0800820 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000821 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800822 write(fd, buffer, strlen(buffer));
823
Marco Nelissenb2208842014-02-07 14:00:50 -0800824 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800825 sp<EffectChain> chain = mEffectChains[i];
826 if (chain != 0) {
827 chain->dump(fd, args);
828 }
829 }
830}
831
Marco Nelissene14a5d62013-10-03 08:51:24 -0700832void AudioFlinger::ThreadBase::acquireWakeLock(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800833{
834 Mutex::Autolock _l(mLock);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700835 acquireWakeLock_l(uid);
Eric Laurent81784c32012-11-19 14:55:58 -0800836}
837
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100838String16 AudioFlinger::ThreadBase::getWakeLockTag()
839{
840 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -0800841 case MIXER:
842 return String16("AudioMix");
843 case DIRECT:
844 return String16("AudioDirectOut");
845 case DUPLICATING:
846 return String16("AudioDup");
847 case RECORD:
848 return String16("AudioIn");
849 case OFFLOAD:
850 return String16("AudioOffload");
851 default:
852 ALOG_ASSERT(false);
853 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100854 }
855}
856
Marco Nelissene14a5d62013-10-03 08:51:24 -0700857void AudioFlinger::ThreadBase::acquireWakeLock_l(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800858{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800859 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800860 if (mPowerManager != 0) {
861 sp<IBinder> binder = new BBinder();
Marco Nelissene14a5d62013-10-03 08:51:24 -0700862 status_t status;
863 if (uid >= 0) {
Eric Laurent547789d2013-10-04 11:46:55 -0700864 status = mPowerManager->acquireWakeLockWithUid(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700865 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100866 getWakeLockTag(),
Marco Nelissene14a5d62013-10-03 08:51:24 -0700867 String16("media"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700868 uid,
869 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700870 } else {
Eric Laurent547789d2013-10-04 11:46:55 -0700871 status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700872 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100873 getWakeLockTag(),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700874 String16("media"),
875 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700876 }
Eric Laurent81784c32012-11-19 14:55:58 -0800877 if (status == NO_ERROR) {
878 mWakeLockToken = binder;
879 }
Glenn Kastend7dca052015-03-05 16:05:54 -0800880 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Eric Laurent81784c32012-11-19 14:55:58 -0800881 }
882}
883
884void AudioFlinger::ThreadBase::releaseWakeLock()
885{
886 Mutex::Autolock _l(mLock);
887 releaseWakeLock_l();
888}
889
890void AudioFlinger::ThreadBase::releaseWakeLock_l()
891{
892 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800893 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -0800894 if (mPowerManager != 0) {
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700895 mPowerManager->releaseWakeLock(mWakeLockToken, 0,
896 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800897 }
898 mWakeLockToken.clear();
899 }
900}
901
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800902void AudioFlinger::ThreadBase::updateWakeLockUids(const SortedVector<int> &uids) {
903 Mutex::Autolock _l(mLock);
904 updateWakeLockUids_l(uids);
905}
906
907void AudioFlinger::ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -0700908 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800909 // use checkService() to avoid blocking if power service is not up yet
910 sp<IBinder> binder =
911 defaultServiceManager()->checkService(String16("power"));
912 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800913 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800914 } else {
915 mPowerManager = interface_cast<IPowerManager>(binder);
916 binder->linkToDeath(mDeathRecipient);
917 }
918 }
919}
920
921void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<int> &uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800922 getPowerManager_l();
923 if (mWakeLockToken == NULL) {
924 ALOGE("no wake lock to update!");
925 return;
926 }
927 if (mPowerManager != 0) {
928 sp<IBinder> binder = new BBinder();
929 status_t status;
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700930 status = mPowerManager->updateWakeLockUids(mWakeLockToken, uids.size(), uids.array(),
931 true /* FIXME force oneway contrary to .aidl */);
Glenn Kastend7dca052015-03-05 16:05:54 -0800932 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800933 }
934}
935
Eric Laurent81784c32012-11-19 14:55:58 -0800936void AudioFlinger::ThreadBase::clearPowerManager()
937{
938 Mutex::Autolock _l(mLock);
939 releaseWakeLock_l();
940 mPowerManager.clear();
941}
942
Glenn Kasten0f11b512014-01-31 16:18:54 -0800943void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800944{
945 sp<ThreadBase> thread = mThread.promote();
946 if (thread != 0) {
947 thread->clearPowerManager();
948 }
949 ALOGW("power manager service died !!!");
950}
951
952void AudioFlinger::ThreadBase::setEffectSuspended(
953 const effect_uuid_t *type, bool suspend, int sessionId)
954{
955 Mutex::Autolock _l(mLock);
956 setEffectSuspended_l(type, suspend, sessionId);
957}
958
959void AudioFlinger::ThreadBase::setEffectSuspended_l(
960 const effect_uuid_t *type, bool suspend, int sessionId)
961{
962 sp<EffectChain> chain = getEffectChain_l(sessionId);
963 if (chain != 0) {
964 if (type != NULL) {
965 chain->setEffectSuspended_l(type, suspend);
966 } else {
967 chain->setEffectSuspendedAll_l(suspend);
968 }
969 }
970
971 updateSuspendedSessions_l(type, suspend, sessionId);
972}
973
974void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
975{
976 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
977 if (index < 0) {
978 return;
979 }
980
981 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
982 mSuspendedSessions.valueAt(index);
983
984 for (size_t i = 0; i < sessionEffects.size(); i++) {
985 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
986 for (int j = 0; j < desc->mRefCount; j++) {
987 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
988 chain->setEffectSuspendedAll_l(true);
989 } else {
990 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
991 desc->mType.timeLow);
992 chain->setEffectSuspended_l(&desc->mType, true);
993 }
994 }
995 }
996}
997
998void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
999 bool suspend,
1000 int sessionId)
1001{
1002 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1003
1004 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1005
1006 if (suspend) {
1007 if (index >= 0) {
1008 sessionEffects = mSuspendedSessions.valueAt(index);
1009 } else {
1010 mSuspendedSessions.add(sessionId, sessionEffects);
1011 }
1012 } else {
1013 if (index < 0) {
1014 return;
1015 }
1016 sessionEffects = mSuspendedSessions.valueAt(index);
1017 }
1018
1019
1020 int key = EffectChain::kKeyForSuspendAll;
1021 if (type != NULL) {
1022 key = type->timeLow;
1023 }
1024 index = sessionEffects.indexOfKey(key);
1025
1026 sp<SuspendedSessionDesc> desc;
1027 if (suspend) {
1028 if (index >= 0) {
1029 desc = sessionEffects.valueAt(index);
1030 } else {
1031 desc = new SuspendedSessionDesc();
1032 if (type != NULL) {
1033 desc->mType = *type;
1034 }
1035 sessionEffects.add(key, desc);
1036 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1037 }
1038 desc->mRefCount++;
1039 } else {
1040 if (index < 0) {
1041 return;
1042 }
1043 desc = sessionEffects.valueAt(index);
1044 if (--desc->mRefCount == 0) {
1045 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1046 sessionEffects.removeItemsAt(index);
1047 if (sessionEffects.isEmpty()) {
1048 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1049 sessionId);
1050 mSuspendedSessions.removeItem(sessionId);
1051 }
1052 }
1053 }
1054 if (!sessionEffects.isEmpty()) {
1055 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1056 }
1057}
1058
1059void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1060 bool enabled,
1061 int sessionId)
1062{
1063 Mutex::Autolock _l(mLock);
1064 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1065}
1066
1067void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1068 bool enabled,
1069 int sessionId)
1070{
1071 if (mType != RECORD) {
1072 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1073 // another session. This gives the priority to well behaved effect control panels
1074 // and applications not using global effects.
1075 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1076 // global effects
1077 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
1078 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1079 }
1080 }
1081
1082 sp<EffectChain> chain = getEffectChain_l(sessionId);
1083 if (chain != 0) {
1084 chain->checkSuspendOnEffectEnabled(effect, enabled);
1085 }
1086}
1087
1088// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1089sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1090 const sp<AudioFlinger::Client>& client,
1091 const sp<IEffectClient>& effectClient,
1092 int32_t priority,
1093 int sessionId,
1094 effect_descriptor_t *desc,
1095 int *enabled,
Glenn Kasten9156ef32013-08-06 15:39:08 -07001096 status_t *status)
Eric Laurent81784c32012-11-19 14:55:58 -08001097{
1098 sp<EffectModule> effect;
1099 sp<EffectHandle> handle;
1100 status_t lStatus;
1101 sp<EffectChain> chain;
1102 bool chainCreated = false;
1103 bool effectCreated = false;
1104 bool effectRegistered = false;
1105
1106 lStatus = initCheck();
1107 if (lStatus != NO_ERROR) {
1108 ALOGW("createEffect_l() Audio driver not initialized.");
1109 goto Exit;
1110 }
1111
Andy Hung98ef9782014-03-04 14:46:50 -08001112 // Reject any effect on Direct output threads for now, since the format of
1113 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1114 if (mType == DIRECT) {
1115 ALOGW("createEffect_l() Cannot add effect %s on Direct output type thread %s",
Glenn Kastend7dca052015-03-05 16:05:54 -08001116 desc->name, mThreadName);
Andy Hung98ef9782014-03-04 14:46:50 -08001117 lStatus = BAD_VALUE;
1118 goto Exit;
1119 }
1120
Andy Hung389cfdb2014-08-07 17:49:53 -07001121 // Reject any effect on mixer or duplicating multichannel sinks.
Andy Hung9a592762014-07-21 21:56:01 -07001122 // TODO: fix both format and multichannel issues with effects.
Andy Hung389cfdb2014-08-07 17:49:53 -07001123 if ((mType == MIXER || mType == DUPLICATING) && mChannelCount != FCC_2) {
1124 ALOGW("createEffect_l() Cannot add effect %s for multichannel(%d) %s threads",
1125 desc->name, mChannelCount, mType == MIXER ? "MIXER" : "DUPLICATING");
Andy Hung9a592762014-07-21 21:56:01 -07001126 lStatus = BAD_VALUE;
1127 goto Exit;
1128 }
1129
Eric Laurent5baf2af2013-09-12 17:37:00 -07001130 // Allow global effects only on offloaded and mixer threads
1131 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1132 switch (mType) {
1133 case MIXER:
1134 case OFFLOAD:
1135 break;
1136 case DIRECT:
1137 case DUPLICATING:
1138 case RECORD:
1139 default:
Glenn Kastend7dca052015-03-05 16:05:54 -08001140 ALOGW("createEffect_l() Cannot add global effect %s on thread %s",
1141 desc->name, mThreadName);
Eric Laurent5baf2af2013-09-12 17:37:00 -07001142 lStatus = BAD_VALUE;
1143 goto Exit;
1144 }
Eric Laurent81784c32012-11-19 14:55:58 -08001145 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07001146
Eric Laurent81784c32012-11-19 14:55:58 -08001147 // Only Pre processor effects are allowed on input threads and only on input threads
1148 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
1149 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
1150 desc->name, desc->flags, mType);
1151 lStatus = BAD_VALUE;
1152 goto Exit;
1153 }
1154
1155 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1156
1157 { // scope for mLock
1158 Mutex::Autolock _l(mLock);
1159
1160 // check for existing effect chain with the requested audio session
1161 chain = getEffectChain_l(sessionId);
1162 if (chain == 0) {
1163 // create a new chain for this session
1164 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1165 chain = new EffectChain(this, sessionId);
1166 addEffectChain_l(chain);
1167 chain->setStrategy(getStrategyForSession_l(sessionId));
1168 chainCreated = true;
1169 } else {
1170 effect = chain->getEffectFromDesc_l(desc);
1171 }
1172
1173 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1174
1175 if (effect == 0) {
1176 int id = mAudioFlinger->nextUniqueId();
1177 // Check CPU and memory usage
1178 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
1179 if (lStatus != NO_ERROR) {
1180 goto Exit;
1181 }
1182 effectRegistered = true;
1183 // create a new effect module if none present in the chain
1184 effect = new EffectModule(this, chain, desc, id, sessionId);
1185 lStatus = effect->status();
1186 if (lStatus != NO_ERROR) {
1187 goto Exit;
1188 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07001189 effect->setOffloaded(mType == OFFLOAD, mId);
1190
Eric Laurent81784c32012-11-19 14:55:58 -08001191 lStatus = chain->addEffect_l(effect);
1192 if (lStatus != NO_ERROR) {
1193 goto Exit;
1194 }
1195 effectCreated = true;
1196
1197 effect->setDevice(mOutDevice);
1198 effect->setDevice(mInDevice);
1199 effect->setMode(mAudioFlinger->getMode());
1200 effect->setAudioSource(mAudioSource);
1201 }
1202 // create effect handle and connect it to effect module
1203 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001204 lStatus = handle->initCheck();
1205 if (lStatus == OK) {
1206 lStatus = effect->addHandle(handle.get());
1207 }
Eric Laurent81784c32012-11-19 14:55:58 -08001208 if (enabled != NULL) {
1209 *enabled = (int)effect->isEnabled();
1210 }
1211 }
1212
1213Exit:
1214 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1215 Mutex::Autolock _l(mLock);
1216 if (effectCreated) {
1217 chain->removeEffect_l(effect);
1218 }
1219 if (effectRegistered) {
1220 AudioSystem::unregisterEffect(effect->id());
1221 }
1222 if (chainCreated) {
1223 removeEffectChain_l(chain);
1224 }
1225 handle.clear();
1226 }
1227
Glenn Kasten9156ef32013-08-06 15:39:08 -07001228 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001229 return handle;
1230}
1231
1232sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
1233{
1234 Mutex::Autolock _l(mLock);
1235 return getEffect_l(sessionId, effectId);
1236}
1237
1238sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
1239{
1240 sp<EffectChain> chain = getEffectChain_l(sessionId);
1241 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1242}
1243
1244// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1245// PlaybackThread::mLock held
1246status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1247{
1248 // check for existing effect chain with the requested audio session
1249 int sessionId = effect->sessionId();
1250 sp<EffectChain> chain = getEffectChain_l(sessionId);
1251 bool chainCreated = false;
1252
Eric Laurent5baf2af2013-09-12 17:37:00 -07001253 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
1254 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
1255 this, effect->desc().name, effect->desc().flags);
1256
Eric Laurent81784c32012-11-19 14:55:58 -08001257 if (chain == 0) {
1258 // create a new chain for this session
1259 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1260 chain = new EffectChain(this, sessionId);
1261 addEffectChain_l(chain);
1262 chain->setStrategy(getStrategyForSession_l(sessionId));
1263 chainCreated = true;
1264 }
1265 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1266
1267 if (chain->getEffectFromId_l(effect->id()) != 0) {
1268 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1269 this, effect->desc().name, chain.get());
1270 return BAD_VALUE;
1271 }
1272
Eric Laurent5baf2af2013-09-12 17:37:00 -07001273 effect->setOffloaded(mType == OFFLOAD, mId);
1274
Eric Laurent81784c32012-11-19 14:55:58 -08001275 status_t status = chain->addEffect_l(effect);
1276 if (status != NO_ERROR) {
1277 if (chainCreated) {
1278 removeEffectChain_l(chain);
1279 }
1280 return status;
1281 }
1282
1283 effect->setDevice(mOutDevice);
1284 effect->setDevice(mInDevice);
1285 effect->setMode(mAudioFlinger->getMode());
1286 effect->setAudioSource(mAudioSource);
1287 return NO_ERROR;
1288}
1289
1290void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
1291
1292 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
1293 effect_descriptor_t desc = effect->desc();
1294 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1295 detachAuxEffect_l(effect->id());
1296 }
1297
1298 sp<EffectChain> chain = effect->chain().promote();
1299 if (chain != 0) {
1300 // remove effect chain if removing last effect
1301 if (chain->removeEffect_l(effect) == 0) {
1302 removeEffectChain_l(chain);
1303 }
1304 } else {
1305 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1306 }
1307}
1308
1309void AudioFlinger::ThreadBase::lockEffectChains_l(
1310 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1311{
1312 effectChains = mEffectChains;
1313 for (size_t i = 0; i < mEffectChains.size(); i++) {
1314 mEffectChains[i]->lock();
1315 }
1316}
1317
1318void AudioFlinger::ThreadBase::unlockEffectChains(
1319 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1320{
1321 for (size_t i = 0; i < effectChains.size(); i++) {
1322 effectChains[i]->unlock();
1323 }
1324}
1325
1326sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
1327{
1328 Mutex::Autolock _l(mLock);
1329 return getEffectChain_l(sessionId);
1330}
1331
1332sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const
1333{
1334 size_t size = mEffectChains.size();
1335 for (size_t i = 0; i < size; i++) {
1336 if (mEffectChains[i]->sessionId() == sessionId) {
1337 return mEffectChains[i];
1338 }
1339 }
1340 return 0;
1341}
1342
1343void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1344{
1345 Mutex::Autolock _l(mLock);
1346 size_t size = mEffectChains.size();
1347 for (size_t i = 0; i < size; i++) {
1348 mEffectChains[i]->setMode_l(mode);
1349 }
1350}
1351
Eric Laurent83b88082014-06-20 18:31:16 -07001352void AudioFlinger::ThreadBase::getAudioPortConfig(struct audio_port_config *config)
1353{
1354 config->type = AUDIO_PORT_TYPE_MIX;
1355 config->ext.mix.handle = mId;
1356 config->sample_rate = mSampleRate;
1357 config->format = mFormat;
1358 config->channel_mask = mChannelMask;
1359 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1360 AUDIO_PORT_CONFIG_FORMAT;
1361}
1362
Eric Laurent72e3f392015-05-20 14:43:50 -07001363void AudioFlinger::ThreadBase::systemReady()
1364{
1365 Mutex::Autolock _l(mLock);
1366 if (mSystemReady) {
1367 return;
1368 }
1369 mSystemReady = true;
1370
1371 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1372 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1373 }
1374 mPendingConfigEvents.clear();
1375}
1376
Eric Laurent83b88082014-06-20 18:31:16 -07001377
Eric Laurent81784c32012-11-19 14:55:58 -08001378// ----------------------------------------------------------------------------
1379// Playback
1380// ----------------------------------------------------------------------------
1381
1382AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1383 AudioStreamOut* output,
1384 audio_io_handle_t id,
1385 audio_devices_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07001386 type_t type,
1387 bool systemReady)
1388 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type, systemReady),
Andy Hung2098f272014-02-27 14:00:06 -08001389 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001390 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001391 mMixerBuffer(NULL),
1392 mMixerBufferSize(0),
1393 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1394 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001395 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001396 mEffectBuffer(NULL),
1397 mEffectBufferSize(0),
1398 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1399 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001400 mSuspended(0), mBytesWritten(0),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001401 mActiveTracksGeneration(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001402 // mStreamTypes[] initialized in constructor body
1403 mOutput(output),
1404 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
1405 mMixerStatus(MIXER_IDLE),
1406 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001407 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001408 mBytesRemaining(0),
1409 mCurrentWriteLength(0),
1410 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001411 mWriteAckSequence(0),
1412 mDrainSequence(0),
Eric Laurentede6c3b2013-09-19 14:37:46 -07001413 mSignalPending(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001414 mScreenState(AudioFlinger::mScreenState),
1415 // index 0 is reserved for normal mixer's submix
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001416 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1),
Eric Laurentd1f69b02014-12-15 14:33:13 -08001417 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001418 // mLatchD, mLatchQ,
1419 mLatchDValid(false), mLatchQValid(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001420{
Glenn Kastend7dca052015-03-05 16:05:54 -08001421 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1422 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001423
1424 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1425 // it would be safer to explicitly pass initial masterVolume/masterMute as
1426 // parameter.
1427 //
1428 // If the HAL we are using has support for master volume or master mute,
1429 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1430 // and the mute set to false).
1431 mMasterVolume = audioFlinger->masterVolume_l();
1432 mMasterMute = audioFlinger->masterMute_l();
1433 if (mOutput && mOutput->audioHwDev) {
1434 if (mOutput->audioHwDev->canSetMasterVolume()) {
1435 mMasterVolume = 1.0;
1436 }
1437
1438 if (mOutput->audioHwDev->canSetMasterMute()) {
1439 mMasterMute = false;
1440 }
1441 }
1442
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001443 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001444
Eric Laurent223fd5c2014-11-11 13:43:36 -08001445 // ++ operator does not compile
Glenn Kasten66e46352014-01-16 17:44:23 -08001446 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001447 stream = (audio_stream_type_t) (stream + 1)) {
1448 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1449 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1450 }
Eric Laurent81784c32012-11-19 14:55:58 -08001451}
1452
1453AudioFlinger::PlaybackThread::~PlaybackThread()
1454{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001455 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001456 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001457 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001458 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001459}
1460
1461void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1462{
1463 dumpInternals(fd, args);
1464 dumpTracks(fd, args);
1465 dumpEffectChains(fd, args);
1466}
1467
Glenn Kasten0f11b512014-01-31 16:18:54 -08001468void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001469{
1470 const size_t SIZE = 256;
1471 char buffer[SIZE];
1472 String8 result;
1473
Marco Nelissenb2208842014-02-07 14:00:50 -08001474 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001475 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1476 const stream_type_t *st = &mStreamTypes[i];
1477 if (i > 0) {
1478 result.appendFormat(", ");
1479 }
1480 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1481 if (st->mute) {
1482 result.append("M");
1483 }
1484 }
1485 result.append("\n");
1486 write(fd, result.string(), result.length());
1487 result.clear();
1488
Eric Laurent81784c32012-11-19 14:55:58 -08001489 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1490 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001491 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001492 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001493
1494 size_t numtracks = mTracks.size();
1495 size_t numactive = mActiveTracks.size();
Elliott Hughes87cebad2014-05-22 10:14:43 -07001496 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001497 size_t numactiveseen = 0;
1498 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07001499 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08001500 Track::appendDumpHeader(result);
1501 for (size_t i = 0; i < numtracks; ++i) {
1502 sp<Track> track = mTracks[i];
1503 if (track != 0) {
1504 bool active = mActiveTracks.indexOf(track) >= 0;
1505 if (active) {
1506 numactiveseen++;
1507 }
1508 track->dump(buffer, SIZE, active);
1509 result.append(buffer);
1510 }
1511 }
1512 } else {
1513 result.append("\n");
1514 }
1515 if (numactiveseen != numactive) {
1516 // some tracks in the active list were not in the tracks list
1517 snprintf(buffer, SIZE, " The following tracks are in the active list but"
1518 " not in the track list\n");
1519 result.append(buffer);
1520 Track::appendDumpHeader(result);
1521 for (size_t i = 0; i < numactive; ++i) {
1522 sp<Track> track = mActiveTracks[i].promote();
1523 if (track != 0 && mTracks.indexOf(track) < 0) {
1524 track->dump(buffer, SIZE, true);
1525 result.append(buffer);
1526 }
1527 }
1528 }
1529
1530 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001531}
1532
1533void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1534{
Glenn Kasten97b7b752014-09-28 13:04:24 -07001535 dprintf(fd, "\nOutput thread %p type %d (%s):\n", this, type(), threadTypeToString(type()));
Glenn Kasten44182c22015-03-05 17:12:23 -08001536
1537 dumpBase(fd, args);
1538
Elliott Hughes87cebad2014-05-22 10:14:43 -07001539 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
1540 dprintf(fd, " Last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1541 dprintf(fd, " Total writes: %d\n", mNumWrites);
1542 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1543 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1544 dprintf(fd, " Suspend count: %d\n", mSuspended);
1545 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1546 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1547 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1548 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001549 AudioStreamOut *output = mOutput;
1550 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
1551 String8 flagsAsString = outputFlagsToString(flags);
1552 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n", output, flags, flagsAsString.string());
Eric Laurent81784c32012-11-19 14:55:58 -08001553}
1554
1555// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001556
1557void AudioFlinger::PlaybackThread::onFirstRef()
1558{
Glenn Kastend7dca052015-03-05 16:05:54 -08001559 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001560}
1561
1562// ThreadBase virtuals
1563void AudioFlinger::PlaybackThread::preExit()
1564{
1565 ALOGV(" preExit()");
1566 // FIXME this is using hard-coded strings but in the future, this functionality will be
1567 // converted to use audio HAL extensions required to support tunneling
1568 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1569}
1570
1571// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1572sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1573 const sp<AudioFlinger::Client>& client,
1574 audio_stream_type_t streamType,
1575 uint32_t sampleRate,
1576 audio_format_t format,
1577 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001578 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001579 const sp<IMemory>& sharedBuffer,
1580 int sessionId,
1581 IAudioFlinger::track_flags_t *flags,
1582 pid_t tid,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001583 int uid,
Eric Laurent81784c32012-11-19 14:55:58 -08001584 status_t *status)
1585{
Glenn Kasten74935e42013-12-19 08:56:45 -08001586 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001587 sp<Track> track;
1588 status_t lStatus;
1589
1590 bool isTimed = (*flags & IAudioFlinger::TRACK_TIMED) != 0;
1591
1592 // client expresses a preference for FAST, but we get the final say
1593 if (*flags & IAudioFlinger::TRACK_FAST) {
1594 if (
1595 // not timed
1596 (!isTimed) &&
1597 // either of these use cases:
1598 (
1599 // use case 1: shared buffer with any frame count
1600 (
1601 (sharedBuffer != 0)
1602 ) ||
Glenn Kasten1dfe2f92015-03-09 12:03:14 -07001603 // use case 2: frame count is default or at least as large as HAL
Eric Laurent81784c32012-11-19 14:55:58 -08001604 (
Glenn Kasten1dfe2f92015-03-09 12:03:14 -07001605 // we formerly checked for a callback handler (non-0 tid),
1606 // but that is no longer required for TRANSFER_OBTAIN mode
Eric Laurent81784c32012-11-19 14:55:58 -08001607 ((frameCount == 0) ||
Glenn Kastenb5fed682013-12-03 09:06:43 -08001608 (frameCount >= mFrameCount))
Eric Laurent81784c32012-11-19 14:55:58 -08001609 )
1610 ) &&
1611 // PCM data
1612 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07001613 // TODO: extract as a data library function that checks that a computationally
1614 // expensive downmixer is not required: isFastOutputChannelConversion()
Andy Hung9a592762014-07-21 21:56:01 -07001615 (channelMask == mChannelMask ||
Andy Hung1f439e12015-05-19 12:57:41 -07001616 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
1617 (channelMask == AUDIO_CHANNEL_OUT_MONO
1618 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001619 // hardware sample rate
1620 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001621 // normal mixer has an associated fast mixer
1622 hasFastMixer() &&
1623 // there are sufficient fast track slots available
1624 (mFastTrackAvailMask != 0)
1625 // FIXME test that MixerThread for this fast track has a capable output HAL
1626 // FIXME add a permission test also?
1627 ) {
1628 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1629 if (frameCount == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001630 // read the fast track multiplier property the first time it is needed
1631 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1632 if (ok != 0) {
1633 ALOGE("%s pthread_once failed: %d", __func__, ok);
1634 }
1635 frameCount = mFrameCount * sFastTrackMultiplier;
Eric Laurent81784c32012-11-19 14:55:58 -08001636 }
1637 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
1638 frameCount, mFrameCount);
1639 } else {
1640 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
Andy Hung6146c082014-03-18 11:56:15 -07001641 "mFrameCount=%d format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
1642 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001643 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Andy Hung6146c082014-03-18 11:56:15 -07001644 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001645 audio_is_linear_pcm(format),
1646 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
1647 *flags &= ~IAudioFlinger::TRACK_FAST;
Andy Hung0e48d252015-01-26 11:43:15 -08001648 }
1649 }
1650 // For normal PCM streaming tracks, update minimum frame count.
1651 // For compatibility with AudioTrack calculation, buffer depth is forced
1652 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1653 // This is probably too conservative, but legacy application code may depend on it.
1654 // If you change this calculation, also review the start threshold which is related.
1655 if (!(*flags & IAudioFlinger::TRACK_FAST)
1656 && audio_is_linear_pcm(format) && sharedBuffer == 0) {
Andy Hung8edb8dc2015-03-26 19:13:55 -07001657 // this must match AudioTrack.cpp calculateMinFrameCount().
1658 // TODO: Move to a common library
Eric Laurent81784c32012-11-19 14:55:58 -08001659 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1660 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1661 if (minBufCount < 2) {
1662 minBufCount = 2;
1663 }
Andy Hung8edb8dc2015-03-26 19:13:55 -07001664 // For normal mixing tracks, if speed is > 1.0f (normal), AudioTrack
1665 // or the client should compute and pass in a larger buffer request.
Andy Hung0e48d252015-01-26 11:43:15 -08001666 size_t minFrameCount =
Andy Hung8edb8dc2015-03-26 19:13:55 -07001667 minBufCount * sourceFramesNeededWithTimestretch(
1668 sampleRate, mNormalFrameCount,
1669 mSampleRate, AUDIO_TIMESTRETCH_SPEED_NORMAL /*speed*/);
Andy Hung0e48d252015-01-26 11:43:15 -08001670 if (frameCount < minFrameCount) { // including frameCount == 0
Eric Laurent81784c32012-11-19 14:55:58 -08001671 frameCount = minFrameCount;
1672 }
Eric Laurent81784c32012-11-19 14:55:58 -08001673 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001674 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001675
Glenn Kastenc3df8382014-03-13 15:05:25 -07001676 switch (mType) {
1677
1678 case DIRECT:
Glenn Kasten993fa062014-05-02 11:14:34 -07001679 if (audio_is_linear_pcm(format)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001680 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001681 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1682 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001683 sampleRate, format, channelMask, mOutput, mFormat);
1684 lStatus = BAD_VALUE;
1685 goto Exit;
1686 }
1687 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001688 break;
1689
1690 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001691 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001692 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1693 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001694 sampleRate, format, channelMask, mOutput, mFormat);
1695 lStatus = BAD_VALUE;
1696 goto Exit;
1697 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001698 break;
1699
1700 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07001701 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001702 ALOGE("createTrack_l() Bad parameter: format %#x \""
1703 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001704 format, mOutput, mFormat);
1705 lStatus = BAD_VALUE;
1706 goto Exit;
1707 }
Andy Hungcd044842014-08-07 11:04:34 -07001708 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08001709 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1710 lStatus = BAD_VALUE;
1711 goto Exit;
1712 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001713 break;
1714
Eric Laurent81784c32012-11-19 14:55:58 -08001715 }
1716
1717 lStatus = initCheck();
1718 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07001719 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08001720 goto Exit;
1721 }
1722
1723 { // scope for mLock
1724 Mutex::Autolock _l(mLock);
1725
1726 // all tracks in same audio session must share the same routing strategy otherwise
1727 // conflicts will happen when tracks are moved from one output to another by audio policy
1728 // manager
1729 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1730 for (size_t i = 0; i < mTracks.size(); ++i) {
1731 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07001732 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001733 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1734 if (sessionId == t->sessionId() && strategy != actual) {
1735 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1736 strategy, actual);
1737 lStatus = BAD_VALUE;
1738 goto Exit;
1739 }
1740 }
1741 }
1742
1743 if (!isTimed) {
1744 track = new Track(this, client, streamType, sampleRate, format,
Eric Laurent83b88082014-06-20 18:31:16 -07001745 channelMask, frameCount, NULL, sharedBuffer,
1746 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08001747 } else {
1748 track = TimedTrack::create(this, client, streamType, sampleRate, format,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001749 channelMask, frameCount, sharedBuffer, sessionId, uid);
Eric Laurent81784c32012-11-19 14:55:58 -08001750 }
Glenn Kasten03003332013-08-06 15:40:54 -07001751
1752 // new Track always returns non-NULL,
1753 // but TimedTrack::create() is a factory that could fail by returning NULL
1754 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
1755 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08001756 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001757 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08001758 goto Exit;
1759 }
1760 mTracks.add(track);
1761
1762 sp<EffectChain> chain = getEffectChain_l(sessionId);
1763 if (chain != 0) {
1764 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1765 track->setMainBuffer(chain->inBuffer());
1766 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1767 chain->incTrackCnt();
1768 }
1769
1770 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1771 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1772 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1773 // so ask activity manager to do this on our behalf
1774 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1775 }
1776 }
1777
1778 lStatus = NO_ERROR;
1779
1780Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001781 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001782 return track;
1783}
1784
1785uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1786{
1787 return latency;
1788}
1789
1790uint32_t AudioFlinger::PlaybackThread::latency() const
1791{
1792 Mutex::Autolock _l(mLock);
1793 return latency_l();
1794}
1795uint32_t AudioFlinger::PlaybackThread::latency_l() const
1796{
1797 if (initCheck() == NO_ERROR) {
1798 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
1799 } else {
1800 return 0;
1801 }
1802}
1803
1804void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1805{
1806 Mutex::Autolock _l(mLock);
1807 // Don't apply master volume in SW if our HAL can do it for us.
1808 if (mOutput && mOutput->audioHwDev &&
1809 mOutput->audioHwDev->canSetMasterVolume()) {
1810 mMasterVolume = 1.0;
1811 } else {
1812 mMasterVolume = value;
1813 }
1814}
1815
1816void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1817{
1818 Mutex::Autolock _l(mLock);
1819 // Don't apply master mute in SW if our HAL can do it for us.
1820 if (mOutput && mOutput->audioHwDev &&
1821 mOutput->audioHwDev->canSetMasterMute()) {
1822 mMasterMute = false;
1823 } else {
1824 mMasterMute = muted;
1825 }
1826}
1827
1828void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
1829{
1830 Mutex::Autolock _l(mLock);
1831 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001832 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001833}
1834
1835void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
1836{
1837 Mutex::Autolock _l(mLock);
1838 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001839 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001840}
1841
1842float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
1843{
1844 Mutex::Autolock _l(mLock);
1845 return mStreamTypes[stream].volume;
1846}
1847
1848// addTrack_l() must be called with ThreadBase::mLock held
1849status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1850{
1851 status_t status = ALREADY_EXISTS;
1852
1853 // set retry count for buffer fill
1854 track->mRetryCount = kMaxTrackStartupRetries;
1855 if (mActiveTracks.indexOf(track) < 0) {
1856 // the track is newly added, make sure it fills up all its
1857 // buffers before playing. This is to ensure the client will
1858 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07001859 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001860 TrackBase::track_state state = track->mState;
1861 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08001862 status = AudioSystem::startOutput(mId, track->streamType(),
1863 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001864 mLock.lock();
1865 // abort track was stopped/paused while we released the lock
1866 if (state != track->mState) {
1867 if (status == NO_ERROR) {
1868 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08001869 AudioSystem::stopOutput(mId, track->streamType(),
1870 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001871 mLock.lock();
1872 }
1873 return INVALID_OPERATION;
1874 }
1875 // abort if start is rejected by audio policy manager
1876 if (status != NO_ERROR) {
1877 return PERMISSION_DENIED;
1878 }
1879#ifdef ADD_BATTERY_DATA
1880 // to track the speaker usage
1881 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
1882#endif
1883 }
1884
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001885 track->mFillingUpStatus = track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent81784c32012-11-19 14:55:58 -08001886 track->mResetDone = false;
1887 track->mPresentationCompleteFrames = 0;
1888 mActiveTracks.add(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001889 mWakeLockUids.add(track->uid());
1890 mActiveTracksGeneration++;
Eric Laurentfd477972013-10-25 18:10:40 -07001891 mLatestActiveTrack = track;
Eric Laurentd0107bc2013-06-11 14:38:48 -07001892 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1893 if (chain != 0) {
1894 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
1895 track->sessionId());
1896 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08001897 }
1898
1899 status = NO_ERROR;
1900 }
1901
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08001902 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001903 return status;
1904}
1905
Eric Laurentbfb1b832013-01-07 09:53:42 -08001906bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08001907{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001908 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08001909 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001910 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
1911 track->mState = TrackBase::STOPPED;
1912 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08001913 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07001914 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001915 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08001916 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001917
1918 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08001919}
1920
1921void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1922{
1923 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
1924 mTracks.remove(track);
1925 deleteTrackName_l(track->name());
1926 // redundant as track is about to be destroyed, for dumpsys only
1927 track->mName = -1;
1928 if (track->isFastTrack()) {
1929 int index = track->mFastIndex;
1930 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
1931 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1932 mFastTrackAvailMask |= 1 << index;
1933 // redundant as track is about to be destroyed, for dumpsys only
1934 track->mFastIndex = -1;
1935 }
1936 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1937 if (chain != 0) {
1938 chain->decTrackCnt();
1939 }
1940}
1941
Eric Laurentede6c3b2013-09-19 14:37:46 -07001942void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001943{
1944 // Thread could be blocked waiting for async
1945 // so signal it to handle state changes immediately
1946 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1947 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1948 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001949 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001950}
1951
Eric Laurent81784c32012-11-19 14:55:58 -08001952String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1953{
Eric Laurent81784c32012-11-19 14:55:58 -08001954 Mutex::Autolock _l(mLock);
1955 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07001956 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08001957 }
1958
Glenn Kastend8ea6992013-07-16 14:17:15 -07001959 char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
1960 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08001961 free(s);
1962 return out_s8;
1963}
1964
Eric Laurent73e26b62015-04-27 16:55:58 -07001965void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event) {
1966 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
1967 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08001968
Eric Laurent73e26b62015-04-27 16:55:58 -07001969 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08001970
1971 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07001972 case AUDIO_OUTPUT_OPENED:
1973 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07001974 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07001975 desc->mChannelMask = mChannelMask;
1976 desc->mSamplingRate = mSampleRate;
1977 desc->mFormat = mFormat;
1978 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08001979 // AudioFlinger::frameCount(audio_io_handle_t)
Eric Laurent73e26b62015-04-27 16:55:58 -07001980 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001981 break;
1982
Eric Laurent73e26b62015-04-27 16:55:58 -07001983 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08001984 default:
1985 break;
1986 }
Eric Laurent73e26b62015-04-27 16:55:58 -07001987 mAudioFlinger->ioConfigChanged(event, desc);
Eric Laurent81784c32012-11-19 14:55:58 -08001988}
1989
Eric Laurentbfb1b832013-01-07 09:53:42 -08001990void AudioFlinger::PlaybackThread::writeCallback()
1991{
1992 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001993 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001994}
1995
1996void AudioFlinger::PlaybackThread::drainCallback()
1997{
1998 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001999 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002000}
2001
Eric Laurent3b4529e2013-09-05 18:09:19 -07002002void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002003{
2004 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002005 // reject out of sequence requests
2006 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2007 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002008 mWaitWorkCV.signal();
2009 }
2010}
2011
Eric Laurent3b4529e2013-09-05 18:09:19 -07002012void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002013{
2014 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002015 // reject out of sequence requests
2016 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
2017 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002018 mWaitWorkCV.signal();
2019 }
2020}
2021
2022// static
2023int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
Glenn Kasten0f11b512014-01-31 16:18:54 -08002024 void *param __unused,
Eric Laurentbfb1b832013-01-07 09:53:42 -08002025 void *cookie)
2026{
2027 AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
2028 ALOGV("asyncCallback() event %d", event);
2029 switch (event) {
2030 case STREAM_CBK_EVENT_WRITE_READY:
2031 me->writeCallback();
2032 break;
2033 case STREAM_CBK_EVENT_DRAIN_READY:
2034 me->drainCallback();
2035 break;
2036 default:
2037 ALOGW("asyncCallback() unknown event %d", event);
2038 break;
2039 }
2040 return 0;
2041}
2042
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002043void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002044{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002045 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Eric Laurent81784c32012-11-19 14:55:58 -08002046 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
2047 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002048 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002049 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002050 }
Andy Hung9a592762014-07-21 21:56:01 -07002051 if ((mType == MIXER || mType == DUPLICATING)
2052 && !isValidPcmSinkChannelMask(mChannelMask)) {
2053 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2054 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002055 }
Andy Hunge5412692014-05-16 11:25:07 -07002056 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Andy Hung463be252014-07-10 16:56:07 -07002057 mHALFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
2058 mFormat = mHALFormat;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002059 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002060 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002061 }
Andy Hung6146c082014-03-18 11:56:15 -07002062 if ((mType == MIXER || mType == DUPLICATING)
2063 && !isValidPcmSinkFormat(mFormat)) {
2064 LOG_FATAL("HAL format %#x not supported for mixed output",
2065 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002066 }
Phil Burk062e67a2015-02-11 13:40:50 -08002067 mFrameSize = mOutput->getFrameSize();
Glenn Kasten70949c42013-08-06 07:40:12 -07002068 mBufferSize = mOutput->stream->common.get_buffer_size(&mOutput->stream->common);
2069 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002070 if (mFrameCount & 15) {
2071 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
2072 mFrameCount);
2073 }
2074
Eric Laurentbfb1b832013-01-07 09:53:42 -08002075 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
2076 (mOutput->stream->set_callback != NULL)) {
2077 if (mOutput->stream->set_callback(mOutput->stream,
2078 AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
2079 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002080 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002081 }
2082 }
2083
Eric Laurentd1f69b02014-12-15 14:33:13 -08002084 mHwSupportsPause = false;
2085 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
2086 if (mOutput->stream->pause != NULL) {
2087 if (mOutput->stream->resume != NULL) {
2088 mHwSupportsPause = true;
2089 } else {
2090 ALOGW("direct output implements pause but not resume");
2091 }
2092 } else if (mOutput->stream->resume != NULL) {
2093 ALOGW("direct output implements resume but not pause");
2094 }
2095 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002096 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2097 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2098 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002099
Andy Hungfbfc3952015-01-15 13:33:51 -08002100 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2101 // For best precision, we use float instead of the associated output
2102 // device format (typically PCM 16 bit).
2103
2104 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2105 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2106 mBufferSize = mFrameSize * mFrameCount;
2107
2108 // TODO: We currently use the associated output device channel mask and sample rate.
2109 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2110 // (if a valid mask) to avoid premature downmix.
2111 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2112 // instead of the output device sample rate to avoid loss of high frequency information.
2113 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2114 }
2115
Andy Hung09a50072014-02-27 14:30:47 -08002116 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002117 double multiplier = 1.0;
2118 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2119 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002120 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2121 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Eric Laurent81784c32012-11-19 14:55:58 -08002122 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2123 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2124 maxNormalFrameCount = maxNormalFrameCount & ~15;
2125 if (maxNormalFrameCount < minNormalFrameCount) {
2126 maxNormalFrameCount = minNormalFrameCount;
2127 }
2128 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2129 if (multiplier <= 1.0) {
2130 multiplier = 1.0;
2131 } else if (multiplier <= 2.0) {
2132 if (2 * mFrameCount <= maxNormalFrameCount) {
2133 multiplier = 2.0;
2134 } else {
2135 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2136 }
2137 } else {
2138 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
Andy Hung09a50072014-02-27 14:30:47 -08002139 // 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 -08002140 // track, but we sometimes have to do this to satisfy the maximum frame count
2141 // constraint)
2142 // FIXME this rounding up should not be done if no HAL SRC
2143 uint32_t truncMult = (uint32_t) multiplier;
2144 if ((truncMult & 1)) {
2145 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
2146 ++truncMult;
2147 }
2148 }
2149 multiplier = (double) truncMult;
2150 }
2151 }
2152 mNormalFrameCount = multiplier * mFrameCount;
2153 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002154 if (mType == MIXER || mType == DUPLICATING) {
2155 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2156 }
Andy Hung09a50072014-02-27 14:30:47 -08002157 ALOGI("HAL output buffer size %u frames, normal sink buffer size %u frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002158 mNormalFrameCount);
2159
Andy Hung010a1a12014-03-13 13:57:33 -07002160 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2161 // Originally this was int16_t[] array, need to remove legacy implications.
2162 free(mSinkBuffer);
2163 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002164 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2165 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2166 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002167 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002168
Andy Hung69aed5f2014-02-25 17:24:40 -08002169 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2170 // drives the output.
2171 free(mMixerBuffer);
2172 mMixerBuffer = NULL;
2173 if (mMixerBufferEnabled) {
2174 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2175 mMixerBufferSize = mNormalFrameCount * mChannelCount
2176 * audio_bytes_per_sample(mMixerBufferFormat);
2177 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2178 }
Andy Hung98ef9782014-03-04 14:46:50 -08002179 free(mEffectBuffer);
2180 mEffectBuffer = NULL;
2181 if (mEffectBufferEnabled) {
2182 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
2183 mEffectBufferSize = mNormalFrameCount * mChannelCount
2184 * audio_bytes_per_sample(mEffectBufferFormat);
2185 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2186 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002187
Eric Laurent81784c32012-11-19 14:55:58 -08002188 // force reconfiguration of effect chains and engines to take new buffer size and audio
2189 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002190 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002191 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2192 // matter.
2193 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2194 Vector< sp<EffectChain> > effectChains = mEffectChains;
2195 for (size_t i = 0; i < effectChains.size(); i ++) {
2196 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2197 }
2198}
2199
2200
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002201status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002202{
2203 if (halFrames == NULL || dspFrames == NULL) {
2204 return BAD_VALUE;
2205 }
2206 Mutex::Autolock _l(mLock);
2207 if (initCheck() != NO_ERROR) {
2208 return INVALID_OPERATION;
2209 }
2210 size_t framesWritten = mBytesWritten / mFrameSize;
2211 *halFrames = framesWritten;
2212
2213 if (isSuspended()) {
2214 // return an estimation of rendered frames when the output is suspended
2215 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
2216 *dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0;
2217 return NO_ERROR;
2218 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002219 status_t status;
2220 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002221 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002222 *dspFrames = (size_t)frames;
2223 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002224 }
2225}
2226
2227uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
2228{
2229 Mutex::Autolock _l(mLock);
2230 uint32_t result = 0;
2231 if (getEffectChain_l(sessionId) != 0) {
2232 result = EFFECT_SESSION;
2233 }
2234
2235 for (size_t i = 0; i < mTracks.size(); ++i) {
2236 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002237 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002238 result |= TRACK_SESSION;
2239 break;
2240 }
2241 }
2242
2243 return result;
2244}
2245
2246uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
2247{
2248 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2249 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2250 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2251 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2252 }
2253 for (size_t i = 0; i < mTracks.size(); i++) {
2254 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002255 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002256 return AudioSystem::getStrategyForStream(track->streamType());
2257 }
2258 }
2259 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2260}
2261
2262
Phil Burk062e67a2015-02-11 13:40:50 -08002263AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002264{
2265 Mutex::Autolock _l(mLock);
2266 return mOutput;
2267}
2268
Phil Burk062e67a2015-02-11 13:40:50 -08002269AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002270{
2271 Mutex::Autolock _l(mLock);
2272 AudioStreamOut *output = mOutput;
2273 mOutput = NULL;
2274 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2275 // must push a NULL and wait for ack
2276 mOutputSink.clear();
2277 mPipeSink.clear();
2278 mNormalSink.clear();
2279 return output;
2280}
2281
2282// this method must always be called either with ThreadBase mLock held or inside the thread loop
2283audio_stream_t* AudioFlinger::PlaybackThread::stream() const
2284{
2285 if (mOutput == NULL) {
2286 return NULL;
2287 }
2288 return &mOutput->stream->common;
2289}
2290
2291uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2292{
2293 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2294}
2295
2296status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2297{
2298 if (!isValidSyncEvent(event)) {
2299 return BAD_VALUE;
2300 }
2301
2302 Mutex::Autolock _l(mLock);
2303
2304 for (size_t i = 0; i < mTracks.size(); ++i) {
2305 sp<Track> track = mTracks[i];
2306 if (event->triggerSession() == track->sessionId()) {
2307 (void) track->setSyncEvent(event);
2308 return NO_ERROR;
2309 }
2310 }
2311
2312 return NAME_NOT_FOUND;
2313}
2314
2315bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2316{
2317 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2318}
2319
2320void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2321 const Vector< sp<Track> >& tracksToRemove)
2322{
2323 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002324 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002325 for (size_t i = 0 ; i < count ; i++) {
2326 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002327 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002328 AudioSystem::stopOutput(mId, track->streamType(),
2329 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002330#ifdef ADD_BATTERY_DATA
2331 // to track the speaker usage
2332 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2333#endif
2334 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002335 AudioSystem::releaseOutput(mId, track->streamType(),
2336 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002337 }
Eric Laurent81784c32012-11-19 14:55:58 -08002338 }
2339 }
2340 }
Eric Laurent81784c32012-11-19 14:55:58 -08002341}
2342
2343void AudioFlinger::PlaybackThread::checkSilentMode_l()
2344{
2345 if (!mMasterMute) {
2346 char value[PROPERTY_VALUE_MAX];
2347 if (property_get("ro.audio.silent", value, "0") > 0) {
2348 char *endptr;
2349 unsigned long ul = strtoul(value, &endptr, 0);
2350 if (*endptr == '\0' && ul != 0) {
2351 ALOGD("Silence is golden");
2352 // The setprop command will not allow a property to be changed after
2353 // the first time it is set, so we don't have to worry about un-muting.
2354 setMasterMute_l(true);
2355 }
2356 }
2357 }
2358}
2359
2360// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002361ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002362{
2363 // FIXME rewrite to reduce number of system calls
2364 mLastWriteTime = systemTime();
2365 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002366 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002367 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002368
2369 // If an NBAIO sink is present, use it to write the normal mixer's submix
2370 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002371
Andy Hung010a1a12014-03-13 13:57:33 -07002372 const size_t count = mBytesRemaining / mFrameSize;
2373
Simon Wilson2d590962012-11-29 15:18:50 -08002374 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002375 // update the setpoint when AudioFlinger::mScreenState changes
2376 uint32_t screenState = AudioFlinger::mScreenState;
2377 if (screenState != mScreenState) {
2378 mScreenState = screenState;
2379 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2380 if (pipe != NULL) {
2381 pipe->setAvgFrames((mScreenState & 1) ?
2382 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2383 }
2384 }
Andy Hung010a1a12014-03-13 13:57:33 -07002385 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002386 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002387 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002388 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002389 } else {
2390 bytesWritten = framesWritten;
2391 }
Glenn Kastenefaa7ab2014-08-20 08:48:54 -07002392 mLatchDValid = false;
Glenn Kasten767094d2013-08-23 13:51:43 -07002393 status_t status = mNormalSink->getTimestamp(mLatchD.mTimestamp);
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002394 if (status == NO_ERROR) {
2395 size_t totalFramesWritten = mNormalSink->framesWritten();
2396 if (totalFramesWritten >= mLatchD.mTimestamp.mPosition) {
2397 mLatchD.mUnpresentedFrames = totalFramesWritten - mLatchD.mTimestamp.mPosition;
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002398 // mLatchD.mFramesReleased is set immediately before D is clocked into Q
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002399 mLatchDValid = true;
2400 }
2401 }
Eric Laurent81784c32012-11-19 14:55:58 -08002402 // otherwise use the HAL / AudioStreamOut directly
2403 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002404 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002405
Eric Laurentbfb1b832013-01-07 09:53:42 -08002406 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002407 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2408 mWriteAckSequence += 2;
2409 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002410 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002411 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002412 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002413 // FIXME We should have an implementation of timestamps for direct output threads.
2414 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002415 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002416 if (mUseAsyncWrite &&
2417 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2418 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002419 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002420 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002421 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002422 }
Eric Laurent81784c32012-11-19 14:55:58 -08002423 }
2424
Eric Laurent81784c32012-11-19 14:55:58 -08002425 mNumWrites++;
2426 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002427 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002428 return bytesWritten;
2429}
2430
2431void AudioFlinger::PlaybackThread::threadLoop_drain()
2432{
2433 if (mOutput->stream->drain) {
2434 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2435 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002436 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2437 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002438 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002439 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002440 }
2441 mOutput->stream->drain(mOutput->stream,
2442 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
2443 : AUDIO_DRAIN_ALL);
2444 }
2445}
2446
2447void AudioFlinger::PlaybackThread::threadLoop_exit()
2448{
Eric Laurent275e8e92014-11-30 15:14:47 -08002449 {
2450 Mutex::Autolock _l(mLock);
2451 for (size_t i = 0; i < mTracks.size(); i++) {
2452 sp<Track> track = mTracks[i];
2453 track->invalidate();
2454 }
2455 }
Eric Laurent81784c32012-11-19 14:55:58 -08002456}
2457
2458/*
2459The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002460 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002461 - mActiveSleepTimeUs from activeSleepTimeUs()
2462 - mIdleSleepTimeUs from idleSleepTimeUs()
2463 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only)
Eric Laurent81784c32012-11-19 14:55:58 -08002464 - maxPeriod from frame count and sample rate (MIXER only)
2465
2466The parameters that affect these derived values are:
2467 - frame count
2468 - frame size
2469 - sample rate
2470 - device type: A2DP or not
2471 - device latency
2472 - format: PCM or not
2473 - active sleep time
2474 - idle sleep time
2475*/
2476
2477void AudioFlinger::PlaybackThread::cacheParameters_l()
2478{
Andy Hung25c2dac2014-02-27 14:56:00 -08002479 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002480 mActiveSleepTimeUs = activeSleepTimeUs();
2481 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent81784c32012-11-19 14:55:58 -08002482}
2483
2484void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2485{
Glenn Kasten7c027242012-12-26 14:43:16 -08002486 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurent81784c32012-11-19 14:55:58 -08002487 this, streamType, mTracks.size());
2488 Mutex::Autolock _l(mLock);
2489
2490 size_t size = mTracks.size();
2491 for (size_t i = 0; i < size; i++) {
2492 sp<Track> t = mTracks[i];
2493 if (t->streamType() == streamType) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002494 t->invalidate();
Eric Laurent81784c32012-11-19 14:55:58 -08002495 }
2496 }
2497}
2498
2499status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2500{
2501 int session = chain->sessionId();
Andy Hung010a1a12014-03-13 13:57:33 -07002502 int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled
2503 ? mEffectBuffer : mSinkBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002504 bool ownsBuffer = false;
2505
2506 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
2507 if (session > 0) {
2508 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002509 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002510 if (mType != DIRECT) {
2511 size_t numSamples = mNormalFrameCount * mChannelCount;
2512 buffer = new int16_t[numSamples];
2513 memset(buffer, 0, numSamples * sizeof(int16_t));
2514 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2515 ownsBuffer = true;
2516 }
2517
2518 // Attach all tracks with same session ID to this chain.
2519 for (size_t i = 0; i < mTracks.size(); ++i) {
2520 sp<Track> track = mTracks[i];
2521 if (session == track->sessionId()) {
2522 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2523 buffer);
2524 track->setMainBuffer(buffer);
2525 chain->incTrackCnt();
2526 }
2527 }
2528
2529 // indicate all active tracks in the chain
2530 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2531 sp<Track> track = mActiveTracks[i].promote();
2532 if (track == 0) {
2533 continue;
2534 }
2535 if (session == track->sessionId()) {
2536 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2537 chain->incActiveTrackCnt();
2538 }
2539 }
2540 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002541 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08002542 chain->setInBuffer(buffer, ownsBuffer);
Andy Hung010a1a12014-03-13 13:57:33 -07002543 chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled
2544 ? mEffectBuffer : mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002545 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
2546 // chains list in order to be processed last as it contains output stage effects
2547 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2548 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
2549 // after track specific effects and before output stage
2550 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
2551 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
2552 // Effect chain for other sessions are inserted at beginning of effect
2553 // chains list to be processed before output mix effects. Relative order between other
2554 // sessions is not important
2555 size_t size = mEffectChains.size();
2556 size_t i = 0;
2557 for (i = 0; i < size; i++) {
2558 if (mEffectChains[i]->sessionId() < session) {
2559 break;
2560 }
2561 }
2562 mEffectChains.insertAt(chain, i);
2563 checkSuspendOnAddEffectChain_l(chain);
2564
2565 return NO_ERROR;
2566}
2567
2568size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2569{
2570 int session = chain->sessionId();
2571
2572 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2573
2574 for (size_t i = 0; i < mEffectChains.size(); i++) {
2575 if (chain == mEffectChains[i]) {
2576 mEffectChains.removeAt(i);
2577 // detach all active tracks from the chain
2578 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2579 sp<Track> track = mActiveTracks[i].promote();
2580 if (track == 0) {
2581 continue;
2582 }
2583 if (session == track->sessionId()) {
2584 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2585 chain.get(), session);
2586 chain->decActiveTrackCnt();
2587 }
2588 }
2589
2590 // detach all tracks with same session ID from this chain
2591 for (size_t i = 0; i < mTracks.size(); ++i) {
2592 sp<Track> track = mTracks[i];
2593 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002594 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002595 chain->decTrackCnt();
2596 }
2597 }
2598 break;
2599 }
2600 }
2601 return mEffectChains.size();
2602}
2603
2604status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2605 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2606{
2607 Mutex::Autolock _l(mLock);
2608 return attachAuxEffect_l(track, EffectId);
2609}
2610
2611status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2612 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2613{
2614 status_t status = NO_ERROR;
2615
2616 if (EffectId == 0) {
2617 track->setAuxBuffer(0, NULL);
2618 } else {
2619 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2620 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2621 if (effect != 0) {
2622 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2623 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2624 } else {
2625 status = INVALID_OPERATION;
2626 }
2627 } else {
2628 status = BAD_VALUE;
2629 }
2630 }
2631 return status;
2632}
2633
2634void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2635{
2636 for (size_t i = 0; i < mTracks.size(); ++i) {
2637 sp<Track> track = mTracks[i];
2638 if (track->auxEffectId() == effectId) {
2639 attachAuxEffect_l(track, 0);
2640 }
2641 }
2642}
2643
2644bool AudioFlinger::PlaybackThread::threadLoop()
2645{
2646 Vector< sp<Track> > tracksToRemove;
2647
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002648 mStandbyTimeNs = systemTime();
Eric Laurent81784c32012-11-19 14:55:58 -08002649
2650 // MIXER
2651 nsecs_t lastWarning = 0;
2652
2653 // DUPLICATING
2654 // FIXME could this be made local to while loop?
2655 writeFrames = 0;
2656
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002657 int lastGeneration = 0;
2658
Eric Laurent81784c32012-11-19 14:55:58 -08002659 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002660 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08002661
2662 if (mType == MIXER) {
2663 sleepTimeShift = 0;
2664 }
2665
2666 CpuStats cpuStats;
2667 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2668
2669 acquireWakeLock();
2670
Glenn Kasten9e58b552013-01-18 15:09:48 -08002671 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2672 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2673 // and then that string will be logged at the next convenient opportunity.
2674 const char *logString = NULL;
2675
Eric Laurent664539d2013-09-23 18:24:31 -07002676 checkSilentMode_l();
2677
Eric Laurent81784c32012-11-19 14:55:58 -08002678 while (!exitPending())
2679 {
2680 cpuStats.sample(myName);
2681
2682 Vector< sp<EffectChain> > effectChains;
2683
Eric Laurent81784c32012-11-19 14:55:58 -08002684 { // scope for mLock
2685
2686 Mutex::Autolock _l(mLock);
2687
Eric Laurent021cf962014-05-13 10:18:14 -07002688 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07002689
Glenn Kasten9e58b552013-01-18 15:09:48 -08002690 if (logString != NULL) {
2691 mNBLogWriter->logTimestamp();
2692 mNBLogWriter->log(logString);
2693 logString = NULL;
2694 }
2695
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002696 // Gather the framesReleased counters for all active tracks,
2697 // and latch them atomically with the timestamp.
2698 // FIXME We're using raw pointers as indices. A unique track ID would be a better index.
2699 mLatchD.mFramesReleased.clear();
2700 size_t size = mActiveTracks.size();
2701 for (size_t i = 0; i < size; i++) {
2702 sp<Track> t = mActiveTracks[i].promote();
2703 if (t != 0) {
2704 mLatchD.mFramesReleased.add(t.get(),
2705 t->mAudioTrackServerProxy->framesReleased());
2706 }
2707 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002708 if (mLatchDValid) {
2709 mLatchQ = mLatchD;
2710 mLatchDValid = false;
2711 mLatchQValid = true;
2712 }
2713
Eric Laurent81784c32012-11-19 14:55:58 -08002714 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002715 if (mSignalPending) {
2716 // A signal was raised while we were unlocked
2717 mSignalPending = false;
2718 } else if (waitingAsyncCallback_l()) {
2719 if (exitPending()) {
2720 break;
2721 }
Marco Nelissen078538c2015-05-12 09:17:57 -07002722 bool released = false;
2723 // The following works around a bug in the offload driver. Ideally we would release
2724 // the wake lock every time, but that causes the last offload buffer(s) to be
2725 // dropped while the device is on battery, so we need to hold a wake lock during
2726 // the drain phase.
2727 if (mBytesRemaining && !(mDrainSequence & 1)) {
2728 releaseWakeLock_l();
2729 released = true;
2730 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002731 mWakeLockUids.clear();
2732 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002733 ALOGV("wait async completion");
2734 mWaitWorkCV.wait(mLock);
2735 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07002736 if (released) {
2737 acquireWakeLock_l();
2738 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002739 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
2740 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002741
2742 continue;
2743 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002744 if ((!mActiveTracks.size() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08002745 isSuspended()) {
2746 // put audio hardware into standby after short delay
2747 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002748
2749 threadLoop_standby();
2750
2751 mStandby = true;
2752 }
2753
2754 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2755 // we're about to wait, flush the binder command buffer
2756 IPCThreadState::self()->flushCommands();
2757
2758 clearOutputTracks();
2759
2760 if (exitPending()) {
2761 break;
2762 }
2763
2764 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002765 mWakeLockUids.clear();
2766 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002767 // wait until we have something to do...
2768 ALOGV("%s going to sleep", myName.string());
2769 mWaitWorkCV.wait(mLock);
2770 ALOGV("%s waking up", myName.string());
2771 acquireWakeLock_l();
2772
2773 mMixerStatus = MIXER_IDLE;
2774 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2775 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002776 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002777 checkSilentMode_l();
2778
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002779 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
2780 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08002781 if (mType == MIXER) {
2782 sleepTimeShift = 0;
2783 }
2784
2785 continue;
2786 }
2787 }
Eric Laurent81784c32012-11-19 14:55:58 -08002788 // mMixerStatusIgnoringFastTracks is also updated internally
2789 mMixerStatus = prepareTracks_l(&tracksToRemove);
2790
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002791 // compare with previously applied list
2792 if (lastGeneration != mActiveTracksGeneration) {
2793 // update wakelock
2794 updateWakeLockUids_l(mWakeLockUids);
2795 lastGeneration = mActiveTracksGeneration;
2796 }
2797
Eric Laurent81784c32012-11-19 14:55:58 -08002798 // prevent any changes in effect chain list and in each effect chain
2799 // during mixing and effect process as the audio buffers could be deleted
2800 // or modified if an effect is created or deleted
2801 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002802 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08002803
Eric Laurentbfb1b832013-01-07 09:53:42 -08002804 if (mBytesRemaining == 0) {
2805 mCurrentWriteLength = 0;
2806 if (mMixerStatus == MIXER_TRACKS_READY) {
2807 // threadLoop_mix() sets mCurrentWriteLength
2808 threadLoop_mix();
2809 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
2810 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002811 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08002812 // must be written to HAL
2813 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002814 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08002815 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002816 }
2817 }
Andy Hung98ef9782014-03-04 14:46:50 -08002818 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002819 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08002820 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
2821 // or mSinkBuffer (if there are no effects).
2822 //
2823 // This is done pre-effects computation; if effects change to
2824 // support higher precision, this needs to move.
2825 //
2826 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002827 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08002828 if (mMixerBufferValid) {
2829 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
2830 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
2831
2832 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
2833 mNormalFrameCount * mChannelCount);
2834 }
2835
Eric Laurentbfb1b832013-01-07 09:53:42 -08002836 mBytesRemaining = mCurrentWriteLength;
2837 if (isSuspended()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002838 mSleepTimeUs = suspendSleepTimeUs();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002839 // simulate write to HAL when suspended
Andy Hung25c2dac2014-02-27 14:56:00 -08002840 mBytesWritten += mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002841 mBytesRemaining = 0;
2842 }
Eric Laurent81784c32012-11-19 14:55:58 -08002843
Eric Laurentbfb1b832013-01-07 09:53:42 -08002844 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002845 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002846 for (size_t i = 0; i < effectChains.size(); i ++) {
2847 effectChains[i]->process_l();
2848 }
Eric Laurent81784c32012-11-19 14:55:58 -08002849 }
2850 }
Eric Laurent59fe0102013-09-27 18:48:26 -07002851 // Process effect chains for offloaded thread even if no audio
2852 // was read from audio track: process only updates effect state
2853 // and thus does have to be synchronized with audio writes but may have
2854 // to be called while waiting for async write callback
2855 if (mType == OFFLOAD) {
2856 for (size_t i = 0; i < effectChains.size(); i ++) {
2857 effectChains[i]->process_l();
2858 }
2859 }
Eric Laurent81784c32012-11-19 14:55:58 -08002860
Andy Hung98ef9782014-03-04 14:46:50 -08002861 // Only if the Effects buffer is enabled and there is data in the
2862 // Effects buffer (buffer valid), we need to
2863 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002864 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08002865 if (mEffectBufferValid) {
2866 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
2867 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
2868 mNormalFrameCount * mChannelCount);
2869 }
2870
Eric Laurent81784c32012-11-19 14:55:58 -08002871 // enable changes in effect chain
2872 unlockEffectChains(effectChains);
2873
Eric Laurentbfb1b832013-01-07 09:53:42 -08002874 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002875 // mSleepTimeUs == 0 means we must write to audio hardware
2876 if (mSleepTimeUs == 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002877 if (mBytesRemaining) {
2878 ssize_t ret = threadLoop_write();
2879 if (ret < 0) {
2880 mBytesRemaining = 0;
2881 } else {
2882 mBytesWritten += ret;
2883 mBytesRemaining -= ret;
2884 }
2885 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
2886 (mMixerStatus == MIXER_DRAIN_ALL)) {
2887 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08002888 }
Glenn Kasten4944acb2013-08-19 08:39:20 -07002889 if (mType == MIXER) {
2890 // write blocked detection
2891 nsecs_t now = systemTime();
2892 nsecs_t delta = now - mLastWriteTime;
2893 if (!mStandby && delta > maxPeriod) {
2894 mNumDelayedWrites++;
2895 if ((now - lastWarning) > kWarningThrottleNs) {
2896 ATRACE_NAME("underrun");
2897 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2898 ns2ms(delta), mNumDelayedWrites, this);
2899 lastWarning = now;
2900 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002901 }
2902 }
Eric Laurent81784c32012-11-19 14:55:58 -08002903
Eric Laurentbfb1b832013-01-07 09:53:42 -08002904 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07002905 ATRACE_BEGIN("sleep");
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002906 usleep(mSleepTimeUs);
Glenn Kastene7754022014-10-31 12:11:26 -07002907 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002908 }
Eric Laurent81784c32012-11-19 14:55:58 -08002909 }
2910
2911 // Finally let go of removed track(s), without the lock held
2912 // since we can't guarantee the destructors won't acquire that
2913 // same lock. This will also mutate and push a new fast mixer state.
2914 threadLoop_removeTracks(tracksToRemove);
2915 tracksToRemove.clear();
2916
2917 // FIXME I don't understand the need for this here;
2918 // it was in the original code but maybe the
2919 // assignment in saveOutputTracks() makes this unnecessary?
2920 clearOutputTracks();
2921
2922 // Effect chains will be actually deleted here if they were removed from
2923 // mEffectChains list during mixing or effects processing
2924 effectChains.clear();
2925
2926 // FIXME Note that the above .clear() is no longer necessary since effectChains
2927 // is now local to this block, but will keep it for now (at least until merge done).
2928 }
2929
Eric Laurentbfb1b832013-01-07 09:53:42 -08002930 threadLoop_exit();
2931
Eric Laurentcf817a22014-08-04 20:36:31 -07002932 if (!mStandby) {
2933 threadLoop_standby();
2934 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08002935 }
2936
2937 releaseWakeLock();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002938 mWakeLockUids.clear();
2939 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002940
2941 ALOGV("Thread %p type %d exiting", this, mType);
2942 return false;
2943}
2944
Eric Laurentbfb1b832013-01-07 09:53:42 -08002945// removeTracks_l() must be called with ThreadBase::mLock held
2946void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
2947{
2948 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002949 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002950 for (size_t i=0 ; i<count ; i++) {
2951 const sp<Track>& track = tracksToRemove.itemAt(i);
2952 mActiveTracks.remove(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002953 mWakeLockUids.remove(track->uid());
2954 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002955 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
2956 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2957 if (chain != 0) {
2958 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
2959 track->sessionId());
2960 chain->decActiveTrackCnt();
2961 }
2962 if (track->isTerminated()) {
2963 removeTrack_l(track);
2964 }
2965 }
2966 }
2967
2968}
Eric Laurent81784c32012-11-19 14:55:58 -08002969
Eric Laurentaccc1472013-09-20 09:36:34 -07002970status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
2971{
2972 if (mNormalSink != 0) {
2973 return mNormalSink->getTimestamp(timestamp);
2974 }
Andy Hung9a1c8892014-12-03 11:37:42 -08002975 if ((mType == OFFLOAD || mType == DIRECT)
2976 && mOutput != NULL && mOutput->stream->get_presentation_position) {
Eric Laurentaccc1472013-09-20 09:36:34 -07002977 uint64_t position64;
Phil Burk062e67a2015-02-11 13:40:50 -08002978 int ret = mOutput->getPresentationPosition(&position64, &timestamp.mTime);
Eric Laurentaccc1472013-09-20 09:36:34 -07002979 if (ret == 0) {
2980 timestamp.mPosition = (uint32_t)position64;
2981 return NO_ERROR;
2982 }
2983 }
2984 return INVALID_OPERATION;
2985}
Eric Laurent1c333e22014-05-20 10:48:17 -07002986
Eric Laurent054d9d32015-04-24 08:48:48 -07002987status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
2988 audio_patch_handle_t *handle)
2989{
2990 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
2991 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
2992 if (mFastMixer != 0) {
2993 FastMixerStateQueue *sq = mFastMixer->sq();
2994 FastMixerState *state = sq->begin();
2995 if (!(state->mCommand & FastMixerState::IDLE)) {
2996 previousCommand = state->mCommand;
2997 state->mCommand = FastMixerState::HOT_IDLE;
2998 sq->end();
2999 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3000 } else {
3001 sq->end(false /*didModify*/);
3002 }
3003 }
3004 status_t status = PlaybackThread::createAudioPatch_l(patch, handle);
3005
3006 if (!(previousCommand & FastMixerState::IDLE)) {
3007 ALOG_ASSERT(mFastMixer != 0);
3008 FastMixerStateQueue *sq = mFastMixer->sq();
3009 FastMixerState *state = sq->begin();
3010 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3011 state->mCommand = previousCommand;
3012 sq->end();
3013 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3014 }
3015
3016 return status;
3017}
3018
Eric Laurent1c333e22014-05-20 10:48:17 -07003019status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3020 audio_patch_handle_t *handle)
3021{
3022 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003023
3024 // store new device and send to effects
3025 audio_devices_t type = AUDIO_DEVICE_NONE;
3026 for (unsigned int i = 0; i < patch->num_sinks; i++) {
3027 type |= patch->sinks[i].ext.device.type;
3028 }
3029
3030#ifdef ADD_BATTERY_DATA
3031 // when changing the audio output device, call addBatteryData to notify
3032 // the change
3033 if (mOutDevice != type) {
3034 uint32_t params = 0;
3035 // check whether speaker is on
3036 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3037 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003038 }
3039
Eric Laurent054d9d32015-04-24 08:48:48 -07003040 audio_devices_t deviceWithoutSpeaker
3041 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3042 // check if any other device (except speaker) is on
3043 if (type & deviceWithoutSpeaker) {
3044 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3045 }
3046
3047 if (params != 0) {
3048 addBatteryData(params);
3049 }
3050 }
3051#endif
3052
3053 for (size_t i = 0; i < mEffectChains.size(); i++) {
3054 mEffectChains[i]->setDevice_l(type);
3055 }
3056 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003057 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003058
3059 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003060 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
3061 status = hwDevice->create_audio_patch(hwDevice,
3062 patch->num_sources,
3063 patch->sources,
3064 patch->num_sinks,
3065 patch->sinks,
3066 handle);
3067 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003068 char *address;
3069 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3070 //FIXME: we only support address on first sink with HAL version < 3.0
3071 address = audio_device_address_to_parameter(
3072 patch->sinks[0].ext.device.type,
3073 patch->sinks[0].ext.device.address);
3074 } else {
3075 address = (char *)calloc(1, 1);
3076 }
3077 AudioParameter param = AudioParameter(String8(address));
3078 free(address);
3079 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), (int)type);
3080 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3081 param.toString().string());
3082 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003083 }
Eric Laurent296fb132015-05-01 11:38:42 -07003084 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent1c333e22014-05-20 10:48:17 -07003085 return status;
3086}
3087
Eric Laurent054d9d32015-04-24 08:48:48 -07003088status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3089{
3090 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3091 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3092 if (mFastMixer != 0) {
3093 FastMixerStateQueue *sq = mFastMixer->sq();
3094 FastMixerState *state = sq->begin();
3095 if (!(state->mCommand & FastMixerState::IDLE)) {
3096 previousCommand = state->mCommand;
3097 state->mCommand = FastMixerState::HOT_IDLE;
3098 sq->end();
3099 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3100 } else {
3101 sq->end(false /*didModify*/);
3102 }
3103 }
3104
3105 status_t status = PlaybackThread::releaseAudioPatch_l(handle);
3106
3107 if (!(previousCommand & FastMixerState::IDLE)) {
3108 ALOG_ASSERT(mFastMixer != 0);
3109 FastMixerStateQueue *sq = mFastMixer->sq();
3110 FastMixerState *state = sq->begin();
3111 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3112 state->mCommand = previousCommand;
3113 sq->end();
3114 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3115 }
3116
3117 return status;
3118}
3119
Eric Laurent1c333e22014-05-20 10:48:17 -07003120status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3121{
3122 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003123
3124 mOutDevice = AUDIO_DEVICE_NONE;
3125
Eric Laurent1c333e22014-05-20 10:48:17 -07003126 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
3127 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
3128 status = hwDevice->release_audio_patch(hwDevice, handle);
3129 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003130 AudioParameter param;
3131 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
3132 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3133 param.toString().string());
Eric Laurent1c333e22014-05-20 10:48:17 -07003134 }
3135 return status;
3136}
3137
Eric Laurent83b88082014-06-20 18:31:16 -07003138void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3139{
3140 Mutex::Autolock _l(mLock);
3141 mTracks.add(track);
3142}
3143
3144void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3145{
3146 Mutex::Autolock _l(mLock);
3147 destroyTrack_l(track);
3148}
3149
3150void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
3151{
3152 ThreadBase::getAudioPortConfig(config);
3153 config->role = AUDIO_PORT_ROLE_SOURCE;
3154 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3155 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
3156}
3157
Eric Laurent81784c32012-11-19 14:55:58 -08003158// ----------------------------------------------------------------------------
3159
3160AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurent72e3f392015-05-20 14:43:50 -07003161 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
3162 : PlaybackThread(audioFlinger, output, id, device, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08003163 // mAudioMixer below
3164 // mFastMixer below
3165 mFastMixerFutex(0)
3166 // mOutputSink below
3167 // mPipeSink below
3168 // mNormalSink below
3169{
3170 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07003171 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, "
Eric Laurent81784c32012-11-19 14:55:58 -08003172 "mFrameCount=%d, mNormalFrameCount=%d",
3173 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3174 mNormalFrameCount);
3175 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3176
Andy Hungfbfc3952015-01-15 13:33:51 -08003177 if (type == DUPLICATING) {
3178 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3179 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3180 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3181 return;
3182 }
Eric Laurent81784c32012-11-19 14:55:58 -08003183 // create an NBAIO sink for the HAL output stream, and negotiate
3184 mOutputSink = new AudioStreamOutSink(output->stream);
3185 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003186 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Eric Laurent81784c32012-11-19 14:55:58 -08003187 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
3188 ALOG_ASSERT(index == 0);
3189
3190 // initialize fast mixer depending on configuration
3191 bool initFastMixer;
3192 switch (kUseFastMixer) {
3193 case FastMixer_Never:
3194 initFastMixer = false;
3195 break;
3196 case FastMixer_Always:
3197 initFastMixer = true;
3198 break;
3199 case FastMixer_Static:
3200 case FastMixer_Dynamic:
3201 initFastMixer = mFrameCount < mNormalFrameCount;
3202 break;
3203 }
3204 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003205 audio_format_t fastMixerFormat;
3206 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3207 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3208 } else {
3209 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3210 }
3211 if (mFormat != fastMixerFormat) {
3212 // change our Sink format to accept our intermediate precision
3213 mFormat = fastMixerFormat;
3214 free(mSinkBuffer);
3215 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3216 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3217 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3218 }
Eric Laurent81784c32012-11-19 14:55:58 -08003219
3220 // create a MonoPipe to connect our submix to FastMixer
3221 NBAIO_Format format = mOutputSink->format();
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003222 NBAIO_Format origformat = format;
Andy Hung1258c1a2014-05-23 21:22:17 -07003223 // adjust format to match that of the Fast Mixer
Glenn Kasten97b7b752014-09-28 13:04:24 -07003224 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003225 format.mFormat = fastMixerFormat;
3226 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3227
Eric Laurent81784c32012-11-19 14:55:58 -08003228 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3229 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3230 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3231 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3232 const NBAIO_Format offers[1] = {format};
3233 size_t numCounterOffers = 0;
3234 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
3235 ALOG_ASSERT(index == 0);
3236 monoPipe->setAvgFrames((mScreenState & 1) ?
3237 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3238 mPipeSink = monoPipe;
3239
Glenn Kasten46909e72013-02-26 09:20:22 -08003240#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08003241 if (mTeeSinkOutputEnabled) {
3242 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003243 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
3244 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08003245 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003246 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003247 ALOG_ASSERT(index == 0);
3248 mTeeSink = teeSink;
3249 PipeReader *teeSource = new PipeReader(*teeSink);
3250 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003251 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003252 ALOG_ASSERT(index == 0);
3253 mTeeSource = teeSource;
3254 }
Glenn Kasten46909e72013-02-26 09:20:22 -08003255#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003256
3257 // create fast mixer and configure it initially with just one fast track for our submix
3258 mFastMixer = new FastMixer();
3259 FastMixerStateQueue *sq = mFastMixer->sq();
3260#ifdef STATE_QUEUE_DUMP
3261 sq->setObserverDump(&mStateQueueObserverDump);
3262 sq->setMutatorDump(&mStateQueueMutatorDump);
3263#endif
3264 FastMixerState *state = sq->begin();
3265 FastTrack *fastTrack = &state->mFastTracks[0];
3266 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3267 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3268 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003269 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3270 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003271 fastTrack->mGeneration++;
3272 state->mFastTracksGen++;
3273 state->mTrackMask = 1;
3274 // fast mixer will use the HAL output sink
3275 state->mOutputSink = mOutputSink.get();
3276 state->mOutputSinkGen++;
3277 state->mFrameCount = mFrameCount;
3278 state->mCommand = FastMixerState::COLD_IDLE;
3279 // already done in constructor initialization list
3280 //mFastMixerFutex = 0;
3281 state->mColdFutexAddr = &mFastMixerFutex;
3282 state->mColdGen++;
3283 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08003284#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003285 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08003286#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08003287 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3288 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003289 sq->end();
3290 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3291
3292 // start the fast mixer
3293 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3294 pid_t tid = mFastMixer->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003295 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003296
3297#ifdef AUDIO_WATCHDOG
3298 // create and start the watchdog
3299 mAudioWatchdog = new AudioWatchdog();
3300 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3301 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3302 tid = mAudioWatchdog->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003303 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003304#endif
3305
Eric Laurent81784c32012-11-19 14:55:58 -08003306 }
3307
3308 switch (kUseFastMixer) {
3309 case FastMixer_Never:
3310 case FastMixer_Dynamic:
3311 mNormalSink = mOutputSink;
3312 break;
3313 case FastMixer_Always:
3314 mNormalSink = mPipeSink;
3315 break;
3316 case FastMixer_Static:
3317 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3318 break;
3319 }
3320}
3321
3322AudioFlinger::MixerThread::~MixerThread()
3323{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003324 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003325 FastMixerStateQueue *sq = mFastMixer->sq();
3326 FastMixerState *state = sq->begin();
3327 if (state->mCommand == FastMixerState::COLD_IDLE) {
3328 int32_t old = android_atomic_inc(&mFastMixerFutex);
3329 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003330 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003331 }
3332 }
3333 state->mCommand = FastMixerState::EXIT;
3334 sq->end();
3335 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3336 mFastMixer->join();
3337 // Though the fast mixer thread has exited, it's state queue is still valid.
3338 // We'll use that extract the final state which contains one remaining fast track
3339 // corresponding to our sub-mix.
3340 state = sq->begin();
3341 ALOG_ASSERT(state->mTrackMask == 1);
3342 FastTrack *fastTrack = &state->mFastTracks[0];
3343 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3344 delete fastTrack->mBufferProvider;
3345 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003346 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003347#ifdef AUDIO_WATCHDOG
3348 if (mAudioWatchdog != 0) {
3349 mAudioWatchdog->requestExit();
3350 mAudioWatchdog->requestExitAndWait();
3351 mAudioWatchdog.clear();
3352 }
3353#endif
3354 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003355 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003356 delete mAudioMixer;
3357}
3358
3359
3360uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3361{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003362 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003363 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3364 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3365 }
3366 return latency;
3367}
3368
3369
3370void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3371{
3372 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3373}
3374
Eric Laurentbfb1b832013-01-07 09:53:42 -08003375ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003376{
3377 // FIXME we should only do one push per cycle; confirm this is true
3378 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003379 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003380 FastMixerStateQueue *sq = mFastMixer->sq();
3381 FastMixerState *state = sq->begin();
3382 if (state->mCommand != FastMixerState::MIX_WRITE &&
3383 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3384 if (state->mCommand == FastMixerState::COLD_IDLE) {
3385 int32_t old = android_atomic_inc(&mFastMixerFutex);
3386 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003387 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003388 }
3389#ifdef AUDIO_WATCHDOG
3390 if (mAudioWatchdog != 0) {
3391 mAudioWatchdog->resume();
3392 }
3393#endif
3394 }
3395 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08003396#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003397 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08003398 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08003399#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003400 sq->end();
3401 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3402 if (kUseFastMixer == FastMixer_Dynamic) {
3403 mNormalSink = mPipeSink;
3404 }
3405 } else {
3406 sq->end(false /*didModify*/);
3407 }
3408 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003409 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003410}
3411
3412void AudioFlinger::MixerThread::threadLoop_standby()
3413{
3414 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003415 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003416 FastMixerStateQueue *sq = mFastMixer->sq();
3417 FastMixerState *state = sq->begin();
3418 if (!(state->mCommand & FastMixerState::IDLE)) {
3419 state->mCommand = FastMixerState::COLD_IDLE;
3420 state->mColdFutexAddr = &mFastMixerFutex;
3421 state->mColdGen++;
3422 mFastMixerFutex = 0;
3423 sq->end();
3424 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3425 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3426 if (kUseFastMixer == FastMixer_Dynamic) {
3427 mNormalSink = mOutputSink;
3428 }
3429#ifdef AUDIO_WATCHDOG
3430 if (mAudioWatchdog != 0) {
3431 mAudioWatchdog->pause();
3432 }
3433#endif
3434 } else {
3435 sq->end(false /*didModify*/);
3436 }
3437 }
3438 PlaybackThread::threadLoop_standby();
3439}
3440
Eric Laurentbfb1b832013-01-07 09:53:42 -08003441bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3442{
3443 return false;
3444}
3445
3446bool AudioFlinger::PlaybackThread::shouldStandby_l()
3447{
3448 return !mStandby;
3449}
3450
3451bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3452{
3453 Mutex::Autolock _l(mLock);
3454 return waitingAsyncCallback_l();
3455}
3456
Eric Laurent81784c32012-11-19 14:55:58 -08003457// shared by MIXER and DIRECT, overridden by DUPLICATING
3458void AudioFlinger::PlaybackThread::threadLoop_standby()
3459{
3460 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08003461 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003462 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003463 // discard any pending drain or write ack by incrementing sequence
3464 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3465 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003466 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003467 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3468 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003469 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003470 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003471}
3472
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003473void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3474{
3475 ALOGV("signal playback thread");
3476 broadcast_l();
3477}
3478
Eric Laurent81784c32012-11-19 14:55:58 -08003479void AudioFlinger::MixerThread::threadLoop_mix()
3480{
3481 // obtain the presentation timestamp of the next output buffer
3482 int64_t pts;
3483 status_t status = INVALID_OPERATION;
3484
3485 if (mNormalSink != 0) {
3486 status = mNormalSink->getNextWriteTimestamp(&pts);
3487 } else {
3488 status = mOutputSink->getNextWriteTimestamp(&pts);
3489 }
3490
3491 if (status != NO_ERROR) {
3492 pts = AudioBufferProvider::kInvalidPTS;
3493 }
3494
3495 // mix buffers...
3496 mAudioMixer->process(pts);
Andy Hung25c2dac2014-02-27 14:56:00 -08003497 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003498 // increase sleep time progressively when application underrun condition clears.
3499 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3500 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3501 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003502 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003503 sleepTimeShift--;
3504 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003505 mSleepTimeUs = 0;
3506 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08003507 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003508
Eric Laurent81784c32012-11-19 14:55:58 -08003509}
3510
3511void AudioFlinger::MixerThread::threadLoop_sleepTime()
3512{
3513 // If no tracks are ready, sleep once for the duration of an output
3514 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003515 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003516 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003517 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
3518 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
3519 mSleepTimeUs = kMinThreadSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003520 }
3521 // reduce sleep time in case of consecutive application underruns to avoid
3522 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3523 // duration we would end up writing less data than needed by the audio HAL if
3524 // the condition persists.
3525 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3526 sleepTimeShift++;
3527 }
3528 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003529 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003530 }
3531 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003532 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3533 // before effects processing or output.
3534 if (mMixerBufferValid) {
3535 memset(mMixerBuffer, 0, mMixerBufferSize);
3536 } else {
3537 memset(mSinkBuffer, 0, mSinkBufferSize);
3538 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003539 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003540 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3541 "anticipated start");
3542 }
3543 // TODO add standby time extension fct of effect tail
3544}
3545
3546// prepareTracks_l() must be called with ThreadBase::mLock held
3547AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3548 Vector< sp<Track> > *tracksToRemove)
3549{
3550
3551 mixer_state mixerStatus = MIXER_IDLE;
3552 // find out which tracks need to be processed
3553 size_t count = mActiveTracks.size();
3554 size_t mixedTracks = 0;
3555 size_t tracksWithEffect = 0;
3556 // counts only _active_ fast tracks
3557 size_t fastTracks = 0;
3558 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
3559
3560 float masterVolume = mMasterVolume;
3561 bool masterMute = mMasterMute;
3562
3563 if (masterMute) {
3564 masterVolume = 0;
3565 }
3566 // Delegate master volume control to effect in output mix effect chain if needed
3567 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3568 if (chain != 0) {
3569 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
3570 chain->setVolume_l(&v, &v);
3571 masterVolume = (float)((v + (1 << 23)) >> 24);
3572 chain.clear();
3573 }
3574
3575 // prepare a new state to push
3576 FastMixerStateQueue *sq = NULL;
3577 FastMixerState *state = NULL;
3578 bool didModify = false;
3579 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003580 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003581 sq = mFastMixer->sq();
3582 state = sq->begin();
3583 }
3584
Andy Hung69aed5f2014-02-25 17:24:40 -08003585 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08003586 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08003587
Eric Laurent81784c32012-11-19 14:55:58 -08003588 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003589 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003590 if (t == 0) {
3591 continue;
3592 }
3593
3594 // this const just means the local variable doesn't change
3595 Track* const track = t.get();
3596
3597 // process fast tracks
3598 if (track->isFastTrack()) {
3599
3600 // It's theoretically possible (though unlikely) for a fast track to be created
3601 // and then removed within the same normal mix cycle. This is not a problem, as
3602 // the track never becomes active so it's fast mixer slot is never touched.
3603 // The converse, of removing an (active) track and then creating a new track
3604 // at the identical fast mixer slot within the same normal mix cycle,
3605 // is impossible because the slot isn't marked available until the end of each cycle.
3606 int j = track->mFastIndex;
3607 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
3608 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
3609 FastTrack *fastTrack = &state->mFastTracks[j];
3610
3611 // Determine whether the track is currently in underrun condition,
3612 // and whether it had a recent underrun.
3613 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
3614 FastTrackUnderruns underruns = ftDump->mUnderruns;
3615 uint32_t recentFull = (underruns.mBitFields.mFull -
3616 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
3617 uint32_t recentPartial = (underruns.mBitFields.mPartial -
3618 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
3619 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
3620 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
3621 uint32_t recentUnderruns = recentPartial + recentEmpty;
3622 track->mObservedUnderruns = underruns;
3623 // don't count underruns that occur while stopping or pausing
3624 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07003625 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
3626 recentUnderruns > 0) {
3627 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
3628 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003629 }
3630
3631 // This is similar to the state machine for normal tracks,
3632 // with a few modifications for fast tracks.
3633 bool isActive = true;
3634 switch (track->mState) {
3635 case TrackBase::STOPPING_1:
3636 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08003637 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003638 track->mState = TrackBase::STOPPING_2;
3639 }
3640 break;
3641 case TrackBase::PAUSING:
3642 // ramp down is not yet implemented
3643 track->setPaused();
3644 break;
3645 case TrackBase::RESUMING:
3646 // ramp up is not yet implemented
3647 track->mState = TrackBase::ACTIVE;
3648 break;
3649 case TrackBase::ACTIVE:
3650 if (recentFull > 0 || recentPartial > 0) {
3651 // track has provided at least some frames recently: reset retry count
3652 track->mRetryCount = kMaxTrackRetries;
3653 }
3654 if (recentUnderruns == 0) {
3655 // no recent underruns: stay active
3656 break;
3657 }
3658 // there has recently been an underrun of some kind
3659 if (track->sharedBuffer() == 0) {
3660 // were any of the recent underruns "empty" (no frames available)?
3661 if (recentEmpty == 0) {
3662 // no, then ignore the partial underruns as they are allowed indefinitely
3663 break;
3664 }
3665 // there has recently been an "empty" underrun: decrement the retry counter
3666 if (--(track->mRetryCount) > 0) {
3667 break;
3668 }
3669 // indicate to client process that the track was disabled because of underrun;
3670 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003671 android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003672 // remove from active list, but state remains ACTIVE [confusing but true]
3673 isActive = false;
3674 break;
3675 }
3676 // fall through
3677 case TrackBase::STOPPING_2:
3678 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003679 case TrackBase::STOPPED:
3680 case TrackBase::FLUSHED: // flush() while active
3681 // Check for presentation complete if track is inactive
3682 // We have consumed all the buffers of this track.
3683 // This would be incomplete if we auto-paused on underrun
3684 {
3685 size_t audioHALFrames =
3686 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3687 size_t framesWritten = mBytesWritten / mFrameSize;
3688 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
3689 // track stays in active list until presentation is complete
3690 break;
3691 }
3692 }
3693 if (track->isStopping_2()) {
3694 track->mState = TrackBase::STOPPED;
3695 }
3696 if (track->isStopped()) {
3697 // Can't reset directly, as fast mixer is still polling this track
3698 // track->reset();
3699 // So instead mark this track as needing to be reset after push with ack
3700 resetMask |= 1 << i;
3701 }
3702 isActive = false;
3703 break;
3704 case TrackBase::IDLE:
3705 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08003706 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08003707 }
3708
3709 if (isActive) {
3710 // was it previously inactive?
3711 if (!(state->mTrackMask & (1 << j))) {
3712 ExtendedAudioBufferProvider *eabp = track;
3713 VolumeProvider *vp = track;
3714 fastTrack->mBufferProvider = eabp;
3715 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08003716 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003717 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08003718 fastTrack->mGeneration++;
3719 state->mTrackMask |= 1 << j;
3720 didModify = true;
3721 // no acknowledgement required for newly active tracks
3722 }
3723 // cache the combined master volume and stream type volume for fast mixer; this
3724 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08003725 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08003726 ++fastTracks;
3727 } else {
3728 // was it previously active?
3729 if (state->mTrackMask & (1 << j)) {
3730 fastTrack->mBufferProvider = NULL;
3731 fastTrack->mGeneration++;
3732 state->mTrackMask &= ~(1 << j);
3733 didModify = true;
3734 // If any fast tracks were removed, we must wait for acknowledgement
3735 // because we're about to decrement the last sp<> on those tracks.
3736 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3737 } else {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003738 LOG_ALWAYS_FATAL("fast track %d should have been active", j);
Eric Laurent81784c32012-11-19 14:55:58 -08003739 }
3740 tracksToRemove->add(track);
3741 // Avoids a misleading display in dumpsys
3742 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
3743 }
3744 continue;
3745 }
3746
3747 { // local variable scope to avoid goto warning
3748
3749 audio_track_cblk_t* cblk = track->cblk();
3750
3751 // The first time a track is added we wait
3752 // for all its buffers to be filled before processing it
3753 int name = track->name();
3754 // make sure that we have enough frames to mix one full buffer.
3755 // enforce this condition only once to enable draining the buffer in case the client
3756 // app does not call stop() and relies on underrun to stop:
3757 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
3758 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003759 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07003760 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07003761 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07003762
3763 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07003764 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07003765 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
3766 // add frames already consumed but not yet released by the resampler
3767 // because mAudioTrackServerProxy->framesReady() will include these frames
3768 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
3769
Eric Laurent81784c32012-11-19 14:55:58 -08003770 uint32_t minFrames = 1;
3771 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
3772 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003773 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08003774 }
Eric Laurent13e4c962013-12-20 17:36:01 -08003775
3776 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07003777 if (ATRACE_ENABLED()) {
3778 // I wish we had formatted trace names
3779 char traceName[16];
3780 strcpy(traceName, "nRdy");
3781 int name = track->name();
3782 if (AudioMixer::TRACK0 <= name &&
3783 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
3784 name -= AudioMixer::TRACK0;
3785 traceName[4] = (name / 10) + '0';
3786 traceName[5] = (name % 10) + '0';
3787 } else {
3788 traceName[4] = '?';
3789 traceName[5] = '?';
3790 }
3791 traceName[6] = '\0';
3792 ATRACE_INT(traceName, framesReady);
3793 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003794 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08003795 !track->isPaused() && !track->isTerminated())
3796 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003797 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003798
3799 mixedTracks++;
3800
Andy Hung69aed5f2014-02-25 17:24:40 -08003801 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
3802 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08003803 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08003804 if (track->mainBuffer() != mSinkBuffer &&
3805 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08003806 if (mEffectBufferEnabled) {
3807 mEffectBufferValid = true; // Later can set directly.
3808 }
Eric Laurent81784c32012-11-19 14:55:58 -08003809 chain = getEffectChain_l(track->sessionId());
3810 // Delegate volume control to effect in track effect chain if needed
3811 if (chain != 0) {
3812 tracksWithEffect++;
3813 } else {
3814 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
3815 "session %d",
3816 name, track->sessionId());
3817 }
3818 }
3819
3820
3821 int param = AudioMixer::VOLUME;
3822 if (track->mFillingUpStatus == Track::FS_FILLED) {
3823 // no ramp for the first volume setting
3824 track->mFillingUpStatus = Track::FS_ACTIVE;
3825 if (track->mState == TrackBase::RESUMING) {
3826 track->mState = TrackBase::ACTIVE;
3827 param = AudioMixer::RAMP_VOLUME;
3828 }
3829 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003830 // FIXME should not make a decision based on mServer
3831 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003832 // If the track is stopped before the first frame was mixed,
3833 // do not apply ramp
3834 param = AudioMixer::RAMP_VOLUME;
3835 }
3836
3837 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07003838 uint32_t vl, vr; // in U8.24 integer format
3839 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08003840 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07003841 vl = vr = 0;
3842 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08003843 if (track->isPausing()) {
3844 track->setPaused();
3845 }
3846 } else {
3847
3848 // read original volumes with volume control
3849 float typeVolume = mStreamTypes[track->streamType()].volume;
3850 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003851 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07003852 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07003853 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
3854 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08003855 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07003856 if (vlf > GAIN_FLOAT_UNITY) {
3857 ALOGV("Track left volume out of range: %.3g", vlf);
3858 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003859 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07003860 if (vrf > GAIN_FLOAT_UNITY) {
3861 ALOGV("Track right volume out of range: %.3g", vrf);
3862 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003863 }
3864 // now apply the master volume and stream type volume
Andy Hung6be49402014-05-30 10:42:03 -07003865 vlf *= v;
3866 vrf *= v;
Eric Laurent81784c32012-11-19 14:55:58 -08003867 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07003868 // then derive vl and vr as U8.24 versions for the effect chain
3869 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
3870 vl = (uint32_t) (scaleto8_24 * vlf);
3871 vr = (uint32_t) (scaleto8_24 * vrf);
3872 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08003873 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08003874 // send level comes from shared memory and so may be corrupt
3875 if (sendLevel > MAX_GAIN_INT) {
3876 ALOGV("Track send level out of range: %04X", sendLevel);
3877 sendLevel = MAX_GAIN_INT;
3878 }
Andy Hung6be49402014-05-30 10:42:03 -07003879 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
3880 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08003881 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003882
Eric Laurent81784c32012-11-19 14:55:58 -08003883 // Delegate volume control to effect in track effect chain if needed
3884 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3885 // Do not ramp volume if volume is controlled by effect
3886 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08003887 // Update remaining floating point volume levels
3888 vlf = (float)vl / (1 << 24);
3889 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08003890 track->mHasVolumeController = true;
3891 } else {
3892 // force no volume ramp when volume controller was just disabled or removed
3893 // from effect chain to avoid volume spike
3894 if (track->mHasVolumeController) {
3895 param = AudioMixer::VOLUME;
3896 }
3897 track->mHasVolumeController = false;
3898 }
3899
Eric Laurent81784c32012-11-19 14:55:58 -08003900 // XXX: these things DON'T need to be done each time
3901 mAudioMixer->setBufferProvider(name, track);
3902 mAudioMixer->enable(name);
3903
Andy Hung6be49402014-05-30 10:42:03 -07003904 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
3905 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
3906 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08003907 mAudioMixer->setParameter(
3908 name,
3909 AudioMixer::TRACK,
3910 AudioMixer::FORMAT, (void *)track->format());
3911 mAudioMixer->setParameter(
3912 name,
3913 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003914 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07003915 mAudioMixer->setParameter(
3916 name,
3917 AudioMixer::TRACK,
3918 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08003919 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07003920 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003921 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08003922 if (reqSampleRate == 0) {
3923 reqSampleRate = mSampleRate;
3924 } else if (reqSampleRate > maxSampleRate) {
3925 reqSampleRate = maxSampleRate;
3926 }
Eric Laurent81784c32012-11-19 14:55:58 -08003927 mAudioMixer->setParameter(
3928 name,
3929 AudioMixer::RESAMPLE,
3930 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003931 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07003932
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07003933 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07003934 mAudioMixer->setParameter(
3935 name,
3936 AudioMixer::TIMESTRETCH,
3937 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07003938 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07003939
Andy Hung69aed5f2014-02-25 17:24:40 -08003940 /*
3941 * Select the appropriate output buffer for the track.
3942 *
Andy Hung98ef9782014-03-04 14:46:50 -08003943 * Tracks with effects go into their own effects chain buffer
3944 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08003945 *
3946 * Other tracks can use mMixerBuffer for higher precision
3947 * channel accumulation. If this buffer is enabled
3948 * (mMixerBufferEnabled true), then selected tracks will accumulate
3949 * into it.
3950 *
3951 */
3952 if (mMixerBufferEnabled
3953 && (track->mainBuffer() == mSinkBuffer
3954 || track->mainBuffer() == mMixerBuffer)) {
3955 mAudioMixer->setParameter(
3956 name,
3957 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08003958 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08003959 mAudioMixer->setParameter(
3960 name,
3961 AudioMixer::TRACK,
3962 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
3963 // TODO: override track->mainBuffer()?
3964 mMixerBufferValid = true;
3965 } else {
3966 mAudioMixer->setParameter(
3967 name,
3968 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08003969 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08003970 mAudioMixer->setParameter(
3971 name,
3972 AudioMixer::TRACK,
3973 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3974 }
Eric Laurent81784c32012-11-19 14:55:58 -08003975 mAudioMixer->setParameter(
3976 name,
3977 AudioMixer::TRACK,
3978 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3979
3980 // reset retry count
3981 track->mRetryCount = kMaxTrackRetries;
3982
3983 // If one track is ready, set the mixer ready if:
3984 // - the mixer was not ready during previous round OR
3985 // - no other track is not ready
3986 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
3987 mixerStatus != MIXER_TRACKS_ENABLED) {
3988 mixerStatus = MIXER_TRACKS_READY;
3989 }
3990 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003991 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Glenn Kasten82aaf942013-07-17 16:05:07 -07003992 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003993 }
Eric Laurent81784c32012-11-19 14:55:58 -08003994 // clear effect chain input buffer if an active track underruns to avoid sending
3995 // previous audio buffer again to effects
3996 chain = getEffectChain_l(track->sessionId());
3997 if (chain != 0) {
3998 chain->clearInputBuffer();
3999 }
4000
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004001 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004002 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
4003 track->isStopped() || track->isPaused()) {
4004 // We have consumed all the buffers of this track.
4005 // Remove it from the list of active tracks.
4006 // TODO: use actual buffer filling status instead of latency when available from
4007 // audio HAL
4008 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
4009 size_t framesWritten = mBytesWritten / mFrameSize;
4010 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
4011 if (track->isStopped()) {
4012 track->reset();
4013 }
4014 tracksToRemove->add(track);
4015 }
4016 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08004017 // No buffers for this track. Give it a few chances to
4018 // fill a buffer, then remove it from active list.
4019 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004020 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004021 tracksToRemove->add(track);
4022 // indicate to client process that the track was disabled because of underrun;
4023 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07004024 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08004025 // If one track is not ready, mark the mixer also not ready if:
4026 // - the mixer was ready during previous round OR
4027 // - no other track is ready
4028 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
4029 mixerStatus != MIXER_TRACKS_READY) {
4030 mixerStatus = MIXER_TRACKS_ENABLED;
4031 }
4032 }
4033 mAudioMixer->disable(name);
4034 }
4035
4036 } // local variable scope to avoid goto warning
4037track_is_ready: ;
4038
4039 }
4040
4041 // Push the new FastMixer state if necessary
4042 bool pauseAudioWatchdog = false;
4043 if (didModify) {
4044 state->mFastTracksGen++;
4045 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4046 if (kUseFastMixer == FastMixer_Dynamic &&
4047 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4048 state->mCommand = FastMixerState::COLD_IDLE;
4049 state->mColdFutexAddr = &mFastMixerFutex;
4050 state->mColdGen++;
4051 mFastMixerFutex = 0;
4052 if (kUseFastMixer == FastMixer_Dynamic) {
4053 mNormalSink = mOutputSink;
4054 }
4055 // If we go into cold idle, need to wait for acknowledgement
4056 // so that fast mixer stops doing I/O.
4057 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4058 pauseAudioWatchdog = true;
4059 }
Eric Laurent81784c32012-11-19 14:55:58 -08004060 }
4061 if (sq != NULL) {
4062 sq->end(didModify);
4063 sq->push(block);
4064 }
4065#ifdef AUDIO_WATCHDOG
4066 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4067 mAudioWatchdog->pause();
4068 }
4069#endif
4070
4071 // Now perform the deferred reset on fast tracks that have stopped
4072 while (resetMask != 0) {
4073 size_t i = __builtin_ctz(resetMask);
4074 ALOG_ASSERT(i < count);
4075 resetMask &= ~(1 << i);
4076 sp<Track> t = mActiveTracks[i].promote();
4077 if (t == 0) {
4078 continue;
4079 }
4080 Track* track = t.get();
4081 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
4082 track->reset();
4083 }
4084
4085 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004086 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004087
Eric Laurent97d547d2014-09-02 14:45:53 -07004088 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
4089 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07004090 }
4091
4092 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07004093 // as long as there are effects we should clear the effects buffer, to avoid
4094 // passing a non-clean buffer to the effect chain
4095 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07004096 }
Andy Hung69aed5f2014-02-25 17:24:40 -08004097 // sink or mix buffer must be cleared if all tracks are connected to an
4098 // effect chain as in this case the mixer will not write to the sink or mix buffer
4099 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08004100 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4101 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08004102 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08004103 if (mMixerBufferValid) {
4104 memset(mMixerBuffer, 0, mMixerBufferSize);
4105 // TODO: In testing, mSinkBuffer below need not be cleared because
4106 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
4107 // after mixing.
4108 //
4109 // To enforce this guarantee:
4110 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4111 // (mixedTracks == 0 && fastTracks > 0))
4112 // must imply MIXER_TRACKS_READY.
4113 // Later, we may clear buffers regardless, and skip much of this logic.
4114 }
Andy Hung98ef9782014-03-04 14:46:50 -08004115 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07004116 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004117 }
4118
4119 // if any fast tracks, then status is ready
4120 mMixerStatusIgnoringFastTracks = mixerStatus;
4121 if (fastTracks > 0) {
4122 mixerStatus = MIXER_TRACKS_READY;
4123 }
4124 return mixerStatus;
4125}
4126
4127// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07004128int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
4129 audio_format_t format, int sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08004130{
Andy Hunge8a1ced2014-05-09 15:02:21 -07004131 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08004132}
4133
4134// deleteTrackName_l() must be called with ThreadBase::mLock held
4135void AudioFlinger::MixerThread::deleteTrackName_l(int name)
4136{
4137 ALOGV("remove track (%d) and delete from mixer", name);
4138 mAudioMixer->deleteTrackName(name);
4139}
4140
Eric Laurent10351942014-05-08 18:49:52 -07004141// checkForNewParameter_l() must be called with ThreadBase::mLock held
4142bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
4143 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004144{
Eric Laurent81784c32012-11-19 14:55:58 -08004145 bool reconfig = false;
4146
Eric Laurent10351942014-05-08 18:49:52 -07004147 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004148
Eric Laurent10351942014-05-08 18:49:52 -07004149 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
4150 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004151 if (mFastMixer != 0) {
Eric Laurent10351942014-05-08 18:49:52 -07004152 FastMixerStateQueue *sq = mFastMixer->sq();
4153 FastMixerState *state = sq->begin();
4154 if (!(state->mCommand & FastMixerState::IDLE)) {
4155 previousCommand = state->mCommand;
4156 state->mCommand = FastMixerState::HOT_IDLE;
4157 sq->end();
4158 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
4159 } else {
4160 sq->end(false /*didModify*/);
Eric Laurent81784c32012-11-19 14:55:58 -08004161 }
Eric Laurent10351942014-05-08 18:49:52 -07004162 }
Eric Laurent81784c32012-11-19 14:55:58 -08004163
Eric Laurent10351942014-05-08 18:49:52 -07004164 AudioParameter param = AudioParameter(keyValuePair);
4165 int value;
4166 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4167 reconfig = true;
4168 }
4169 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004170 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004171 status = BAD_VALUE;
4172 } else {
4173 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08004174 reconfig = true;
4175 }
Eric Laurent10351942014-05-08 18:49:52 -07004176 }
4177 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004178 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004179 status = BAD_VALUE;
4180 } else {
4181 // no need to save value, since it's constant
4182 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004183 }
Eric Laurent10351942014-05-08 18:49:52 -07004184 }
4185 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4186 // do not accept frame count changes if tracks are open as the track buffer
4187 // size depends on frame count and correct behavior would not be guaranteed
4188 // if frame count is changed after track creation
4189 if (!mTracks.isEmpty()) {
4190 status = INVALID_OPERATION;
4191 } else {
4192 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004193 }
Eric Laurent10351942014-05-08 18:49:52 -07004194 }
4195 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004196#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07004197 // when changing the audio output device, call addBatteryData to notify
4198 // the change
4199 if (mOutDevice != value) {
4200 uint32_t params = 0;
4201 // check whether speaker is on
4202 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
4203 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08004204 }
Eric Laurent10351942014-05-08 18:49:52 -07004205
4206 audio_devices_t deviceWithoutSpeaker
4207 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
4208 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07004209 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07004210 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4211 }
4212
4213 if (params != 0) {
4214 addBatteryData(params);
4215 }
4216 }
Eric Laurent81784c32012-11-19 14:55:58 -08004217#endif
4218
Eric Laurent10351942014-05-08 18:49:52 -07004219 // forward device change to effects that have requested to be
4220 // aware of attached audio device.
4221 if (value != AUDIO_DEVICE_NONE) {
4222 mOutDevice = value;
4223 for (size_t i = 0; i < mEffectChains.size(); i++) {
4224 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08004225 }
4226 }
Eric Laurent10351942014-05-08 18:49:52 -07004227 }
Eric Laurent81784c32012-11-19 14:55:58 -08004228
Eric Laurent10351942014-05-08 18:49:52 -07004229 if (status == NO_ERROR) {
4230 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4231 keyValuePair.string());
4232 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004233 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004234 mStandby = true;
4235 mBytesWritten = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004236 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Eric Laurent10351942014-05-08 18:49:52 -07004237 keyValuePair.string());
Eric Laurent81784c32012-11-19 14:55:58 -08004238 }
Eric Laurent10351942014-05-08 18:49:52 -07004239 if (status == NO_ERROR && reconfig) {
4240 readOutputParameters_l();
4241 delete mAudioMixer;
4242 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4243 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07004244 int name = getTrackName_l(mTracks[i]->mChannelMask,
4245 mTracks[i]->mFormat, mTracks[i]->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07004246 if (name < 0) {
4247 break;
4248 }
4249 mTracks[i]->mName = name;
4250 }
Eric Laurent73e26b62015-04-27 16:55:58 -07004251 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004252 }
Eric Laurent81784c32012-11-19 14:55:58 -08004253 }
4254
4255 if (!(previousCommand & FastMixerState::IDLE)) {
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004256 ALOG_ASSERT(mFastMixer != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08004257 FastMixerStateQueue *sq = mFastMixer->sq();
4258 FastMixerState *state = sq->begin();
4259 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
4260 state->mCommand = previousCommand;
4261 sq->end();
4262 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4263 }
4264
4265 return reconfig;
4266}
4267
4268
4269void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
4270{
4271 const size_t SIZE = 256;
4272 char buffer[SIZE];
4273 String8 result;
4274
4275 PlaybackThread::dumpInternals(fd, args);
4276
Elliott Hughes87cebad2014-05-22 10:14:43 -07004277 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Eric Laurent81784c32012-11-19 14:55:58 -08004278
4279 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten4182c4e2013-07-15 14:45:07 -07004280 const FastMixerDumpState copy(mFastMixerDumpState);
Eric Laurent81784c32012-11-19 14:55:58 -08004281 copy.dump(fd);
4282
4283#ifdef STATE_QUEUE_DUMP
4284 // Similar for state queue
4285 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4286 observerCopy.dump(fd);
4287 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4288 mutatorCopy.dump(fd);
4289#endif
4290
Glenn Kasten46909e72013-02-26 09:20:22 -08004291#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08004292 // Write the tee output to a .wav file
4293 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08004294#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004295
4296#ifdef AUDIO_WATCHDOG
4297 if (mAudioWatchdog != 0) {
4298 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4299 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4300 wdCopy.dump(fd);
4301 }
4302#endif
4303}
4304
4305uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4306{
4307 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4308}
4309
4310uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4311{
4312 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4313}
4314
4315void AudioFlinger::MixerThread::cacheParameters_l()
4316{
4317 PlaybackThread::cacheParameters_l();
4318
4319 // FIXME: Relaxed timing because of a certain device that can't meet latency
4320 // Should be reduced to 2x after the vendor fixes the driver issue
4321 // increase threshold again due to low power audio mode. The way this warning
4322 // threshold is calculated and its usefulness should be reconsidered anyway.
4323 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4324}
4325
4326// ----------------------------------------------------------------------------
4327
4328AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07004329 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device, bool systemReady)
4330 : PlaybackThread(audioFlinger, output, id, device, DIRECT, systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08004331 // mLeftVolFloat, mRightVolFloat
4332{
4333}
4334
Eric Laurentbfb1b832013-01-07 09:53:42 -08004335AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4336 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07004337 ThreadBase::type_t type, bool systemReady)
4338 : PlaybackThread(audioFlinger, output, id, device, type, systemReady)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004339 // mLeftVolFloat, mRightVolFloat
4340{
4341}
4342
Eric Laurent81784c32012-11-19 14:55:58 -08004343AudioFlinger::DirectOutputThread::~DirectOutputThread()
4344{
4345}
4346
Eric Laurentbfb1b832013-01-07 09:53:42 -08004347void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
4348{
4349 audio_track_cblk_t* cblk = track->cblk();
4350 float left, right;
4351
4352 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4353 left = right = 0;
4354 } else {
4355 float typeVolume = mStreamTypes[track->streamType()].volume;
4356 float v = mMasterVolume * typeVolume;
4357 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004358 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4359 left = float_from_gain(gain_minifloat_unpack_left(vlr));
4360 if (left > GAIN_FLOAT_UNITY) {
4361 left = GAIN_FLOAT_UNITY;
4362 }
4363 left *= v;
4364 right = float_from_gain(gain_minifloat_unpack_right(vlr));
4365 if (right > GAIN_FLOAT_UNITY) {
4366 right = GAIN_FLOAT_UNITY;
4367 }
4368 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004369 }
4370
4371 if (lastTrack) {
4372 if (left != mLeftVolFloat || right != mRightVolFloat) {
4373 mLeftVolFloat = left;
4374 mRightVolFloat = right;
4375
4376 // Convert volumes from float to 8.24
4377 uint32_t vl = (uint32_t)(left * (1 << 24));
4378 uint32_t vr = (uint32_t)(right * (1 << 24));
4379
4380 // Delegate volume control to effect in track effect chain if needed
4381 // only one effect chain can be present on DirectOutputThread, so if
4382 // there is one, the track is connected to it
4383 if (!mEffectChains.isEmpty()) {
4384 mEffectChains[0]->setVolume_l(&vl, &vr);
4385 left = (float)vl / (1 << 24);
4386 right = (float)vr / (1 << 24);
4387 }
4388 if (mOutput->stream->set_volume) {
4389 mOutput->stream->set_volume(mOutput->stream, left, right);
4390 }
4391 }
4392 }
4393}
4394
4395
Eric Laurent81784c32012-11-19 14:55:58 -08004396AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4397 Vector< sp<Track> > *tracksToRemove
4398)
4399{
Eric Laurentd595b7c2013-04-03 17:27:56 -07004400 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08004401 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004402 bool doHwPause = false;
4403 bool doHwResume = false;
4404 bool flushPending = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004405
4406 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07004407 for (size_t i = 0; i < count; i++) {
4408 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08004409 // The track died recently
4410 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004411 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08004412 }
4413
4414 Track* const track = t.get();
4415 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07004416 // Only consider last track started for volume and mixer state control.
4417 // In theory an older track could underrun and restart after the new one starts
4418 // but as we only care about the transition phase between two tracks on a
4419 // direct output, it is not a problem to ignore the underrun case.
4420 sp<Track> l = mLatestActiveTrack.promote();
4421 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08004422
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004423 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004424 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004425 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004426 doHwPause = true;
4427 mHwPaused = true;
4428 }
4429 tracksToRemove->add(track);
4430 } else if (track->isFlushPending()) {
4431 track->flushAck();
4432 if (last) {
4433 flushPending = true;
4434 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004435 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004436 track->resumeAck();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004437 if (last && mHwPaused) {
4438 doHwResume = true;
4439 mHwPaused = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004440 }
4441 }
4442
Eric Laurent81784c32012-11-19 14:55:58 -08004443 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08004444 // for all its buffers to be filled before processing it.
4445 // Allow draining the buffer in case the client
4446 // app does not call stop() and relies on underrun to stop:
4447 // hence the test on (track->mRetryCount > 1).
4448 // If retryCount<=1 then track is about to underrun and be removed.
Eric Laurent81784c32012-11-19 14:55:58 -08004449 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08004450 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
4451 && (track->mRetryCount > 1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004452 minFrames = mNormalFrameCount;
4453 } else {
4454 minFrames = 1;
4455 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004456
Eric Laurentab5cdba2014-06-09 17:22:27 -07004457 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4458 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08004459 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004460 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08004461
4462 if (track->mFillingUpStatus == Track::FS_FILLED) {
4463 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004464 // make sure processVolume_l() will apply new volume even if 0
4465 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004466 if (!mHwSupportsPause) {
4467 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08004468 }
4469 }
4470
4471 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004472 processVolume_l(track, last);
4473 if (last) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004474 // reset retry count
4475 track->mRetryCount = kMaxTrackRetriesDirect;
4476 mActiveTrack = t;
4477 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07004478 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004479 doHwResume = true;
4480 mHwPaused = false;
4481 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004482 }
Eric Laurent81784c32012-11-19 14:55:58 -08004483 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004484 // clear effect chain input buffer if the last active track started underruns
4485 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07004486 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004487 mEffectChains[0]->clearInputBuffer();
4488 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004489 if (track->isStopping_1()) {
4490 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07004491 if (last && mHwPaused) {
4492 doHwResume = true;
4493 mHwPaused = false;
4494 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004495 }
4496 if ((track->sharedBuffer() != 0) || track->isStopped() ||
4497 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004498 // We have consumed all the buffers of this track.
4499 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07004500 size_t audioHALFrames;
4501 if (audio_is_linear_pcm(mFormat)) {
4502 audioHALFrames = (latency_l() * mSampleRate) / 1000;
4503 } else {
4504 audioHALFrames = 0;
4505 }
4506
Eric Laurent81784c32012-11-19 14:55:58 -08004507 size_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07004508 if (mStandby || !last ||
4509 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004510 if (track->isStopping_2()) {
4511 track->mState = TrackBase::STOPPED;
4512 }
Eric Laurent81784c32012-11-19 14:55:58 -08004513 if (track->isStopped()) {
4514 track->reset();
4515 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004516 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08004517 }
4518 } else {
4519 // No buffers for this track. Give it a few chances to
4520 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07004521 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08004522 if (--(track->mRetryCount) <= 0) {
4523 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07004524 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004525 // indicate to client process that the track was disabled because of underrun;
4526 // it will then automatically call start() when data is available
4527 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004528 } else if (last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004529 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07004530 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004531 doHwPause = true;
4532 mHwPaused = true;
4533 }
Eric Laurent81784c32012-11-19 14:55:58 -08004534 }
4535 }
4536 }
4537 }
4538
Eric Laurentd1f69b02014-12-15 14:33:13 -08004539 // if an active track did not command a flush, check for pending flush on stopped tracks
4540 if (!flushPending) {
4541 for (size_t i = 0; i < mTracks.size(); i++) {
4542 if (mTracks[i]->isFlushPending()) {
4543 mTracks[i]->flushAck();
4544 flushPending = true;
4545 }
4546 }
4547 }
4548
4549 // make sure the pause/flush/resume sequence is executed in the right order.
4550 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4551 // before flush and then resume HW. This can happen in case of pause/flush/resume
4552 // if resume is received before pause is executed.
4553 if (mHwSupportsPause && !mStandby &&
4554 (doHwPause || (flushPending && !mHwPaused && (count != 0)))) {
4555 mOutput->stream->pause(mOutput->stream);
4556 }
4557 if (flushPending) {
4558 flushHw_l();
4559 }
4560 if (mHwSupportsPause && !mStandby && doHwResume) {
4561 mOutput->stream->resume(mOutput->stream);
4562 }
Eric Laurent81784c32012-11-19 14:55:58 -08004563 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004564 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004565
4566 return mixerStatus;
4567}
4568
4569void AudioFlinger::DirectOutputThread::threadLoop_mix()
4570{
Eric Laurent81784c32012-11-19 14:55:58 -08004571 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08004572 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004573 // output audio to hardware
4574 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07004575 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004576 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08004577 status_t status = mActiveTrack->getNextBuffer(&buffer);
4578 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08004579 memset(curBuf, 0, frameCount * mFrameSize);
4580 break;
4581 }
4582 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
4583 frameCount -= buffer.frameCount;
4584 curBuf += buffer.frameCount * mFrameSize;
4585 mActiveTrack->releaseBuffer(&buffer);
4586 }
Andy Hung2098f272014-02-27 14:00:06 -08004587 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004588 mSleepTimeUs = 0;
4589 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08004590 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004591}
4592
4593void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
4594{
Eric Laurentd1f69b02014-12-15 14:33:13 -08004595 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004596 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004597 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004598 return;
4599 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004600 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004601 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004602 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004603 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004604 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004605 }
4606 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08004607 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004608 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004609 }
4610}
4611
Eric Laurentd1f69b02014-12-15 14:33:13 -08004612void AudioFlinger::DirectOutputThread::threadLoop_exit()
4613{
4614 {
4615 Mutex::Autolock _l(mLock);
4616 bool flushPending = false;
4617 for (size_t i = 0; i < mTracks.size(); i++) {
4618 if (mTracks[i]->isFlushPending()) {
4619 mTracks[i]->flushAck();
4620 flushPending = true;
4621 }
4622 }
4623 if (flushPending) {
4624 flushHw_l();
4625 }
4626 }
4627 PlaybackThread::threadLoop_exit();
4628}
4629
4630// must be called with thread mutex locked
4631bool AudioFlinger::DirectOutputThread::shouldStandby_l()
4632{
4633 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07004634 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004635
4636 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4637 // after a timeout and we will enter standby then.
4638 if (mTracks.size() > 0) {
4639 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07004640 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
4641 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004642 }
4643
Eric Laurent5cff4032015-05-26 13:49:58 -07004644 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08004645}
4646
Eric Laurent81784c32012-11-19 14:55:58 -08004647// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004648int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Andy Hunge8a1ced2014-05-09 15:02:21 -07004649 audio_format_t format __unused, int sessionId __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004650{
4651 return 0;
4652}
4653
4654// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004655void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004656{
4657}
4658
Eric Laurent10351942014-05-08 18:49:52 -07004659// checkForNewParameter_l() must be called with ThreadBase::mLock held
4660bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
4661 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004662{
4663 bool reconfig = false;
4664
Eric Laurent10351942014-05-08 18:49:52 -07004665 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004666
Eric Laurent10351942014-05-08 18:49:52 -07004667 AudioParameter param = AudioParameter(keyValuePair);
4668 int value;
4669 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4670 // forward device change to effects that have requested to be
4671 // aware of attached audio device.
4672 if (value != AUDIO_DEVICE_NONE) {
4673 mOutDevice = value;
4674 for (size_t i = 0; i < mEffectChains.size(); i++) {
4675 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07004676 }
4677 }
Eric Laurent81784c32012-11-19 14:55:58 -08004678 }
Eric Laurent10351942014-05-08 18:49:52 -07004679 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4680 // do not accept frame count changes if tracks are open as the track buffer
4681 // size depends on frame count and correct behavior would not be garantied
4682 // if frame count is changed after track creation
4683 if (!mTracks.isEmpty()) {
4684 status = INVALID_OPERATION;
4685 } else {
4686 reconfig = true;
4687 }
4688 }
4689 if (status == NO_ERROR) {
4690 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4691 keyValuePair.string());
4692 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004693 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004694 mStandby = true;
4695 mBytesWritten = 0;
4696 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4697 keyValuePair.string());
4698 }
4699 if (status == NO_ERROR && reconfig) {
4700 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07004701 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004702 }
4703 }
4704
Eric Laurent81784c32012-11-19 14:55:58 -08004705 return reconfig;
4706}
4707
4708uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
4709{
4710 uint32_t time;
4711 if (audio_is_linear_pcm(mFormat)) {
4712 time = PlaybackThread::activeSleepTimeUs();
4713 } else {
4714 time = 10000;
4715 }
4716 return time;
4717}
4718
4719uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
4720{
4721 uint32_t time;
4722 if (audio_is_linear_pcm(mFormat)) {
4723 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
4724 } else {
4725 time = 10000;
4726 }
4727 return time;
4728}
4729
4730uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
4731{
4732 uint32_t time;
4733 if (audio_is_linear_pcm(mFormat)) {
4734 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
4735 } else {
4736 time = 10000;
4737 }
4738 return time;
4739}
4740
4741void AudioFlinger::DirectOutputThread::cacheParameters_l()
4742{
4743 PlaybackThread::cacheParameters_l();
4744
4745 // use shorter standby delay as on normal output to release
4746 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07004747 // no delay on outputs with HW A/V sync
4748 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004749 mStandbyDelayNs = 0;
Eric Laurent5cff4032015-05-26 13:49:58 -07004750 } else if ((mType == OFFLOAD) && !audio_is_linear_pcm(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004751 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07004752 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004753 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07004754 }
Eric Laurent81784c32012-11-19 14:55:58 -08004755}
4756
Eric Laurente659ef42014-09-29 13:06:46 -07004757void AudioFlinger::DirectOutputThread::flushHw_l()
4758{
Phil Burk062e67a2015-02-11 13:40:50 -08004759 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08004760 mHwPaused = false;
Eric Laurente659ef42014-09-29 13:06:46 -07004761}
4762
Eric Laurent81784c32012-11-19 14:55:58 -08004763// ----------------------------------------------------------------------------
4764
Eric Laurentbfb1b832013-01-07 09:53:42 -08004765AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07004766 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004767 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07004768 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07004769 mWriteAckSequence(0),
4770 mDrainSequence(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004771{
4772}
4773
4774AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
4775{
4776}
4777
4778void AudioFlinger::AsyncCallbackThread::onFirstRef()
4779{
4780 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
4781}
4782
4783bool AudioFlinger::AsyncCallbackThread::threadLoop()
4784{
4785 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004786 uint32_t writeAckSequence;
4787 uint32_t drainSequence;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004788
4789 {
4790 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08004791 while (!((mWriteAckSequence & 1) ||
4792 (mDrainSequence & 1) ||
4793 exitPending())) {
4794 mWaitWorkCV.wait(mLock);
4795 }
4796
Eric Laurentbfb1b832013-01-07 09:53:42 -08004797 if (exitPending()) {
4798 break;
4799 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004800 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
4801 mWriteAckSequence, mDrainSequence);
4802 writeAckSequence = mWriteAckSequence;
4803 mWriteAckSequence &= ~1;
4804 drainSequence = mDrainSequence;
4805 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004806 }
4807 {
Eric Laurent4de95592013-09-26 15:28:21 -07004808 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
4809 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004810 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004811 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004812 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004813 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004814 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004815 }
4816 }
4817 }
4818 }
4819 return false;
4820}
4821
4822void AudioFlinger::AsyncCallbackThread::exit()
4823{
4824 ALOGV("AsyncCallbackThread::exit");
4825 Mutex::Autolock _l(mLock);
4826 requestExit();
4827 mWaitWorkCV.broadcast();
4828}
4829
Eric Laurent3b4529e2013-09-05 18:09:19 -07004830void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004831{
4832 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004833 // bit 0 is cleared
4834 mWriteAckSequence = sequence << 1;
4835}
4836
4837void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
4838{
4839 Mutex::Autolock _l(mLock);
4840 // ignore unexpected callbacks
4841 if (mWriteAckSequence & 2) {
4842 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004843 mWaitWorkCV.signal();
4844 }
4845}
4846
Eric Laurent3b4529e2013-09-05 18:09:19 -07004847void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004848{
4849 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004850 // bit 0 is cleared
4851 mDrainSequence = sequence << 1;
4852}
4853
4854void AudioFlinger::AsyncCallbackThread::resetDraining()
4855{
4856 Mutex::Autolock _l(mLock);
4857 // ignore unexpected callbacks
4858 if (mDrainSequence & 2) {
4859 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004860 mWaitWorkCV.signal();
4861 }
4862}
4863
4864
4865// ----------------------------------------------------------------------------
4866AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07004867 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady)
4868 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady),
Eric Laurentd7e59222013-11-15 12:02:28 -08004869 mPausedBytesRemaining(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004870{
Eric Laurentfd477972013-10-25 18:10:40 -07004871 //FIXME: mStandby should be set to true by ThreadBase constructor
4872 mStandby = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004873}
4874
Eric Laurentbfb1b832013-01-07 09:53:42 -08004875void AudioFlinger::OffloadThread::threadLoop_exit()
4876{
4877 if (mFlushPending || mHwPaused) {
4878 // If a flush is pending or track was paused, just discard buffered data
4879 flushHw_l();
4880 } else {
4881 mMixerStatus = MIXER_DRAIN_ALL;
4882 threadLoop_drain();
4883 }
Uday Gupta56604aa2014-05-13 11:19:17 -07004884 if (mUseAsyncWrite) {
4885 ALOG_ASSERT(mCallbackThread != 0);
4886 mCallbackThread->exit();
4887 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004888 PlaybackThread::threadLoop_exit();
4889}
4890
4891AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
4892 Vector< sp<Track> > *tracksToRemove
4893)
4894{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004895 size_t count = mActiveTracks.size();
4896
4897 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07004898 bool doHwPause = false;
4899 bool doHwResume = false;
4900
Eric Laurentede6c3b2013-09-19 14:37:46 -07004901 ALOGV("OffloadThread::prepareTracks_l active tracks %d", count);
4902
Eric Laurentbfb1b832013-01-07 09:53:42 -08004903 // find out which tracks need to be processed
4904 for (size_t i = 0; i < count; i++) {
4905 sp<Track> t = mActiveTracks[i].promote();
4906 // The track died recently
4907 if (t == 0) {
4908 continue;
4909 }
4910 Track* const track = t.get();
4911 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07004912 // Only consider last track started for volume and mixer state control.
4913 // In theory an older track could underrun and restart after the new one starts
4914 // but as we only care about the transition phase between two tracks on a
4915 // direct output, it is not a problem to ignore the underrun case.
4916 sp<Track> l = mLatestActiveTrack.promote();
4917 bool last = l.get() == track;
4918
Haynes Mathew George7844f672014-01-15 12:32:55 -08004919 if (track->isInvalid()) {
4920 ALOGW("An invalidated track shouldn't be in active list");
4921 tracksToRemove->add(track);
4922 continue;
4923 }
4924
4925 if (track->mState == TrackBase::IDLE) {
4926 ALOGW("An idle track shouldn't be in active list");
4927 continue;
4928 }
4929
Eric Laurentbfb1b832013-01-07 09:53:42 -08004930 if (track->isPausing()) {
4931 track->setPaused();
4932 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07004933 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07004934 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004935 mHwPaused = true;
4936 }
4937 // If we were part way through writing the mixbuffer to
4938 // the HAL we must save this until we resume
4939 // BUG - this will be wrong if a different track is made active,
4940 // in that case we want to discard the pending data in the
4941 // mixbuffer and tell the client to present it again when the
4942 // track is resumed
4943 mPausedWriteLength = mCurrentWriteLength;
4944 mPausedBytesRemaining = mBytesRemaining;
4945 mBytesRemaining = 0; // stop writing
4946 }
4947 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08004948 } else if (track->isFlushPending()) {
4949 track->flushAck();
4950 if (last) {
4951 mFlushPending = true;
4952 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08004953 } else if (track->isResumePending()){
4954 track->resumeAck();
4955 if (last) {
4956 if (mPausedBytesRemaining) {
4957 // Need to continue write that was interrupted
4958 mCurrentWriteLength = mPausedWriteLength;
4959 mBytesRemaining = mPausedBytesRemaining;
4960 mPausedBytesRemaining = 0;
4961 }
4962 if (mHwPaused) {
4963 doHwResume = true;
4964 mHwPaused = false;
4965 // threadLoop_mix() will handle the case that we need to
4966 // resume an interrupted write
4967 }
4968 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004969 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08004970
4971 // Do not handle new data in this iteration even if track->framesReady()
4972 mixerStatus = MIXER_TRACKS_ENABLED;
4973 }
4974 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07004975 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004976 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004977 if (track->mFillingUpStatus == Track::FS_FILLED) {
4978 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004979 // make sure processVolume_l() will apply new volume even if 0
4980 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004981 }
4982
4983 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08004984 sp<Track> previousTrack = mPreviousTrack.promote();
4985 if (previousTrack != 0) {
4986 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08004987 // Flush any data still being written from last track
4988 mBytesRemaining = 0;
4989 if (mPausedBytesRemaining) {
4990 // Last track was paused so we also need to flush saved
4991 // mixbuffer state and invalidate track so that it will
4992 // re-submit that unwritten data when it is next resumed
4993 mPausedBytesRemaining = 0;
4994 // Invalidate is a bit drastic - would be more efficient
4995 // to have a flag to tell client that some of the
4996 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08004997 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004998 }
4999 // flush data already sent to the DSP if changing audio session as audio
5000 // comes from a different source. Also invalidate previous track to force a
5001 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08005002 if (previousTrack->sessionId() != track->sessionId()) {
5003 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005004 }
5005 }
5006 }
5007 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005008 // reset retry count
5009 track->mRetryCount = kMaxTrackRetriesOffload;
5010 mActiveTrack = t;
5011 mixerStatus = MIXER_TRACKS_READY;
5012 }
5013 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005014 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005015 if (track->isStopping_1()) {
5016 // Hardware buffer can hold a large amount of audio so we must
5017 // wait for all current track's data to drain before we say
5018 // that the track is stopped.
5019 if (mBytesRemaining == 0) {
5020 // Only start draining when all data in mixbuffer
5021 // has been written
5022 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
5023 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005024 // do not drain if no data was ever sent to HAL (mStandby == true)
5025 if (last && !mStandby) {
Eric Laurent1b9f9b12013-11-12 19:10:17 -08005026 // do not modify drain sequence if we are already draining. This happens
5027 // when resuming from pause after drain.
5028 if ((mDrainSequence & 1) == 0) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005029 mSleepTimeUs = 0;
5030 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent1b9f9b12013-11-12 19:10:17 -08005031 mixerStatus = MIXER_DRAIN_TRACK;
5032 mDrainSequence += 2;
5033 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005034 if (mHwPaused) {
5035 // It is possible to move from PAUSED to STOPPING_1 without
5036 // a resume so we must ensure hardware is running
Eric Laurent1b9f9b12013-11-12 19:10:17 -08005037 doHwResume = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005038 mHwPaused = false;
5039 }
5040 }
5041 }
5042 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005043 // Drain has completed or we are in standby, signal presentation complete
5044 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005045 track->mState = TrackBase::STOPPED;
5046 size_t audioHALFrames =
5047 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
5048 size_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08005049 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005050 track->presentationComplete(framesWritten, audioHALFrames);
5051 track->reset();
5052 tracksToRemove->add(track);
5053 }
5054 } else {
5055 // No buffers for this track. Give it a few chances to
5056 // fill a buffer, then remove it from active list.
5057 if (--(track->mRetryCount) <= 0) {
5058 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
5059 track->name());
5060 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08005061 // indicate to client process that the track was disabled because of underrun;
5062 // it will then automatically call start() when data is available
5063 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005064 } else if (last){
5065 mixerStatus = MIXER_TRACKS_ENABLED;
5066 }
5067 }
5068 }
5069 // compute volume for this track
5070 processVolume_l(track, last);
5071 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005072
Eric Laurentea0fade2013-10-04 16:23:48 -07005073 // make sure the pause/flush/resume sequence is executed in the right order.
5074 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5075 // before flush and then resume HW. This can happen in case of pause/flush/resume
5076 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07005077 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurent972a1732013-09-04 09:42:59 -07005078 mOutput->stream->pause(mOutput->stream);
5079 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005080 if (mFlushPending) {
5081 flushHw_l();
5082 mFlushPending = false;
5083 }
Eric Laurentfd477972013-10-25 18:10:40 -07005084 if (!mStandby && doHwResume) {
Eric Laurent972a1732013-09-04 09:42:59 -07005085 mOutput->stream->resume(mOutput->stream);
5086 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005087
Eric Laurentbfb1b832013-01-07 09:53:42 -08005088 // remove all the tracks that need to be...
5089 removeTracks_l(*tracksToRemove);
5090
5091 return mixerStatus;
5092}
5093
Eric Laurentbfb1b832013-01-07 09:53:42 -08005094// must be called with thread mutex locked
5095bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
5096{
Eric Laurent3b4529e2013-09-05 18:09:19 -07005097 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
5098 mWriteAckSequence, mDrainSequence);
5099 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005100 return true;
5101 }
5102 return false;
5103}
5104
Eric Laurentbfb1b832013-01-07 09:53:42 -08005105bool AudioFlinger::OffloadThread::waitingAsyncCallback()
5106{
5107 Mutex::Autolock _l(mLock);
5108 return waitingAsyncCallback_l();
5109}
5110
5111void AudioFlinger::OffloadThread::flushHw_l()
5112{
Eric Laurente659ef42014-09-29 13:06:46 -07005113 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005114 // Flush anything still waiting in the mixbuffer
5115 mCurrentWriteLength = 0;
5116 mBytesRemaining = 0;
5117 mPausedWriteLength = 0;
5118 mPausedBytesRemaining = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08005119
Eric Laurentbfb1b832013-01-07 09:53:42 -08005120 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005121 // discard any pending drain or write ack by incrementing sequence
5122 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5123 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005124 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005125 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5126 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005127 }
5128}
5129
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08005130void AudioFlinger::OffloadThread::onAddNewTrack_l()
5131{
5132 sp<Track> previousTrack = mPreviousTrack.promote();
5133 sp<Track> latestTrack = mLatestActiveTrack.promote();
5134
5135 if (previousTrack != 0 && latestTrack != 0 &&
5136 (previousTrack->sessionId() != latestTrack->sessionId())) {
5137 mFlushPending = true;
5138 }
5139 PlaybackThread::onAddNewTrack_l();
5140}
5141
Eric Laurentbfb1b832013-01-07 09:53:42 -08005142// ----------------------------------------------------------------------------
5143
Eric Laurent81784c32012-11-19 14:55:58 -08005144AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07005145 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08005146 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
Eric Laurent72e3f392015-05-20 14:43:50 -07005147 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08005148 mWaitTimeMs(UINT_MAX)
5149{
5150 addOutputTrack(mainThread);
5151}
5152
5153AudioFlinger::DuplicatingThread::~DuplicatingThread()
5154{
5155 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5156 mOutputTracks[i]->destroy();
5157 }
5158}
5159
5160void AudioFlinger::DuplicatingThread::threadLoop_mix()
5161{
5162 // mix buffers...
5163 if (outputsReady(outputTracks)) {
5164 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
5165 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08005166 if (mMixerBufferValid) {
5167 memset(mMixerBuffer, 0, mMixerBufferSize);
5168 } else {
5169 memset(mSinkBuffer, 0, mSinkBufferSize);
5170 }
Eric Laurent81784c32012-11-19 14:55:58 -08005171 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005172 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005173 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005174 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005175 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005176}
5177
5178void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
5179{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005180 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005181 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005182 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005183 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005184 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005185 }
5186 } else if (mBytesWritten != 0) {
5187 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5188 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005189 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005190 } else {
5191 // flush remaining overflow buffers in output tracks
5192 writeFrames = 0;
5193 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005194 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005195 }
5196}
5197
Eric Laurentbfb1b832013-01-07 09:53:42 -08005198ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005199{
5200 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08005201 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005202 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07005203 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08005204 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005205}
5206
5207void AudioFlinger::DuplicatingThread::threadLoop_standby()
5208{
5209 // DuplicatingThread implements standby by stopping all tracks
5210 for (size_t i = 0; i < outputTracks.size(); i++) {
5211 outputTracks[i]->stop();
5212 }
5213}
5214
5215void AudioFlinger::DuplicatingThread::saveOutputTracks()
5216{
5217 outputTracks = mOutputTracks;
5218}
5219
5220void AudioFlinger::DuplicatingThread::clearOutputTracks()
5221{
5222 outputTracks.clear();
5223}
5224
5225void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
5226{
5227 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08005228 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
5229 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
5230 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
5231 const size_t frameCount =
5232 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
5233 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
5234 // from different OutputTracks and their associated MixerThreads (e.g. one may
5235 // nearly empty and the other may be dropping data).
5236
5237 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08005238 this,
5239 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08005240 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08005241 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005242 frameCount,
5243 IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08005244 if (outputTrack->cblk() != NULL) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005245 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
Eric Laurent81784c32012-11-19 14:55:58 -08005246 mOutputTracks.add(outputTrack);
Andy Hungc25b84a2015-01-14 19:04:10 -08005247 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005248 updateWaitTime_l();
5249 }
5250}
5251
5252void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
5253{
5254 Mutex::Autolock _l(mLock);
5255 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5256 if (mOutputTracks[i]->thread() == thread) {
5257 mOutputTracks[i]->destroy();
5258 mOutputTracks.removeAt(i);
5259 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07005260 if (thread->getOutput() == mOutput) {
5261 mOutput = NULL;
5262 }
Eric Laurent81784c32012-11-19 14:55:58 -08005263 return;
5264 }
5265 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07005266 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005267}
5268
5269// caller must hold mLock
5270void AudioFlinger::DuplicatingThread::updateWaitTime_l()
5271{
5272 mWaitTimeMs = UINT_MAX;
5273 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5274 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
5275 if (strong != 0) {
5276 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
5277 if (waitTimeMs < mWaitTimeMs) {
5278 mWaitTimeMs = waitTimeMs;
5279 }
5280 }
5281 }
5282}
5283
5284
5285bool AudioFlinger::DuplicatingThread::outputsReady(
5286 const SortedVector< sp<OutputTrack> > &outputTracks)
5287{
5288 for (size_t i = 0; i < outputTracks.size(); i++) {
5289 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
5290 if (thread == 0) {
5291 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
5292 outputTracks[i].get());
5293 return false;
5294 }
5295 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5296 // see note at standby() declaration
5297 if (playbackThread->standby() && !playbackThread->isSuspended()) {
5298 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
5299 thread.get());
5300 return false;
5301 }
5302 }
5303 return true;
5304}
5305
5306uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
5307{
5308 return (mWaitTimeMs * 1000) / 2;
5309}
5310
5311void AudioFlinger::DuplicatingThread::cacheParameters_l()
5312{
5313 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
5314 updateWaitTime_l();
5315
5316 MixerThread::cacheParameters_l();
5317}
5318
5319// ----------------------------------------------------------------------------
5320// Record
5321// ----------------------------------------------------------------------------
5322
5323AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5324 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08005325 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08005326 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07005327 audio_devices_t inDevice,
5328 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08005329#ifdef TEE_SINK
5330 , const sp<NBAIO_Sink>& teeSink
5331#endif
5332 ) :
Eric Laurent72e3f392015-05-20 14:43:50 -07005333 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005334 mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005335 // mRsmpInFrames and mRsmpInFramesP2 are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005336 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08005337#ifdef TEE_SINK
5338 , mTeeSink(teeSink)
5339#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07005340 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
5341 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005342 // mFastCapture below
5343 , mFastCaptureFutex(0)
5344 // mInputSource
5345 // mPipeSink
5346 // mPipeSource
5347 , mPipeFramesP2(0)
5348 // mPipeMemory
5349 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005350 , mFastTrackAvail(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005351{
Glenn Kastend7dca052015-03-05 16:05:54 -08005352 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
5353 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08005354
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005355 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005356
5357 // create an NBAIO source for the HAL input stream, and negotiate
5358 mInputSource = new AudioStreamInSource(input->stream);
5359 size_t numCounterOffers = 0;
5360 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
5361 ssize_t index = mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
5362 ALOG_ASSERT(index == 0);
5363
5364 // initialize fast capture depending on configuration
5365 bool initFastCapture;
5366 switch (kUseFastCapture) {
5367 case FastCapture_Never:
5368 initFastCapture = false;
5369 break;
5370 case FastCapture_Always:
5371 initFastCapture = true;
5372 break;
5373 case FastCapture_Static:
5374 uint32_t primaryOutputSampleRate;
5375 {
5376 AutoMutex _l(audioFlinger->mHardwareLock);
5377 primaryOutputSampleRate = audioFlinger->mPrimaryOutputSampleRate;
5378 }
5379 initFastCapture =
5380 // either capture sample rate is same as (a reasonable) primary output sample rate
Andy Hungdb4c0312015-05-06 08:46:52 -07005381 ((isMusicRate(primaryOutputSampleRate) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005382 (mSampleRate == primaryOutputSampleRate)) ||
5383 // or primary output sample rate is unknown, and capture sample rate is reasonable
5384 ((primaryOutputSampleRate == 0) &&
Andy Hungdb4c0312015-05-06 08:46:52 -07005385 isMusicRate(mSampleRate))) &&
Glenn Kasten9f81de32014-07-27 15:02:23 -07005386 // and the buffer size is < 12 ms
5387 (mFrameCount * 1000) / mSampleRate < 12;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005388 break;
5389 // case FastCapture_Dynamic:
5390 }
5391
5392 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07005393 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005394 NBAIO_Format format = mInputSource->format();
Glenn Kasten49d00ad2014-07-21 11:22:03 -07005395 size_t pipeFramesP2 = roundup(mSampleRate / 25); // double-buffering of 20 ms each
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005396 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
5397 void *pipeBuffer;
5398 const sp<MemoryDealer> roHeap(readOnlyHeap());
5399 sp<IMemory> pipeMemory;
5400 if ((roHeap == 0) ||
5401 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
5402 (pipeBuffer = pipeMemory->pointer()) == NULL) {
5403 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
5404 goto failed;
5405 }
5406 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
5407 memset(pipeBuffer, 0, pipeSize);
5408 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
5409 const NBAIO_Format offers[1] = {format};
5410 size_t numCounterOffers = 0;
5411 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
5412 ALOG_ASSERT(index == 0);
5413 mPipeSink = pipe;
5414 PipeReader *pipeReader = new PipeReader(*pipe);
5415 numCounterOffers = 0;
5416 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
5417 ALOG_ASSERT(index == 0);
5418 mPipeSource = pipeReader;
5419 mPipeFramesP2 = pipeFramesP2;
5420 mPipeMemory = pipeMemory;
5421
5422 // create fast capture
5423 mFastCapture = new FastCapture();
5424 FastCaptureStateQueue *sq = mFastCapture->sq();
5425#ifdef STATE_QUEUE_DUMP
5426 // FIXME
5427#endif
5428 FastCaptureState *state = sq->begin();
5429 state->mCblk = NULL;
5430 state->mInputSource = mInputSource.get();
5431 state->mInputSourceGen++;
5432 state->mPipeSink = pipe;
5433 state->mPipeSinkGen++;
5434 state->mFrameCount = mFrameCount;
5435 state->mCommand = FastCaptureState::COLD_IDLE;
5436 // already done in constructor initialization list
5437 //mFastCaptureFutex = 0;
5438 state->mColdFutexAddr = &mFastCaptureFutex;
5439 state->mColdGen++;
5440 state->mDumpState = &mFastCaptureDumpState;
5441#ifdef TEE_SINK
5442 // FIXME
5443#endif
5444 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
5445 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
5446 sq->end();
5447 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5448
5449 // start the fast capture
5450 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
5451 pid_t tid = mFastCapture->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07005452 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005453#ifdef AUDIO_WATCHDOG
5454 // FIXME
5455#endif
5456
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005457 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005458 }
5459failed: ;
5460
5461 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08005462}
5463
Eric Laurent81784c32012-11-19 14:55:58 -08005464AudioFlinger::RecordThread::~RecordThread()
5465{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005466 if (mFastCapture != 0) {
5467 FastCaptureStateQueue *sq = mFastCapture->sq();
5468 FastCaptureState *state = sq->begin();
5469 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5470 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5471 if (old == -1) {
5472 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5473 }
5474 }
5475 state->mCommand = FastCaptureState::EXIT;
5476 sq->end();
5477 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5478 mFastCapture->join();
5479 mFastCapture.clear();
5480 }
5481 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07005482 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07005483 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08005484}
5485
5486void AudioFlinger::RecordThread::onFirstRef()
5487{
Glenn Kastend7dca052015-03-05 16:05:54 -08005488 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08005489}
5490
Eric Laurent81784c32012-11-19 14:55:58 -08005491bool AudioFlinger::RecordThread::threadLoop()
5492{
Eric Laurent81784c32012-11-19 14:55:58 -08005493 nsecs_t lastWarning = 0;
5494
5495 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08005496
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005497reacquire_wakelock:
5498 sp<RecordTrack> activeTrack;
Glenn Kasten2b806402013-11-20 16:37:38 -08005499 int activeTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005500 {
5501 Mutex::Autolock _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005502 size_t size = mActiveTracks.size();
5503 activeTracksGen = mActiveTracksGen;
5504 if (size > 0) {
5505 // FIXME an arbitrary choice
5506 activeTrack = mActiveTracks[0];
5507 acquireWakeLock_l(activeTrack->uid());
5508 if (size > 1) {
5509 SortedVector<int> tmp;
5510 for (size_t i = 0; i < size; i++) {
5511 tmp.add(mActiveTracks[i]->uid());
5512 }
5513 updateWakeLockUids_l(tmp);
5514 }
5515 } else {
5516 acquireWakeLock_l(-1);
5517 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005518 }
5519
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005520 // used to request a deferred sleep, to be executed later while mutex is unlocked
5521 uint32_t sleepUs = 0;
5522
5523 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005524 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005525 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07005526
Glenn Kasten5edadd42013-08-14 16:30:49 -07005527 // sleep with mutex unlocked
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005528 if (sleepUs > 0) {
Glenn Kastene7754022014-10-31 12:11:26 -07005529 ATRACE_BEGIN("sleep");
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005530 usleep(sleepUs);
Glenn Kastene7754022014-10-31 12:11:26 -07005531 ATRACE_END();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005532 sleepUs = 0;
Glenn Kasten5edadd42013-08-14 16:30:49 -07005533 }
5534
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005535 // activeTracks accumulates a copy of a subset of mActiveTracks
5536 Vector< sp<RecordTrack> > activeTracks;
5537
Glenn Kasten735f45f2014-08-18 15:51:59 -07005538 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005539 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07005540
Glenn Kasten735f45f2014-08-18 15:51:59 -07005541 // reference to a fast track which is about to be removed
5542 sp<RecordTrack> fastTrackToRemove;
5543
Eric Laurent81784c32012-11-19 14:55:58 -08005544 { // scope for mLock
5545 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08005546
Eric Laurent021cf962014-05-13 10:18:14 -07005547 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005548
Eric Laurent000a4192014-01-29 15:17:32 -08005549 // check exitPending here because checkForNewParameters_l() and
5550 // checkForNewParameters_l() can temporarily release mLock
5551 if (exitPending()) {
5552 break;
5553 }
5554
Glenn Kasten2b806402013-11-20 16:37:38 -08005555 // if no active track(s), then standby and release wakelock
5556 size_t size = mActiveTracks.size();
5557 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07005558 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005559 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08005560 releaseWakeLock_l();
5561 ALOGV("RecordThread: loop stopping");
5562 // go to sleep
5563 mWaitWorkCV.wait(mLock);
5564 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005565 goto reacquire_wakelock;
5566 }
5567
Glenn Kasten2b806402013-11-20 16:37:38 -08005568 if (mActiveTracksGen != activeTracksGen) {
5569 activeTracksGen = mActiveTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005570 SortedVector<int> tmp;
Glenn Kasten2b806402013-11-20 16:37:38 -08005571 for (size_t i = 0; i < size; i++) {
5572 tmp.add(mActiveTracks[i]->uid());
5573 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005574 updateWakeLockUids_l(tmp);
Eric Laurent81784c32012-11-19 14:55:58 -08005575 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005576
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005577 bool doBroadcast = false;
5578 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07005579
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005580 activeTrack = mActiveTracks[i];
5581 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07005582 if (activeTrack->isFastTrack()) {
5583 ALOG_ASSERT(fastTrackToRemove == 0);
5584 fastTrackToRemove = activeTrack;
5585 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005586 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08005587 mActiveTracks.remove(activeTrack);
5588 mActiveTracksGen++;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005589 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07005590 continue;
5591 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005592
5593 TrackBase::track_state activeTrackState = activeTrack->mState;
5594 switch (activeTrackState) {
5595
5596 case TrackBase::PAUSING:
5597 mActiveTracks.remove(activeTrack);
5598 mActiveTracksGen++;
5599 doBroadcast = true;
5600 size--;
5601 continue;
5602
5603 case TrackBase::STARTING_1:
5604 sleepUs = 10000;
5605 i++;
5606 continue;
5607
5608 case TrackBase::STARTING_2:
5609 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005610 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07005611 activeTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005612 break;
5613
5614 case TrackBase::ACTIVE:
5615 break;
5616
5617 case TrackBase::IDLE:
5618 i++;
5619 continue;
5620
5621 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08005622 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07005623 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005624
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005625 activeTracks.add(activeTrack);
5626 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07005627
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005628 if (activeTrack->isFastTrack()) {
5629 ALOG_ASSERT(!mFastTrackAvail);
5630 ALOG_ASSERT(fastTrack == 0);
5631 fastTrack = activeTrack;
5632 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005633 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005634 if (doBroadcast) {
5635 mStartStopCond.broadcast();
5636 }
5637
5638 // sleep if there are no active tracks to process
5639 if (activeTracks.size() == 0) {
5640 if (sleepUs == 0) {
5641 sleepUs = kRecordThreadSleepUs;
5642 }
5643 continue;
5644 }
5645 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07005646
Eric Laurent81784c32012-11-19 14:55:58 -08005647 lockEffectChains_l(effectChains);
5648 }
5649
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005650 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07005651
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005652 size_t size = effectChains.size();
5653 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005654 // thread mutex is not locked, but effect chain is locked
5655 effectChains[i]->process_l();
5656 }
5657
Glenn Kasten735f45f2014-08-18 15:51:59 -07005658 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005659 if (mFastCapture != 0) {
5660 FastCaptureStateQueue *sq = mFastCapture->sq();
5661 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07005662 bool didModify = false;
5663 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005664 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
5665 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
5666 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5667 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5668 if (old == -1) {
5669 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5670 }
5671 }
5672 state->mCommand = FastCaptureState::READ_WRITE;
5673#if 0 // FIXME
5674 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08005675 FastThreadDumpState::kSamplingNforLowRamDevice :
5676 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005677#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07005678 didModify = true;
5679 }
5680 audio_track_cblk_t *cblkOld = state->mCblk;
5681 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
5682 if (cblkNew != cblkOld) {
5683 state->mCblk = cblkNew;
5684 // block until acked if removing a fast track
5685 if (cblkOld != NULL) {
5686 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
5687 }
5688 didModify = true;
5689 }
5690 sq->end(didModify);
5691 if (didModify) {
5692 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005693#if 0
5694 if (kUseFastCapture == FastCapture_Dynamic) {
5695 mNormalSource = mPipeSource;
5696 }
5697#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005698 }
5699 }
5700
Glenn Kasten735f45f2014-08-18 15:51:59 -07005701 // now run the fast track destructor with thread mutex unlocked
5702 fastTrackToRemove.clear();
5703
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005704 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
5705 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
5706 // slow, then this RecordThread will overrun by not calling HAL read often enough.
5707 // If destination is non-contiguous, first read past the nominal end of buffer, then
5708 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005709
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005710 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005711 ssize_t framesRead;
5712
5713 // If an NBAIO source is present, use it to read the normal capture's data
5714 if (mPipeSource != 0) {
5715 size_t framesToRead = mBufferSize / mFrameSize;
Andy Hung57446612015-04-19 23:56:46 -07005716 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005717 framesToRead, AudioBufferProvider::kInvalidPTS);
5718 if (framesRead == 0) {
5719 // since pipe is non-blocking, simulate blocking input
5720 sleepUs = (framesToRead * 1000000LL) / mSampleRate;
5721 }
5722 // otherwise use the HAL / AudioStreamIn directly
5723 } else {
5724 ssize_t bytesRead = mInput->stream->read(mInput->stream,
Andy Hung57446612015-04-19 23:56:46 -07005725 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005726 if (bytesRead < 0) {
5727 framesRead = bytesRead;
5728 } else {
5729 framesRead = bytesRead / mFrameSize;
5730 }
5731 }
5732
5733 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
5734 ALOGE("read failed: framesRead=%d", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005735 // Force input into standby so that it tries to recover at next read attempt
5736 inputStandBy();
5737 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005738 }
5739 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005740 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005741 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005742 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005743
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005744 if (mTeeSink != 0) {
Andy Hung57446612015-04-19 23:56:46 -07005745 (void) mTeeSink->write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005746 }
5747 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005748 {
5749 size_t part1 = mRsmpInFramesP2 - rear;
5750 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07005751 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005752 (framesRead - part1) * mFrameSize);
5753 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005754 }
5755 rear = mRsmpInRear += framesRead;
5756
5757 size = activeTracks.size();
5758 // loop over each active track
5759 for (size_t i = 0; i < size; i++) {
5760 activeTrack = activeTracks[i];
5761
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005762 // skip fast tracks, as those are handled directly by FastCapture
5763 if (activeTrack->isFastTrack()) {
5764 continue;
5765 }
5766
Andy Hung73c02e42015-03-29 01:13:58 -07005767 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07005768 // TODO: Update the activeTrack buffer converter in case of reconfigure.
5769
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005770 enum {
5771 OVERRUN_UNKNOWN,
5772 OVERRUN_TRUE,
5773 OVERRUN_FALSE
5774 } overrun = OVERRUN_UNKNOWN;
5775
5776 // loop over getNextBuffer to handle circular sink
5777 for (;;) {
5778
5779 activeTrack->mSink.frameCount = ~0;
5780 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
5781 size_t framesOut = activeTrack->mSink.frameCount;
5782 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
5783
Andy Hung73c02e42015-03-29 01:13:58 -07005784 // check available frames and handle overrun conditions
5785 // if the record track isn't draining fast enough.
5786 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005787 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07005788 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
5789 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005790 overrun = OVERRUN_TRUE;
5791 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005792 if (framesOut == 0 || framesIn == 0) {
5793 break;
5794 }
5795
Andy Hung6770c6f2015-04-07 13:43:36 -07005796 // Don't allow framesOut to be larger than what is possible with resampling
5797 // from framesIn.
5798 // This isn't strictly necessary but helps limit buffer resizing in
5799 // RecordBufferConverter. TODO: remove when no longer needed.
5800 framesOut = min(framesOut,
5801 destinationFramesPossible(
5802 framesIn, mSampleRate, activeTrack->mSampleRate));
Andy Hung97a893e2015-03-29 01:03:07 -07005803 // process frames from the RecordThread buffer provider to the RecordTrack buffer
5804 framesOut = activeTrack->mRecordBufferConverter->convert(
5805 activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005806
5807 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
5808 overrun = OVERRUN_FALSE;
5809 }
5810
5811 if (activeTrack->mFramesToDrop == 0) {
5812 if (framesOut > 0) {
5813 activeTrack->mSink.frameCount = framesOut;
5814 activeTrack->releaseBuffer(&activeTrack->mSink);
5815 }
5816 } else {
5817 // FIXME could do a partial drop of framesOut
5818 if (activeTrack->mFramesToDrop > 0) {
5819 activeTrack->mFramesToDrop -= framesOut;
5820 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005821 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005822 }
5823 } else {
5824 activeTrack->mFramesToDrop += framesOut;
5825 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
5826 activeTrack->mSyncStartEvent->isCancelled()) {
5827 ALOGW("Synced record %s, session %d, trigger session %d",
5828 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
5829 activeTrack->sessionId(),
5830 (activeTrack->mSyncStartEvent != 0) ?
5831 activeTrack->mSyncStartEvent->triggerSession() : 0);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005832 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005833 }
5834 }
5835 }
5836
5837 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005838 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005839 }
5840 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005841
5842 switch (overrun) {
5843 case OVERRUN_TRUE:
5844 // client isn't retrieving buffers fast enough
5845 if (!activeTrack->setOverflow()) {
5846 nsecs_t now = systemTime();
5847 // FIXME should lastWarning per track?
5848 if ((now - lastWarning) > kWarningThrottleNs) {
5849 ALOGW("RecordThread: buffer overflow");
5850 lastWarning = now;
5851 }
5852 }
5853 break;
5854 case OVERRUN_FALSE:
5855 activeTrack->clearOverflow();
5856 break;
5857 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005858 break;
5859 }
5860
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005861 }
5862
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005863unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08005864 // enable changes in effect chain
5865 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005866 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08005867 }
5868
Glenn Kasten93e471f2013-08-19 08:40:07 -07005869 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08005870
5871 {
5872 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07005873 for (size_t i = 0; i < mTracks.size(); i++) {
5874 sp<RecordTrack> track = mTracks[i];
5875 track->invalidate();
5876 }
Glenn Kasten2b806402013-11-20 16:37:38 -08005877 mActiveTracks.clear();
5878 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08005879 mStartStopCond.broadcast();
5880 }
5881
5882 releaseWakeLock();
5883
5884 ALOGV("RecordThread %p exiting", this);
5885 return false;
5886}
5887
Glenn Kasten93e471f2013-08-19 08:40:07 -07005888void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08005889{
5890 if (!mStandby) {
5891 inputStandBy();
5892 mStandby = true;
5893 }
5894}
5895
5896void AudioFlinger::RecordThread::inputStandBy()
5897{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005898 // Idle the fast capture if it's currently running
5899 if (mFastCapture != 0) {
5900 FastCaptureStateQueue *sq = mFastCapture->sq();
5901 FastCaptureState *state = sq->begin();
5902 if (!(state->mCommand & FastCaptureState::IDLE)) {
5903 state->mCommand = FastCaptureState::COLD_IDLE;
5904 state->mColdFutexAddr = &mFastCaptureFutex;
5905 state->mColdGen++;
5906 mFastCaptureFutex = 0;
5907 sq->end();
5908 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
5909 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
5910#if 0
5911 if (kUseFastCapture == FastCapture_Dynamic) {
5912 // FIXME
5913 }
5914#endif
5915#ifdef AUDIO_WATCHDOG
5916 // FIXME
5917#endif
5918 } else {
5919 sq->end(false /*didModify*/);
5920 }
5921 }
Eric Laurent81784c32012-11-19 14:55:58 -08005922 mInput->stream->common.standby(&mInput->stream->common);
5923}
5924
Glenn Kasten05997e22014-03-13 15:08:33 -07005925// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07005926sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08005927 const sp<AudioFlinger::Client>& client,
5928 uint32_t sampleRate,
5929 audio_format_t format,
5930 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08005931 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08005932 int sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07005933 size_t *notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005934 int uid,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07005935 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08005936 pid_t tid,
5937 status_t *status)
5938{
Glenn Kasten74935e42013-12-19 08:56:45 -08005939 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005940 sp<RecordTrack> track;
5941 status_t lStatus;
5942
Glenn Kasten90e58b12013-07-31 16:16:02 -07005943 // client expresses a preference for FAST, but we get the final say
5944 if (*flags & IAudioFlinger::TRACK_FAST) {
5945 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07005946 // we formerly checked for a callback handler (non-0 tid),
5947 // but that is no longer required for TRANSFER_OBTAIN mode
5948 //
Glenn Kasten74105912014-07-03 12:28:53 -07005949 // frame count is not specified, or is exactly the pipe depth
5950 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005951 // PCM data
5952 audio_is_linear_pcm(format) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005953 // native format
5954 (format == mFormat) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005955 // native channel mask
5956 (channelMask == mChannelMask) &&
5957 // native hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07005958 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005959 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005960 hasFastCapture() &&
5961 // there are sufficient fast track slots available
5962 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07005963 ) {
Glenn Kasten74105912014-07-03 12:28:53 -07005964 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%u mFrameCount=%u",
Glenn Kasten90e58b12013-07-31 16:16:02 -07005965 frameCount, mFrameCount);
5966 } else {
Glenn Kasten74105912014-07-03 12:28:53 -07005967 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%u mFrameCount=%u mPipeFramesP2=%u "
5968 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005969 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Glenn Kasten74105912014-07-03 12:28:53 -07005970 frameCount, mFrameCount, mPipeFramesP2,
5971 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
5972 hasFastCapture(), tid, mFastTrackAvail);
Glenn Kasten90e58b12013-07-31 16:16:02 -07005973 *flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kasten74105912014-07-03 12:28:53 -07005974 }
5975 }
5976
5977 // compute track buffer size in frames, and suggest the notification frame count
5978 if (*flags & IAudioFlinger::TRACK_FAST) {
5979 // fast track: frame count is exactly the pipe depth
5980 frameCount = mPipeFramesP2;
5981 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
5982 *notificationFrames = mFrameCount;
5983 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07005984 // not fast track: max notification period is resampled equivalent of one HAL buffer time
5985 // or 20 ms if there is a fast capture
5986 // TODO This could be a roundupRatio inline, and const
5987 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
5988 * sampleRate + mSampleRate - 1) / mSampleRate;
5989 // minimum number of notification periods is at least kMinNotifications,
5990 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
5991 static const size_t kMinNotifications = 3;
5992 static const uint32_t kMinMs = 30;
5993 // TODO This could be a roundupRatio inline
5994 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
5995 // TODO This could be a roundupRatio inline
5996 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
5997 maxNotificationFrames;
5998 const size_t minFrameCount = maxNotificationFrames *
5999 max(kMinNotifications, minNotificationsByMs);
6000 frameCount = max(frameCount, minFrameCount);
6001 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
6002 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07006003 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07006004 }
Glenn Kasten74935e42013-12-19 08:56:45 -08006005 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07006006
Glenn Kasten15e57982013-09-24 11:52:37 -07006007 lStatus = initCheck();
6008 if (lStatus != NO_ERROR) {
6009 ALOGE("createRecordTrack_l() audio driver not initialized");
6010 goto Exit;
6011 }
Eric Laurent81784c32012-11-19 14:55:58 -08006012
6013 { // scope for mLock
6014 Mutex::Autolock _l(mLock);
6015
6016 track = new RecordTrack(this, client, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07006017 format, channelMask, frameCount, NULL, sessionId, uid,
6018 *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08006019
Glenn Kasten03003332013-08-06 15:40:54 -07006020 lStatus = track->initCheck();
6021 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07006022 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08006023 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08006024 goto Exit;
6025 }
6026 mTracks.add(track);
6027
6028 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6029 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6030 mAudioFlinger->btNrecIsOff();
6031 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6032 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006033
6034 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
6035 pid_t callingPid = IPCThreadState::self()->getCallingPid();
6036 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
6037 // so ask activity manager to do this on our behalf
6038 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
6039 }
Eric Laurent81784c32012-11-19 14:55:58 -08006040 }
Glenn Kasten05997e22014-03-13 15:08:33 -07006041
Eric Laurent81784c32012-11-19 14:55:58 -08006042 lStatus = NO_ERROR;
6043
6044Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07006045 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08006046 return track;
6047}
6048
6049status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
6050 AudioSystem::sync_event_t event,
6051 int triggerSession)
6052{
6053 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
6054 sp<ThreadBase> strongMe = this;
6055 status_t status = NO_ERROR;
6056
6057 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006058 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006059 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006060 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08006061 triggerSession,
6062 recordTrack->sessionId(),
6063 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006064 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08006065 // Sync event can be cancelled by the trigger session if the track is not in a
6066 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006067 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006068 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006069 } else {
6070 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006071 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006072 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08006073 }
6074 }
6075
6076 {
Glenn Kasten47c20702013-08-13 15:37:35 -07006077 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08006078 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006079 if (mActiveTracks.indexOf(recordTrack) >= 0) {
6080 if (recordTrack->mState == TrackBase::PAUSING) {
6081 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006082 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006083 } else {
6084 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08006085 }
6086 return status;
6087 }
6088
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006089 // TODO consider other ways of handling this, such as changing the state to :STARTING and
6090 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
6091 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006092 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08006093 mActiveTracks.add(recordTrack);
6094 mActiveTracksGen++;
Eric Laurent83b88082014-06-20 18:31:16 -07006095 status_t status = NO_ERROR;
6096 if (recordTrack->isExternalTrack()) {
6097 mLock.unlock();
Eric Laurent4dc68062014-07-28 17:26:49 -07006098 status = AudioSystem::startInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006099 mLock.lock();
6100 // FIXME should verify that recordTrack is still in mActiveTracks
6101 if (status != NO_ERROR) {
6102 mActiveTracks.remove(recordTrack);
6103 mActiveTracksGen++;
6104 recordTrack->clearSyncStartEvent();
6105 ALOGV("RecordThread::start error %d", status);
6106 return status;
6107 }
Eric Laurent81784c32012-11-19 14:55:58 -08006108 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006109 // Catch up with current buffer indices if thread is already running.
6110 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
6111 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
6112 // see previously buffered data before it called start(), but with greater risk of overrun.
6113
Andy Hung73c02e42015-03-29 01:13:58 -07006114 recordTrack->mResamplerBufferProvider->reset();
Andy Hung97a893e2015-03-29 01:03:07 -07006115 // clear any converter state as new data will be discontinuous
6116 recordTrack->mRecordBufferConverter->reset();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006117 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08006118 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08006119 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08006120 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006121 ALOGV("Record failed to start");
6122 status = BAD_VALUE;
6123 goto startError;
6124 }
Eric Laurent81784c32012-11-19 14:55:58 -08006125 return status;
6126 }
Glenn Kasten7c027242012-12-26 14:43:16 -08006127
Eric Laurent81784c32012-11-19 14:55:58 -08006128startError:
Eric Laurent83b88082014-06-20 18:31:16 -07006129 if (recordTrack->isExternalTrack()) {
Eric Laurent4dc68062014-07-28 17:26:49 -07006130 AudioSystem::stopInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006131 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006132 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006133 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08006134 return status;
6135}
6136
Eric Laurent81784c32012-11-19 14:55:58 -08006137void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6138{
6139 sp<SyncEvent> strongEvent = event.promote();
6140
6141 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08006142 sp<RefBase> ptr = strongEvent->cookie().promote();
6143 if (ptr != 0) {
6144 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
6145 recordTrack->handleSyncStartEvent(strongEvent);
6146 }
Eric Laurent81784c32012-11-19 14:55:58 -08006147 }
6148}
6149
Glenn Kastena8356f62013-07-25 14:37:52 -07006150bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08006151 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07006152 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006153 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08006154 return false;
6155 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006156 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08006157 recordTrack->mState = TrackBase::PAUSING;
6158 // do not wait for mStartStopCond if exiting
6159 if (exitPending()) {
6160 return true;
6161 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006162 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08006163 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006164 // if we have been restarted, recordTrack is in mActiveTracks here
6165 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006166 ALOGV("Record stopped OK");
6167 return true;
6168 }
6169 return false;
6170}
6171
Glenn Kasten0f11b512014-01-31 16:18:54 -08006172bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08006173{
6174 return false;
6175}
6176
Glenn Kasten0f11b512014-01-31 16:18:54 -08006177status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006178{
6179#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
6180 if (!isValidSyncEvent(event)) {
6181 return BAD_VALUE;
6182 }
6183
6184 int eventSession = event->triggerSession();
6185 status_t ret = NAME_NOT_FOUND;
6186
6187 Mutex::Autolock _l(mLock);
6188
6189 for (size_t i = 0; i < mTracks.size(); i++) {
6190 sp<RecordTrack> track = mTracks[i];
6191 if (eventSession == track->sessionId()) {
6192 (void) track->setSyncEvent(event);
6193 ret = NO_ERROR;
6194 }
6195 }
6196 return ret;
6197#else
6198 return BAD_VALUE;
6199#endif
6200}
6201
6202// destroyTrack_l() must be called with ThreadBase::mLock held
6203void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6204{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006205 track->terminate();
6206 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08006207 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08006208 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006209 removeTrack_l(track);
6210 }
6211}
6212
6213void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6214{
6215 mTracks.remove(track);
6216 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006217 if (track->isFastTrack()) {
6218 ALOG_ASSERT(!mFastTrackAvail);
6219 mFastTrackAvail = true;
6220 }
Eric Laurent81784c32012-11-19 14:55:58 -08006221}
6222
6223void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6224{
6225 dumpInternals(fd, args);
6226 dumpTracks(fd, args);
6227 dumpEffectChains(fd, args);
6228}
6229
6230void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6231{
Elliott Hughes87cebad2014-05-22 10:14:43 -07006232 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08006233
Glenn Kasten44182c22015-03-05 17:12:23 -08006234 dumpBase(fd, args);
6235
6236 if (mActiveTracks.size() == 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006237 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006238 }
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006239 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006240 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08006241
6242 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
6243 const FastCaptureDumpState copy(mFastCaptureDumpState);
6244 copy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006245}
6246
Glenn Kasten0f11b512014-01-31 16:18:54 -08006247void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006248{
6249 const size_t SIZE = 256;
6250 char buffer[SIZE];
6251 String8 result;
6252
Marco Nelissenb2208842014-02-07 14:00:50 -08006253 size_t numtracks = mTracks.size();
6254 size_t numactive = mActiveTracks.size();
6255 size_t numactiveseen = 0;
Elliott Hughes87cebad2014-05-22 10:14:43 -07006256 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08006257 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006258 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08006259 RecordTrack::appendDumpHeader(result);
6260 for (size_t i = 0; i < numtracks ; ++i) {
6261 sp<RecordTrack> track = mTracks[i];
6262 if (track != 0) {
6263 bool active = mActiveTracks.indexOf(track) >= 0;
6264 if (active) {
6265 numactiveseen++;
6266 }
6267 track->dump(buffer, SIZE, active);
6268 result.append(buffer);
6269 }
Eric Laurent81784c32012-11-19 14:55:58 -08006270 }
Marco Nelissenb2208842014-02-07 14:00:50 -08006271 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006272 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006273 }
6274
Marco Nelissenb2208842014-02-07 14:00:50 -08006275 if (numactiveseen != numactive) {
6276 snprintf(buffer, SIZE, " The following tracks are in the active list but"
6277 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006278 result.append(buffer);
6279 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08006280 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08006281 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08006282 if (mTracks.indexOf(track) < 0) {
6283 track->dump(buffer, SIZE, true);
6284 result.append(buffer);
6285 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006286 }
Eric Laurent81784c32012-11-19 14:55:58 -08006287
6288 }
6289 write(fd, result.string(), result.size());
6290}
6291
Andy Hung73c02e42015-03-29 01:13:58 -07006292
6293void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
6294{
6295 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6296 RecordThread *recordThread = (RecordThread *) threadBase.get();
6297 mRsmpInFront = recordThread->mRsmpInRear;
6298 mRsmpInUnrel = 0;
6299}
6300
6301void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
6302 size_t *framesAvailable, bool *hasOverrun)
6303{
6304 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6305 RecordThread *recordThread = (RecordThread *) threadBase.get();
6306 const int32_t rear = recordThread->mRsmpInRear;
6307 const int32_t front = mRsmpInFront;
6308 const ssize_t filled = rear - front;
6309
6310 size_t framesIn;
6311 bool overrun = false;
6312 if (filled < 0) {
6313 // should not happen, but treat like a massive overrun and re-sync
6314 framesIn = 0;
6315 mRsmpInFront = rear;
6316 overrun = true;
6317 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
6318 framesIn = (size_t) filled;
6319 } else {
6320 // client is not keeping up with server, but give it latest data
6321 framesIn = recordThread->mRsmpInFrames;
6322 mRsmpInFront = /* front = */ rear - framesIn;
6323 overrun = true;
6324 }
6325 if (framesAvailable != NULL) {
6326 *framesAvailable = framesIn;
6327 }
6328 if (hasOverrun != NULL) {
6329 *hasOverrun = overrun;
6330 }
6331}
6332
Eric Laurent81784c32012-11-19 14:55:58 -08006333// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006334status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
6335 AudioBufferProvider::Buffer* buffer, int64_t pts __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006336{
Andy Hung73c02e42015-03-29 01:13:58 -07006337 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006338 if (threadBase == 0) {
6339 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006340 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006341 return NOT_ENOUGH_DATA;
6342 }
6343 RecordThread *recordThread = (RecordThread *) threadBase.get();
6344 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07006345 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07006346 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006347 // FIXME should not be P2 (don't want to increase latency)
6348 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006349 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07006350 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006351 front &= recordThread->mRsmpInFramesP2 - 1;
6352 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07006353 if (part1 > (size_t) filled) {
6354 part1 = filled;
6355 }
6356 size_t ask = buffer->frameCount;
6357 ALOG_ASSERT(ask > 0);
6358 if (part1 > ask) {
6359 part1 = ask;
6360 }
6361 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07006362 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07006363 buffer->raw = NULL;
6364 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07006365 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07006366 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08006367 }
6368
Andy Hung57446612015-04-19 23:56:46 -07006369 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07006370 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07006371 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08006372 return NO_ERROR;
6373}
6374
6375// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006376void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
6377 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006378{
Glenn Kasten85948432013-08-19 12:09:05 -07006379 size_t stepCount = buffer->frameCount;
6380 if (stepCount == 0) {
6381 return;
6382 }
Andy Hung73c02e42015-03-29 01:13:58 -07006383 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
6384 mRsmpInUnrel -= stepCount;
6385 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07006386 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006387 buffer->frameCount = 0;
6388}
6389
Andy Hung97a893e2015-03-29 01:03:07 -07006390AudioFlinger::RecordThread::RecordBufferConverter::RecordBufferConverter(
6391 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6392 uint32_t srcSampleRate,
6393 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6394 uint32_t dstSampleRate) :
6395 mSrcChannelMask(AUDIO_CHANNEL_INVALID), // updateParameters will set following vars
6396 // mSrcFormat
6397 // mSrcSampleRate
6398 // mDstChannelMask
6399 // mDstFormat
6400 // mDstSampleRate
6401 // mSrcChannelCount
6402 // mDstChannelCount
6403 // mDstFrameSize
6404 mBuf(NULL), mBufFrames(0), mBufFrameSize(0),
Andy Hungd330ee42015-04-20 13:23:41 -07006405 mResampler(NULL),
6406 mIsLegacyDownmix(false),
6407 mIsLegacyUpmix(false),
6408 mRequiresFloat(false),
6409 mInputConverterProvider(NULL)
Andy Hung97a893e2015-03-29 01:03:07 -07006410{
6411 (void)updateParameters(srcChannelMask, srcFormat, srcSampleRate,
6412 dstChannelMask, dstFormat, dstSampleRate);
6413}
6414
6415AudioFlinger::RecordThread::RecordBufferConverter::~RecordBufferConverter() {
6416 free(mBuf);
6417 delete mResampler;
Andy Hungd330ee42015-04-20 13:23:41 -07006418 delete mInputConverterProvider;
Andy Hung97a893e2015-03-29 01:03:07 -07006419}
6420
6421size_t AudioFlinger::RecordThread::RecordBufferConverter::convert(void *dst,
6422 AudioBufferProvider *provider, size_t frames)
6423{
Andy Hungd330ee42015-04-20 13:23:41 -07006424 if (mInputConverterProvider != NULL) {
6425 mInputConverterProvider->setBufferProvider(provider);
6426 provider = mInputConverterProvider;
6427 }
6428
6429 if (mResampler == NULL) {
Andy Hung97a893e2015-03-29 01:03:07 -07006430 ALOGVV("NO RESAMPLING sampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6431 mSrcSampleRate, mSrcFormat, mDstFormat);
6432
6433 AudioBufferProvider::Buffer buffer;
6434 for (size_t i = frames; i > 0; ) {
6435 buffer.frameCount = i;
6436 status_t status = provider->getNextBuffer(&buffer, 0);
6437 if (status != OK || buffer.frameCount == 0) {
6438 frames -= i; // cannot fill request.
6439 break;
6440 }
Andy Hungd330ee42015-04-20 13:23:41 -07006441 // format convert to destination buffer
6442 convertNoResampler(dst, buffer.raw, buffer.frameCount);
Andy Hung97a893e2015-03-29 01:03:07 -07006443
6444 dst = (int8_t*)dst + buffer.frameCount * mDstFrameSize;
6445 i -= buffer.frameCount;
6446 provider->releaseBuffer(&buffer);
6447 }
6448 } else {
6449 ALOGVV("RESAMPLING mSrcSampleRate:%u mDstSampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6450 mSrcSampleRate, mDstSampleRate, mSrcFormat, mDstFormat);
6451
Andy Hungd330ee42015-04-20 13:23:41 -07006452 // reallocate buffer if needed
6453 if (mBufFrameSize != 0 && mBufFrames < frames) {
6454 free(mBuf);
6455 mBufFrames = frames;
6456 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
6457 }
Andy Hung97a893e2015-03-29 01:03:07 -07006458 // resampler accumulates, but we only have one source track
Andy Hungd330ee42015-04-20 13:23:41 -07006459 memset(mBuf, 0, frames * mBufFrameSize);
6460 frames = mResampler->resample((int32_t*)mBuf, frames, provider);
6461 // format convert to destination buffer
6462 convertResampler(dst, mBuf, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006463 }
6464 return frames;
6465}
6466
6467status_t AudioFlinger::RecordThread::RecordBufferConverter::updateParameters(
6468 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6469 uint32_t srcSampleRate,
6470 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6471 uint32_t dstSampleRate)
6472{
6473 // quick evaluation if there is any change.
6474 if (mSrcFormat == srcFormat
6475 && mSrcChannelMask == srcChannelMask
6476 && mSrcSampleRate == srcSampleRate
6477 && mDstFormat == dstFormat
6478 && mDstChannelMask == dstChannelMask
6479 && mDstSampleRate == dstSampleRate) {
6480 return NO_ERROR;
6481 }
6482
Andy Hungdb4c0312015-05-06 08:46:52 -07006483 ALOGV("RecordBufferConverter updateParameters srcMask:%#x dstMask:%#x"
6484 " srcFormat:%#x dstFormat:%#x srcRate:%u dstRate:%u",
6485 srcChannelMask, dstChannelMask, srcFormat, dstFormat, srcSampleRate, dstSampleRate);
Andy Hung97a893e2015-03-29 01:03:07 -07006486 const bool valid =
6487 audio_is_input_channel(srcChannelMask)
6488 && audio_is_input_channel(dstChannelMask)
6489 && audio_is_valid_format(srcFormat) && audio_is_linear_pcm(srcFormat)
6490 && audio_is_valid_format(dstFormat) && audio_is_linear_pcm(dstFormat)
6491 && (srcSampleRate <= dstSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX)
6492 ; // no upsampling checks for now
6493 if (!valid) {
6494 return BAD_VALUE;
6495 }
6496
6497 mSrcFormat = srcFormat;
6498 mSrcChannelMask = srcChannelMask;
6499 mSrcSampleRate = srcSampleRate;
6500 mDstFormat = dstFormat;
6501 mDstChannelMask = dstChannelMask;
6502 mDstSampleRate = dstSampleRate;
6503
6504 // compute derived parameters
6505 mSrcChannelCount = audio_channel_count_from_in_mask(srcChannelMask);
6506 mDstChannelCount = audio_channel_count_from_in_mask(dstChannelMask);
6507 mDstFrameSize = mDstChannelCount * audio_bytes_per_sample(mDstFormat);
6508
Andy Hungd330ee42015-04-20 13:23:41 -07006509 // do we need to resample?
6510 delete mResampler;
6511 mResampler = NULL;
6512 if (mSrcSampleRate != mDstSampleRate) {
6513 mResampler = AudioResampler::create(AUDIO_FORMAT_PCM_FLOAT,
6514 mSrcChannelCount, mDstSampleRate);
6515 mResampler->setSampleRate(mSrcSampleRate);
6516 mResampler->setVolume(AudioMixer::UNITY_GAIN_FLOAT, AudioMixer::UNITY_GAIN_FLOAT);
6517 }
6518
6519 // are we running legacy channel conversion modes?
6520 mIsLegacyDownmix = (mSrcChannelMask == AUDIO_CHANNEL_IN_STEREO
6521 || mSrcChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK)
6522 && mDstChannelMask == AUDIO_CHANNEL_IN_MONO;
6523 mIsLegacyUpmix = mSrcChannelMask == AUDIO_CHANNEL_IN_MONO
6524 && (mDstChannelMask == AUDIO_CHANNEL_IN_STEREO
6525 || mDstChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK);
6526
6527 // do we need to process in float?
6528 mRequiresFloat = mResampler != NULL || mIsLegacyDownmix || mIsLegacyUpmix;
6529
6530 // do we need a staging buffer to convert for destination (we can still optimize this)?
6531 // we use mBufFrameSize > 0 to indicate both frame size as well as buffer necessity
6532 if (mResampler != NULL) {
6533 mBufFrameSize = max(mSrcChannelCount, FCC_2)
6534 * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
6535 } else if ((mIsLegacyUpmix || mIsLegacyDownmix) && mDstFormat != AUDIO_FORMAT_PCM_FLOAT) {
6536 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
6537 } else if (mSrcChannelMask != mDstChannelMask && mDstFormat != mSrcFormat) {
Andy Hung97a893e2015-03-29 01:03:07 -07006538 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(mSrcFormat);
6539 } else {
6540 mBufFrameSize = 0;
6541 }
6542 mBufFrames = 0; // force the buffer to be resized.
6543
Andy Hungd330ee42015-04-20 13:23:41 -07006544 // do we need an input converter buffer provider to give us float?
6545 delete mInputConverterProvider;
6546 mInputConverterProvider = NULL;
6547 if (mRequiresFloat && mSrcFormat != AUDIO_FORMAT_PCM_FLOAT) {
6548 mInputConverterProvider = new ReformatBufferProvider(
6549 audio_channel_count_from_in_mask(mSrcChannelMask),
6550 mSrcFormat,
6551 AUDIO_FORMAT_PCM_FLOAT,
6552 256 /* provider buffer frame count */);
6553 }
6554
6555 // do we need a remixer to do channel mask conversion
6556 if (!mIsLegacyDownmix && !mIsLegacyUpmix && mSrcChannelMask != mDstChannelMask) {
6557 (void) memcpy_by_index_array_initialization_from_channel_mask(
6558 mIdxAry, ARRAY_SIZE(mIdxAry), mDstChannelMask, mSrcChannelMask);
Andy Hung97a893e2015-03-29 01:03:07 -07006559 }
6560 return NO_ERROR;
6561}
6562
Andy Hungd330ee42015-04-20 13:23:41 -07006563void AudioFlinger::RecordThread::RecordBufferConverter::convertNoResampler(
6564 void *dst, const void *src, size_t frames)
Andy Hung97a893e2015-03-29 01:03:07 -07006565{
Andy Hungd330ee42015-04-20 13:23:41 -07006566 // src is native type unless there is legacy upmix or downmix, whereupon it is float.
Andy Hung97a893e2015-03-29 01:03:07 -07006567 if (mBufFrameSize != 0 && mBufFrames < frames) {
6568 free(mBuf);
6569 mBufFrames = frames;
6570 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
6571 }
Andy Hungd330ee42015-04-20 13:23:41 -07006572 // do we need to do legacy upmix and downmix?
6573 if (mIsLegacyUpmix || mIsLegacyDownmix) {
Andy Hung97a893e2015-03-29 01:03:07 -07006574 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07006575 if (mIsLegacyUpmix) {
6576 upmix_to_stereo_float_from_mono_float((float *)dstBuf,
6577 (const float *)src, frames);
6578 } else /*mIsLegacyDownmix */ {
6579 downmix_to_mono_float_from_stereo_float((float *)dstBuf,
6580 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006581 }
Andy Hungd330ee42015-04-20 13:23:41 -07006582 if (mBuf != NULL) {
6583 memcpy_by_audio_format(dst, mDstFormat, mBuf, AUDIO_FORMAT_PCM_FLOAT,
6584 frames * mDstChannelCount);
6585 }
6586 return;
6587 }
6588 // do we need to do channel mask conversion?
6589 if (mSrcChannelMask != mDstChannelMask) {
Andy Hung97a893e2015-03-29 01:03:07 -07006590 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07006591 memcpy_by_index_array(dstBuf, mDstChannelCount,
6592 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mSrcFormat), frames);
6593 if (dstBuf == dst) {
6594 return; // format is the same
6595 }
6596 }
6597 // convert to destination buffer
6598 const void *convertBuf = mBuf != NULL ? mBuf : src;
6599 memcpy_by_audio_format(dst, mDstFormat, convertBuf, mSrcFormat,
6600 frames * mDstChannelCount);
6601}
6602
6603void AudioFlinger::RecordThread::RecordBufferConverter::convertResampler(
6604 void *dst, /*not-a-const*/ void *src, size_t frames)
6605{
6606 // src buffer format is ALWAYS float when entering this routine
6607 if (mIsLegacyUpmix) {
6608 ; // mono to stereo already handled by resampler
6609 } else if (mIsLegacyDownmix
6610 || (mSrcChannelMask == mDstChannelMask && mSrcChannelCount == 1)) {
6611 // the resampler outputs stereo for mono input channel (a feature?)
6612 // must convert to mono
6613 downmix_to_mono_float_from_stereo_float((float *)src,
6614 (const float *)src, frames);
6615 } else if (mSrcChannelMask != mDstChannelMask) {
6616 // convert to mono channel again for channel mask conversion (could be skipped
6617 // with further optimization).
Andy Hung97a893e2015-03-29 01:03:07 -07006618 if (mSrcChannelCount == 1) {
Andy Hungd330ee42015-04-20 13:23:41 -07006619 downmix_to_mono_float_from_stereo_float((float *)src,
6620 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006621 }
Andy Hungd330ee42015-04-20 13:23:41 -07006622 // convert to destination format (in place, OK as float is larger than other types)
6623 if (mDstFormat != AUDIO_FORMAT_PCM_FLOAT) {
6624 memcpy_by_audio_format(src, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
6625 frames * mSrcChannelCount);
6626 }
6627 // channel convert and save to dst
6628 memcpy_by_index_array(dst, mDstChannelCount,
6629 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mDstFormat), frames);
6630 return;
Andy Hung97a893e2015-03-29 01:03:07 -07006631 }
Andy Hungd330ee42015-04-20 13:23:41 -07006632 // convert to destination format and save to dst
6633 memcpy_by_audio_format(dst, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
6634 frames * mDstChannelCount);
Andy Hung97a893e2015-03-29 01:03:07 -07006635}
6636
Eric Laurent10351942014-05-08 18:49:52 -07006637bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
6638 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006639{
6640 bool reconfig = false;
6641
Eric Laurent10351942014-05-08 18:49:52 -07006642 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006643
Eric Laurent10351942014-05-08 18:49:52 -07006644 audio_format_t reqFormat = mFormat;
6645 uint32_t samplingRate = mSampleRate;
6646 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
Andy Hungd330ee42015-04-20 13:23:41 -07006647 // possible that we are > 2 channels, use channel index mask
6648 if (channelMask == AUDIO_CHANNEL_INVALID && mChannelCount <= FCC_8) {
6649 audio_channel_mask_for_index_assignment_from_count(mChannelCount);
6650 }
Eric Laurent10351942014-05-08 18:49:52 -07006651
6652 AudioParameter param = AudioParameter(keyValuePair);
6653 int value;
6654 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
6655 // channel count change can be requested. Do we mandate the first client defines the
6656 // HAL sampling rate and channel count or do we allow changes on the fly?
6657 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6658 samplingRate = value;
6659 reconfig = true;
6660 }
6661 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07006662 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07006663 status = BAD_VALUE;
6664 } else {
6665 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08006666 reconfig = true;
6667 }
Eric Laurent10351942014-05-08 18:49:52 -07006668 }
6669 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
6670 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07006671 if (!audio_is_input_channel(mask) ||
6672 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07006673 status = BAD_VALUE;
6674 } else {
6675 channelMask = mask;
6676 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006677 }
Eric Laurent10351942014-05-08 18:49:52 -07006678 }
6679 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6680 // do not accept frame count changes if tracks are open as the track buffer
6681 // size depends on frame count and correct behavior would not be guaranteed
6682 // if frame count is changed after track creation
6683 if (mActiveTracks.size() > 0) {
6684 status = INVALID_OPERATION;
6685 } else {
6686 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006687 }
Eric Laurent10351942014-05-08 18:49:52 -07006688 }
6689 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6690 // forward device change to effects that have requested to be
6691 // aware of attached audio device.
6692 for (size_t i = 0; i < mEffectChains.size(); i++) {
6693 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08006694 }
Eric Laurent81784c32012-11-19 14:55:58 -08006695
Eric Laurent10351942014-05-08 18:49:52 -07006696 // store input device and output device but do not forward output device to audio HAL.
6697 // Note that status is ignored by the caller for output device
6698 // (see AudioFlinger::setParameters()
6699 if (audio_is_output_devices(value)) {
6700 mOutDevice = value;
6701 status = BAD_VALUE;
6702 } else {
6703 mInDevice = value;
6704 // disable AEC and NS if the device is a BT SCO headset supporting those
6705 // pre processings
6706 if (mTracks.size() > 0) {
6707 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6708 mAudioFlinger->btNrecIsOff();
6709 for (size_t i = 0; i < mTracks.size(); i++) {
6710 sp<RecordTrack> track = mTracks[i];
6711 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
6712 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08006713 }
6714 }
6715 }
Eric Laurent10351942014-05-08 18:49:52 -07006716 }
6717 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
6718 mAudioSource != (audio_source_t)value) {
6719 // forward device change to effects that have requested to be
6720 // aware of attached audio device.
6721 for (size_t i = 0; i < mEffectChains.size(); i++) {
6722 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08006723 }
Eric Laurent10351942014-05-08 18:49:52 -07006724 mAudioSource = (audio_source_t)value;
6725 }
Glenn Kastene198c362013-08-13 09:13:36 -07006726
Eric Laurent10351942014-05-08 18:49:52 -07006727 if (status == NO_ERROR) {
6728 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6729 keyValuePair.string());
6730 if (status == INVALID_OPERATION) {
6731 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006732 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6733 keyValuePair.string());
Eric Laurent10351942014-05-08 18:49:52 -07006734 }
6735 if (reconfig) {
6736 if (status == BAD_VALUE &&
Andy Hung97a893e2015-03-29 01:03:07 -07006737 audio_is_linear_pcm(mInput->stream->common.get_format(&mInput->stream->common)) &&
6738 audio_is_linear_pcm(reqFormat) &&
Eric Laurent10351942014-05-08 18:49:52 -07006739 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
Andy Hung97a893e2015-03-29 01:03:07 -07006740 <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate)) &&
Andy Hunge5412692014-05-16 11:25:07 -07006741 audio_channel_count_from_in_mask(
Andy Hungd1abb8f2015-05-05 23:42:34 -07006742 mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07006743 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006744 }
Eric Laurent10351942014-05-08 18:49:52 -07006745 if (status == NO_ERROR) {
6746 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07006747 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08006748 }
6749 }
Eric Laurent81784c32012-11-19 14:55:58 -08006750 }
Eric Laurent10351942014-05-08 18:49:52 -07006751
Eric Laurent81784c32012-11-19 14:55:58 -08006752 return reconfig;
6753}
6754
6755String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6756{
Eric Laurent81784c32012-11-19 14:55:58 -08006757 Mutex::Autolock _l(mLock);
6758 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07006759 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08006760 }
6761
Glenn Kastend8ea6992013-07-16 14:17:15 -07006762 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
6763 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08006764 free(s);
6765 return out_s8;
6766}
6767
Eric Laurent73e26b62015-04-27 16:55:58 -07006768void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event) {
6769 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
6770
6771 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08006772
6773 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07006774 case AUDIO_INPUT_OPENED:
6775 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07006776 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07006777 desc->mChannelMask = mChannelMask;
6778 desc->mSamplingRate = mSampleRate;
6779 desc->mFormat = mFormat;
6780 desc->mFrameCount = mFrameCount;
6781 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006782 break;
6783
Eric Laurent73e26b62015-04-27 16:55:58 -07006784 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08006785 default:
6786 break;
6787 }
Eric Laurent73e26b62015-04-27 16:55:58 -07006788 mAudioFlinger->ioConfigChanged(event, desc);
Eric Laurent81784c32012-11-19 14:55:58 -08006789}
6790
Glenn Kastendeca2ae2014-02-07 10:25:56 -08006791void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006792{
Eric Laurent81784c32012-11-19 14:55:58 -08006793 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
6794 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Andy Hunge5412692014-05-16 11:25:07 -07006795 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Andy Hungd330ee42015-04-20 13:23:41 -07006796 if (mChannelCount > FCC_8) {
6797 ALOGE("HAL channel count %d > %d", mChannelCount, FCC_8);
6798 }
Andy Hung463be252014-07-10 16:56:07 -07006799 mHALFormat = mInput->stream->common.get_format(&mInput->stream->common);
6800 mFormat = mHALFormat;
Andy Hungd330ee42015-04-20 13:23:41 -07006801 if (!audio_is_linear_pcm(mFormat)) {
6802 ALOGE("HAL format %#x is not linear pcm", mFormat);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07006803 }
Eric Laurent665470b2014-07-03 16:37:08 -07006804 mFrameSize = audio_stream_in_frame_size(mInput->stream);
Glenn Kasten548efc92012-11-29 08:48:51 -08006805 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
6806 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006807 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08006808 // 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 -07006809 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08006810 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006811 // A larger value should allow more old data to be read after a track calls start(),
6812 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07006813 //
6814 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08006815 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07006816 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07006817 free(mRsmpInBuffer);
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006818
6819 // TODO optimize audio capture buffer sizes ...
6820 // Here we calculate the size of the sliding buffer used as a source
6821 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
6822 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
6823 // be better to have it derived from the pipe depth in the long term.
6824 // The current value is higher than necessary. However it should not add to latency.
6825
Glenn Kasten85948432013-08-19 12:09:05 -07006826 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Andy Hung57446612015-04-19 23:56:46 -07006827 (void)posix_memalign(&mRsmpInBuffer, 32, (mRsmpInFramesP2 + mFrameCount - 1) * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006828
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006829 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
6830 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08006831}
6832
Glenn Kasten5f972c02014-01-13 09:59:31 -08006833uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08006834{
6835 Mutex::Autolock _l(mLock);
6836 if (initCheck() != NO_ERROR) {
6837 return 0;
6838 }
6839
6840 return mInput->stream->get_input_frames_lost(mInput->stream);
6841}
6842
6843uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
6844{
6845 Mutex::Autolock _l(mLock);
6846 uint32_t result = 0;
6847 if (getEffectChain_l(sessionId) != 0) {
6848 result = EFFECT_SESSION;
6849 }
6850
6851 for (size_t i = 0; i < mTracks.size(); ++i) {
6852 if (sessionId == mTracks[i]->sessionId()) {
6853 result |= TRACK_SESSION;
6854 break;
6855 }
6856 }
6857
6858 return result;
6859}
6860
6861KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
6862{
6863 KeyedVector<int, bool> ids;
6864 Mutex::Autolock _l(mLock);
6865 for (size_t j = 0; j < mTracks.size(); ++j) {
6866 sp<RecordThread::RecordTrack> track = mTracks[j];
6867 int sessionId = track->sessionId();
6868 if (ids.indexOfKey(sessionId) < 0) {
6869 ids.add(sessionId, true);
6870 }
6871 }
6872 return ids;
6873}
6874
6875AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
6876{
6877 Mutex::Autolock _l(mLock);
6878 AudioStreamIn *input = mInput;
6879 mInput = NULL;
6880 return input;
6881}
6882
6883// this method must always be called either with ThreadBase mLock held or inside the thread loop
6884audio_stream_t* AudioFlinger::RecordThread::stream() const
6885{
6886 if (mInput == NULL) {
6887 return NULL;
6888 }
6889 return &mInput->stream->common;
6890}
6891
6892status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6893{
6894 // only one chain per input thread
6895 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07006896 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08006897 return INVALID_OPERATION;
6898 }
6899 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07006900 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08006901 chain->setInBuffer(NULL);
6902 chain->setOutBuffer(NULL);
6903
6904 checkSuspendOnAddEffectChain_l(chain);
6905
Eric Laurent1b928682014-10-02 19:41:47 -07006906 // make sure enabled pre processing effects state is communicated to the HAL as we
6907 // just moved them to a new input stream.
6908 chain->syncHalEffectsState();
6909
Eric Laurent81784c32012-11-19 14:55:58 -08006910 mEffectChains.add(chain);
6911
6912 return NO_ERROR;
6913}
6914
6915size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6916{
6917 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
6918 ALOGW_IF(mEffectChains.size() != 1,
6919 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6920 chain.get(), mEffectChains.size(), this);
6921 if (mEffectChains.size() == 1) {
6922 mEffectChains.removeAt(0);
6923 }
6924 return 0;
6925}
6926
Eric Laurent1c333e22014-05-20 10:48:17 -07006927status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
6928 audio_patch_handle_t *handle)
6929{
6930 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07006931
6932 // store new device and send to effects
6933 mInDevice = patch->sources[0].ext.device.type;
Eric Laurent296fb132015-05-01 11:38:42 -07006934 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07006935 for (size_t i = 0; i < mEffectChains.size(); i++) {
6936 mEffectChains[i]->setDevice_l(mInDevice);
6937 }
6938
6939 // disable AEC and NS if the device is a BT SCO headset supporting those
6940 // pre processings
6941 if (mTracks.size() > 0) {
6942 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6943 mAudioFlinger->btNrecIsOff();
6944 for (size_t i = 0; i < mTracks.size(); i++) {
6945 sp<RecordTrack> track = mTracks[i];
6946 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
6947 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
6948 }
6949 }
6950
6951 // store new source and send to effects
6952 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
6953 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07006954 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07006955 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07006956 }
Eric Laurent054d9d32015-04-24 08:48:48 -07006957 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006958
Eric Laurent054d9d32015-04-24 08:48:48 -07006959 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006960 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
6961 status = hwDevice->create_audio_patch(hwDevice,
6962 patch->num_sources,
6963 patch->sources,
6964 patch->num_sinks,
6965 patch->sinks,
6966 handle);
6967 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07006968 char *address;
6969 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
6970 address = audio_device_address_to_parameter(
6971 patch->sources[0].ext.device.type,
6972 patch->sources[0].ext.device.address);
6973 } else {
6974 address = (char *)calloc(1, 1);
6975 }
6976 AudioParameter param = AudioParameter(String8(address));
6977 free(address);
6978 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING),
6979 (int)patch->sources[0].ext.device.type);
6980 param.addInt(String8(AUDIO_PARAMETER_STREAM_INPUT_SOURCE),
6981 (int)patch->sinks[0].ext.mix.usecase.source);
6982 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6983 param.toString().string());
6984 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07006985 }
Eric Laurent054d9d32015-04-24 08:48:48 -07006986
Eric Laurent296fb132015-05-01 11:38:42 -07006987 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
6988
Eric Laurent1c333e22014-05-20 10:48:17 -07006989 return status;
6990}
6991
6992status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
6993{
6994 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07006995
6996 mInDevice = AUDIO_DEVICE_NONE;
6997
Eric Laurent1c333e22014-05-20 10:48:17 -07006998 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
6999 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
7000 status = hwDevice->release_audio_patch(hwDevice, handle);
7001 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007002 AudioParameter param;
7003 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
7004 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7005 param.toString().string());
Eric Laurent1c333e22014-05-20 10:48:17 -07007006 }
7007 return status;
7008}
7009
Eric Laurent83b88082014-06-20 18:31:16 -07007010void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
7011{
7012 Mutex::Autolock _l(mLock);
7013 mTracks.add(record);
7014}
7015
7016void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
7017{
7018 Mutex::Autolock _l(mLock);
7019 destroyTrack_l(record);
7020}
7021
7022void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
7023{
7024 ThreadBase::getAudioPortConfig(config);
7025 config->role = AUDIO_PORT_ROLE_SINK;
7026 config->ext.mix.hw_module = mInput->audioHwDev->handle();
7027 config->ext.mix.usecase.source = mAudioSource;
7028}
Eric Laurent1c333e22014-05-20 10:48:17 -07007029
Glenn Kasten63238ef2015-03-02 15:50:29 -08007030} // namespace android