blob: 410fff57f9f89a781cb5ff13a6039ccd58529be7 [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",
Glenn Kasten84d61ca2015-05-06 18:32:13 -0700359 AUDIO_DEVICE_OUT_BLUETOOTH_SCO, "BLUETOOTH_SCO",
360 AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET, "BLUETOOTH_SCO_HEADSET",
361 AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT, "BLUETOOTH_SCO_CARKIT",
362 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, "BLUETOOTH_A2DP",
363 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES, "BLUETOOTH_A2DP_HEADPHONES",
364 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER, "BLUETOOTH_A2DP_SPEAKER",
365 AUDIO_DEVICE_OUT_AUX_DIGITAL, "AUX_DIGITAL",
366 AUDIO_DEVICE_OUT_HDMI, "HDMI",
367 AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET, "ANLG_DOCK_HEADSET",
368 AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET, "DGTL_DOCK_HEADSET",
369 AUDIO_DEVICE_OUT_USB_ACCESSORY, "USB_ACCESSORY",
370 AUDIO_DEVICE_OUT_USB_DEVICE, "USB_DEVICE",
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800371 AUDIO_DEVICE_OUT_TELEPHONY_TX, "TELEPHONY_TX",
Glenn Kasten84d61ca2015-05-06 18:32:13 -0700372 AUDIO_DEVICE_OUT_LINE, "LINE",
373 AUDIO_DEVICE_OUT_HDMI_ARC, "HDMI_ARC",
374 AUDIO_DEVICE_OUT_SPDIF, "SPDIF",
375 AUDIO_DEVICE_OUT_FM, "FM",
376 AUDIO_DEVICE_OUT_AUX_LINE, "AUX_LINE",
377 AUDIO_DEVICE_OUT_SPEAKER_SAFE, "SPEAKER_SAFE",
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800378 AUDIO_DEVICE_NONE, "NONE", // must be last
379 }, mappingsIn[] = {
Glenn Kasten84d61ca2015-05-06 18:32:13 -0700380 AUDIO_DEVICE_IN_COMMUNICATION, "COMMUNICATION",
381 AUDIO_DEVICE_IN_AMBIENT, "AMBIENT",
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800382 AUDIO_DEVICE_IN_BUILTIN_MIC, "BUILTIN_MIC",
Glenn Kasten84d61ca2015-05-06 18:32:13 -0700383 AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET, "BLUETOOTH_SCO_HEADSET",
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800384 AUDIO_DEVICE_IN_WIRED_HEADSET, "WIRED_HEADSET",
Glenn Kasten84d61ca2015-05-06 18:32:13 -0700385 AUDIO_DEVICE_IN_AUX_DIGITAL, "AUX_DIGITAL",
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800386 AUDIO_DEVICE_IN_VOICE_CALL, "VOICE_CALL",
Glenn Kasten84d61ca2015-05-06 18:32:13 -0700387 AUDIO_DEVICE_IN_TELEPHONY_RX, "TELEPHONY_RX",
388 AUDIO_DEVICE_IN_BACK_MIC, "BACK_MIC",
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800389 AUDIO_DEVICE_IN_REMOTE_SUBMIX, "REMOTE_SUBMIX",
Glenn Kasten84d61ca2015-05-06 18:32:13 -0700390 AUDIO_DEVICE_IN_ANLG_DOCK_HEADSET, "ANLG_DOCK_HEADSET",
391 AUDIO_DEVICE_IN_DGTL_DOCK_HEADSET, "DGTL_DOCK_HEADSET",
392 AUDIO_DEVICE_IN_USB_ACCESSORY, "USB_ACCESSORY",
393 AUDIO_DEVICE_IN_USB_DEVICE, "USB_DEVICE",
394 AUDIO_DEVICE_IN_FM_TUNER, "FM_TUNER",
395 AUDIO_DEVICE_IN_TV_TUNER, "TV_TUNER",
396 AUDIO_DEVICE_IN_LINE, "LINE",
397 AUDIO_DEVICE_IN_SPDIF, "SPDIF",
398 AUDIO_DEVICE_IN_BLUETOOTH_A2DP, "BLUETOOTH_A2DP",
399 AUDIO_DEVICE_IN_LOOPBACK, "LOOPBACK",
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800400 AUDIO_DEVICE_NONE, "NONE", // must be last
401 };
402 String8 result;
403 audio_devices_t allDevices = AUDIO_DEVICE_NONE;
404 const mapping *entry;
405 if (devices & AUDIO_DEVICE_BIT_IN) {
406 devices &= ~AUDIO_DEVICE_BIT_IN;
407 entry = mappingsIn;
408 } else {
409 entry = mappingsOut;
410 }
411 for ( ; entry->mDevices != AUDIO_DEVICE_NONE; entry++) {
412 allDevices = (audio_devices_t) (allDevices | entry->mDevices);
413 if (devices & entry->mDevices) {
414 if (!result.isEmpty()) {
415 result.append("|");
416 }
417 result.append(entry->mString);
418 }
419 }
420 if (devices & ~allDevices) {
421 if (!result.isEmpty()) {
422 result.append("|");
423 }
424 result.appendFormat("0x%X", devices & ~allDevices);
425 }
426 if (result.isEmpty()) {
427 result.append(entry->mString);
428 }
429 return result;
430}
431
432String8 inputFlagsToString(audio_input_flags_t flags)
433{
434 static const struct mapping {
435 audio_input_flags_t mFlag;
436 const char * mString;
437 } mappings[] = {
438 AUDIO_INPUT_FLAG_FAST, "FAST",
439 AUDIO_INPUT_FLAG_HW_HOTWORD, "HW_HOTWORD",
440 AUDIO_INPUT_FLAG_NONE, "NONE", // must be last
441 };
442 String8 result;
443 audio_input_flags_t allFlags = AUDIO_INPUT_FLAG_NONE;
444 const mapping *entry;
445 for (entry = mappings; entry->mFlag != AUDIO_INPUT_FLAG_NONE; entry++) {
446 allFlags = (audio_input_flags_t) (allFlags | entry->mFlag);
447 if (flags & entry->mFlag) {
448 if (!result.isEmpty()) {
449 result.append("|");
450 }
451 result.append(entry->mString);
452 }
453 }
454 if (flags & ~allFlags) {
455 if (!result.isEmpty()) {
456 result.append("|");
457 }
458 result.appendFormat("0x%X", flags & ~allFlags);
459 }
460 if (result.isEmpty()) {
461 result.append(entry->mString);
462 }
463 return result;
464}
465
466String8 outputFlagsToString(audio_output_flags_t flags)
Glenn Kasten97b7b752014-09-28 13:04:24 -0700467{
468 static const struct mapping {
469 audio_output_flags_t mFlag;
470 const char * mString;
471 } mappings[] = {
472 AUDIO_OUTPUT_FLAG_DIRECT, "DIRECT",
473 AUDIO_OUTPUT_FLAG_PRIMARY, "PRIMARY",
474 AUDIO_OUTPUT_FLAG_FAST, "FAST",
475 AUDIO_OUTPUT_FLAG_DEEP_BUFFER, "DEEP_BUFFER",
Glenn Kastendfb0e112015-02-18 14:33:39 -0800476 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD, "COMPRESS_OFFLOAD",
Glenn Kasten97b7b752014-09-28 13:04:24 -0700477 AUDIO_OUTPUT_FLAG_NON_BLOCKING, "NON_BLOCKING",
478 AUDIO_OUTPUT_FLAG_HW_AV_SYNC, "HW_AV_SYNC",
479 AUDIO_OUTPUT_FLAG_NONE, "NONE", // must be last
480 };
481 String8 result;
482 audio_output_flags_t allFlags = AUDIO_OUTPUT_FLAG_NONE;
483 const mapping *entry;
484 for (entry = mappings; entry->mFlag != AUDIO_OUTPUT_FLAG_NONE; entry++) {
485 allFlags = (audio_output_flags_t) (allFlags | entry->mFlag);
486 if (flags & entry->mFlag) {
487 if (!result.isEmpty()) {
488 result.append("|");
489 }
490 result.append(entry->mString);
491 }
492 }
493 if (flags & ~allFlags) {
494 if (!result.isEmpty()) {
495 result.append("|");
496 }
497 result.appendFormat("0x%X", flags & ~allFlags);
498 }
499 if (result.isEmpty()) {
500 result.append(entry->mString);
501 }
502 return result;
503}
504
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800505const char *sourceToString(audio_source_t source)
506{
507 switch (source) {
508 case AUDIO_SOURCE_DEFAULT: return "default";
509 case AUDIO_SOURCE_MIC: return "mic";
510 case AUDIO_SOURCE_VOICE_UPLINK: return "voice uplink";
511 case AUDIO_SOURCE_VOICE_DOWNLINK: return "voice downlink";
512 case AUDIO_SOURCE_VOICE_CALL: return "voice call";
513 case AUDIO_SOURCE_CAMCORDER: return "camcorder";
514 case AUDIO_SOURCE_VOICE_RECOGNITION: return "voice recognition";
515 case AUDIO_SOURCE_VOICE_COMMUNICATION: return "voice communication";
516 case AUDIO_SOURCE_REMOTE_SUBMIX: return "remote submix";
517 case AUDIO_SOURCE_FM_TUNER: return "FM tuner";
518 case AUDIO_SOURCE_HOTWORD: return "hotword";
519 default: return "unknown";
520 }
521}
522
Eric Laurent81784c32012-11-19 14:55:58 -0800523AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -0700524 audio_devices_t outDevice, audio_devices_t inDevice, type_t type, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -0800525 : Thread(false /*canCallJava*/),
526 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700527 mAudioFlinger(audioFlinger),
Glenn Kasten70949c42013-08-06 07:40:12 -0700528 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800529 // are set by PlaybackThread::readOutputParameters_l() or
530 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700531 //FIXME: mStandby should be true here. Is this some kind of hack?
Eric Laurent81784c32012-11-19 14:55:58 -0800532 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
533 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
534 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700535 mDeathRecipient(new PMDeathRecipient(this)),
536 mSystemReady(systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -0800537{
Eric Laurent296fb132015-05-01 11:38:42 -0700538 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800539}
540
541AudioFlinger::ThreadBase::~ThreadBase()
542{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700543 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700544 mConfigEvents.clear();
545
Eric Laurent81784c32012-11-19 14:55:58 -0800546 // do not lock the mutex in destructor
547 releaseWakeLock_l();
548 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800549 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800550 binder->unlinkToDeath(mDeathRecipient);
551 }
552}
553
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700554status_t AudioFlinger::ThreadBase::readyToRun()
555{
556 status_t status = initCheck();
557 if (status == NO_ERROR) {
558 ALOGI("AudioFlinger's thread %p ready to run", this);
559 } else {
560 ALOGE("No working audio driver found.");
561 }
562 return status;
563}
564
Eric Laurent81784c32012-11-19 14:55:58 -0800565void AudioFlinger::ThreadBase::exit()
566{
567 ALOGV("ThreadBase::exit");
568 // do any cleanup required for exit to succeed
569 preExit();
570 {
571 // This lock prevents the following race in thread (uniprocessor for illustration):
572 // if (!exitPending()) {
573 // // context switch from here to exit()
574 // // exit() calls requestExit(), what exitPending() observes
575 // // exit() calls signal(), which is dropped since no waiters
576 // // context switch back from exit() to here
577 // mWaitWorkCV.wait(...);
578 // // now thread is hung
579 // }
580 AutoMutex lock(mLock);
581 requestExit();
582 mWaitWorkCV.broadcast();
583 }
584 // When Thread::requestExitAndWait is made virtual and this method is renamed to
585 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
586 requestExitAndWait();
587}
588
589status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
590{
591 status_t status;
592
593 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
594 Mutex::Autolock _l(mLock);
595
Eric Laurent10351942014-05-08 18:49:52 -0700596 return sendSetParameterConfigEvent_l(keyValuePairs);
597}
598
599// sendConfigEvent_l() must be called with ThreadBase::mLock held
600// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
601status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
602{
603 status_t status = NO_ERROR;
604
Eric Laurent72e3f392015-05-20 14:43:50 -0700605 if (event->mRequiresSystemReady && !mSystemReady) {
606 event->mWaitStatus = false;
607 mPendingConfigEvents.add(event);
608 return status;
609 }
Eric Laurent10351942014-05-08 18:49:52 -0700610 mConfigEvents.add(event);
611 ALOGV("sendConfigEvent_l() num events %d event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800612 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700613 mLock.unlock();
614 {
615 Mutex::Autolock _l(event->mLock);
616 while (event->mWaitStatus) {
617 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
618 event->mStatus = TIMED_OUT;
619 event->mWaitStatus = false;
620 }
621 }
622 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800623 }
Eric Laurent10351942014-05-08 18:49:52 -0700624 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800625 return status;
626}
627
Eric Laurent73e26b62015-04-27 16:55:58 -0700628void AudioFlinger::ThreadBase::sendIoConfigEvent(audio_io_config_event event)
Eric Laurent81784c32012-11-19 14:55:58 -0800629{
630 Mutex::Autolock _l(mLock);
Eric Laurent73e26b62015-04-27 16:55:58 -0700631 sendIoConfigEvent_l(event);
Eric Laurent81784c32012-11-19 14:55:58 -0800632}
633
634// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
Eric Laurent73e26b62015-04-27 16:55:58 -0700635void AudioFlinger::ThreadBase::sendIoConfigEvent_l(audio_io_config_event event)
Eric Laurent81784c32012-11-19 14:55:58 -0800636{
Eric Laurent73e26b62015-04-27 16:55:58 -0700637 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event);
Eric Laurent10351942014-05-08 18:49:52 -0700638 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800639}
640
Eric Laurent72e3f392015-05-20 14:43:50 -0700641void AudioFlinger::ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio)
642{
643 Mutex::Autolock _l(mLock);
644 sendPrioConfigEvent_l(pid, tid, prio);
645}
646
Eric Laurent81784c32012-11-19 14:55:58 -0800647// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
648void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
649{
Eric Laurent10351942014-05-08 18:49:52 -0700650 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio);
651 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800652}
653
Eric Laurent10351942014-05-08 18:49:52 -0700654// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
655status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800656{
Eric Laurent10351942014-05-08 18:49:52 -0700657 sp<ConfigEvent> configEvent = (ConfigEvent *)new SetParameterConfigEvent(keyValuePair);
658 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700659}
660
Eric Laurent1c333e22014-05-20 10:48:17 -0700661status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
662 const struct audio_patch *patch,
663 audio_patch_handle_t *handle)
664{
665 Mutex::Autolock _l(mLock);
666 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
667 status_t status = sendConfigEvent_l(configEvent);
668 if (status == NO_ERROR) {
669 CreateAudioPatchConfigEventData *data =
670 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
671 *handle = data->mHandle;
672 }
673 return status;
674}
675
676status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
677 const audio_patch_handle_t handle)
678{
679 Mutex::Autolock _l(mLock);
680 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
681 return sendConfigEvent_l(configEvent);
682}
683
684
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700685// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700686void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700687{
Eric Laurent10351942014-05-08 18:49:52 -0700688 bool configChanged = false;
689
Eric Laurent81784c32012-11-19 14:55:58 -0800690 while (!mConfigEvents.isEmpty()) {
Eric Laurent10351942014-05-08 18:49:52 -0700691 ALOGV("processConfigEvents_l() remaining events %d", mConfigEvents.size());
692 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800693 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700694 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700695 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700696 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
697 // FIXME Need to understand why this has to be done asynchronously
698 int err = requestPriority(data->mPid, data->mTid, data->mPrio,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700699 true /*asynchronous*/);
700 if (err != 0) {
701 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700702 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700703 }
704 } break;
705 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700706 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent73e26b62015-04-27 16:55:58 -0700707 ioConfigChanged(data->mEvent);
Eric Laurent10351942014-05-08 18:49:52 -0700708 } break;
709 case CFG_EVENT_SET_PARAMETER: {
710 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
711 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
712 configChanged = true;
Glenn Kastend5418eb2013-08-14 13:11:06 -0700713 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700714 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700715 case CFG_EVENT_CREATE_AUDIO_PATCH: {
716 CreateAudioPatchConfigEventData *data =
717 (CreateAudioPatchConfigEventData *)event->mData.get();
718 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
719 } break;
720 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
721 ReleaseAudioPatchConfigEventData *data =
722 (ReleaseAudioPatchConfigEventData *)event->mData.get();
723 event->mStatus = releaseAudioPatch_l(data->mHandle);
724 } break;
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700725 default:
Eric Laurent10351942014-05-08 18:49:52 -0700726 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700727 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800728 }
Eric Laurent10351942014-05-08 18:49:52 -0700729 {
730 Mutex::Autolock _l(event->mLock);
731 if (event->mWaitStatus) {
732 event->mWaitStatus = false;
733 event->mCond.signal();
734 }
735 }
736 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
737 }
738
739 if (configChanged) {
740 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800741 }
Eric Laurent81784c32012-11-19 14:55:58 -0800742}
743
Marco Nelissenb2208842014-02-07 14:00:50 -0800744String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
745 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700746 const audio_channel_representation_t representation =
747 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700748
749 switch (representation) {
750 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
751 if (output) {
752 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
753 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
754 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
755 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
756 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
757 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
758 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
759 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
760 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
761 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
762 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
763 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
764 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
765 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
766 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
767 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
768 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
769 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
770 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
771 } else {
772 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
773 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
774 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
775 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
776 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
777 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
778 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
779 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
780 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
781 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
782 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
783 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
784 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
785 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
786 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
787 }
788 const int len = s.length();
789 if (len > 2) {
790 char *str = s.lockBuffer(len); // needed?
791 s.unlockBuffer(len - 2); // remove trailing ", "
792 }
793 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800794 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700795 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
796 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
797 return s;
798 default:
799 s.appendFormat("unknown mask, representation:%d bits:%#x",
800 representation, audio_channel_mask_get_bits(mask));
801 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800802 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800803}
804
Glenn Kasten0f11b512014-01-31 16:18:54 -0800805void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800806{
807 const size_t SIZE = 256;
808 char buffer[SIZE];
809 String8 result;
810
811 bool locked = AudioFlinger::dumpTryLock(mLock);
812 if (!locked) {
Glenn Kasten97b7b752014-09-28 13:04:24 -0700813 dprintf(fd, "thread %p may be deadlocked\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -0800814 }
815
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800816 dprintf(fd, " Thread name: %s\n", mThreadName);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700817 dprintf(fd, " I/O handle: %d\n", mId);
818 dprintf(fd, " TID: %d\n", getTid());
819 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700820 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700821 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700822 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat));
Elliott Hughes87cebad2014-05-22 10:14:43 -0700823 dprintf(fd, " HAL buffer size: %u bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700824 dprintf(fd, " Channel count: %u\n", mChannelCount);
825 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800826 channelMaskToString(mChannelMask, mType != RECORD).string());
Glenn Kasten97b7b752014-09-28 13:04:24 -0700827 dprintf(fd, " Format: 0x%x (%s)\n", mFormat, formatToString(mFormat));
828 dprintf(fd, " Frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700829 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800830 size_t numConfig = mConfigEvents.size();
831 if (numConfig) {
832 for (size_t i = 0; i < numConfig; i++) {
833 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700834 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800835 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700836 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800837 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700838 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800839 }
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800840 dprintf(fd, " Output device: %#x (%s)\n", mOutDevice, devicesToString(mOutDevice).string());
841 dprintf(fd, " Input device: %#x (%s)\n", mInDevice, devicesToString(mInDevice).string());
842 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, sourceToString(mAudioSource));
Eric Laurent81784c32012-11-19 14:55:58 -0800843
844 if (locked) {
845 mLock.unlock();
846 }
847}
848
849void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
850{
851 const size_t SIZE = 256;
852 char buffer[SIZE];
853 String8 result;
854
Marco Nelissenb2208842014-02-07 14:00:50 -0800855 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000856 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800857 write(fd, buffer, strlen(buffer));
858
Marco Nelissenb2208842014-02-07 14:00:50 -0800859 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800860 sp<EffectChain> chain = mEffectChains[i];
861 if (chain != 0) {
862 chain->dump(fd, args);
863 }
864 }
865}
866
Marco Nelissene14a5d62013-10-03 08:51:24 -0700867void AudioFlinger::ThreadBase::acquireWakeLock(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800868{
869 Mutex::Autolock _l(mLock);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700870 acquireWakeLock_l(uid);
Eric Laurent81784c32012-11-19 14:55:58 -0800871}
872
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100873String16 AudioFlinger::ThreadBase::getWakeLockTag()
874{
875 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -0800876 case MIXER:
877 return String16("AudioMix");
878 case DIRECT:
879 return String16("AudioDirectOut");
880 case DUPLICATING:
881 return String16("AudioDup");
882 case RECORD:
883 return String16("AudioIn");
884 case OFFLOAD:
885 return String16("AudioOffload");
886 default:
887 ALOG_ASSERT(false);
888 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100889 }
890}
891
Marco Nelissene14a5d62013-10-03 08:51:24 -0700892void AudioFlinger::ThreadBase::acquireWakeLock_l(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800893{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800894 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800895 if (mPowerManager != 0) {
896 sp<IBinder> binder = new BBinder();
Marco Nelissene14a5d62013-10-03 08:51:24 -0700897 status_t status;
898 if (uid >= 0) {
Eric Laurent547789d2013-10-04 11:46:55 -0700899 status = mPowerManager->acquireWakeLockWithUid(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700900 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100901 getWakeLockTag(),
Marco Nelissene14a5d62013-10-03 08:51:24 -0700902 String16("media"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700903 uid,
904 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700905 } else {
Eric Laurent547789d2013-10-04 11:46:55 -0700906 status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700907 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100908 getWakeLockTag(),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700909 String16("media"),
910 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700911 }
Eric Laurent81784c32012-11-19 14:55:58 -0800912 if (status == NO_ERROR) {
913 mWakeLockToken = binder;
914 }
Glenn Kastend7dca052015-03-05 16:05:54 -0800915 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Eric Laurent81784c32012-11-19 14:55:58 -0800916 }
917}
918
919void AudioFlinger::ThreadBase::releaseWakeLock()
920{
921 Mutex::Autolock _l(mLock);
922 releaseWakeLock_l();
923}
924
925void AudioFlinger::ThreadBase::releaseWakeLock_l()
926{
927 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800928 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -0800929 if (mPowerManager != 0) {
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700930 mPowerManager->releaseWakeLock(mWakeLockToken, 0,
931 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800932 }
933 mWakeLockToken.clear();
934 }
935}
936
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800937void AudioFlinger::ThreadBase::updateWakeLockUids(const SortedVector<int> &uids) {
938 Mutex::Autolock _l(mLock);
939 updateWakeLockUids_l(uids);
940}
941
942void AudioFlinger::ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -0700943 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800944 // use checkService() to avoid blocking if power service is not up yet
945 sp<IBinder> binder =
946 defaultServiceManager()->checkService(String16("power"));
947 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800948 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800949 } else {
950 mPowerManager = interface_cast<IPowerManager>(binder);
951 binder->linkToDeath(mDeathRecipient);
952 }
953 }
954}
955
956void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<int> &uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800957 getPowerManager_l();
958 if (mWakeLockToken == NULL) {
959 ALOGE("no wake lock to update!");
960 return;
961 }
962 if (mPowerManager != 0) {
963 sp<IBinder> binder = new BBinder();
964 status_t status;
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700965 status = mPowerManager->updateWakeLockUids(mWakeLockToken, uids.size(), uids.array(),
966 true /* FIXME force oneway contrary to .aidl */);
Glenn Kastend7dca052015-03-05 16:05:54 -0800967 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800968 }
969}
970
Eric Laurent81784c32012-11-19 14:55:58 -0800971void AudioFlinger::ThreadBase::clearPowerManager()
972{
973 Mutex::Autolock _l(mLock);
974 releaseWakeLock_l();
975 mPowerManager.clear();
976}
977
Glenn Kasten0f11b512014-01-31 16:18:54 -0800978void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800979{
980 sp<ThreadBase> thread = mThread.promote();
981 if (thread != 0) {
982 thread->clearPowerManager();
983 }
984 ALOGW("power manager service died !!!");
985}
986
987void AudioFlinger::ThreadBase::setEffectSuspended(
988 const effect_uuid_t *type, bool suspend, int sessionId)
989{
990 Mutex::Autolock _l(mLock);
991 setEffectSuspended_l(type, suspend, sessionId);
992}
993
994void AudioFlinger::ThreadBase::setEffectSuspended_l(
995 const effect_uuid_t *type, bool suspend, int sessionId)
996{
997 sp<EffectChain> chain = getEffectChain_l(sessionId);
998 if (chain != 0) {
999 if (type != NULL) {
1000 chain->setEffectSuspended_l(type, suspend);
1001 } else {
1002 chain->setEffectSuspendedAll_l(suspend);
1003 }
1004 }
1005
1006 updateSuspendedSessions_l(type, suspend, sessionId);
1007}
1008
1009void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1010{
1011 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1012 if (index < 0) {
1013 return;
1014 }
1015
1016 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1017 mSuspendedSessions.valueAt(index);
1018
1019 for (size_t i = 0; i < sessionEffects.size(); i++) {
1020 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
1021 for (int j = 0; j < desc->mRefCount; j++) {
1022 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1023 chain->setEffectSuspendedAll_l(true);
1024 } else {
1025 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1026 desc->mType.timeLow);
1027 chain->setEffectSuspended_l(&desc->mType, true);
1028 }
1029 }
1030 }
1031}
1032
1033void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1034 bool suspend,
1035 int sessionId)
1036{
1037 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1038
1039 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1040
1041 if (suspend) {
1042 if (index >= 0) {
1043 sessionEffects = mSuspendedSessions.valueAt(index);
1044 } else {
1045 mSuspendedSessions.add(sessionId, sessionEffects);
1046 }
1047 } else {
1048 if (index < 0) {
1049 return;
1050 }
1051 sessionEffects = mSuspendedSessions.valueAt(index);
1052 }
1053
1054
1055 int key = EffectChain::kKeyForSuspendAll;
1056 if (type != NULL) {
1057 key = type->timeLow;
1058 }
1059 index = sessionEffects.indexOfKey(key);
1060
1061 sp<SuspendedSessionDesc> desc;
1062 if (suspend) {
1063 if (index >= 0) {
1064 desc = sessionEffects.valueAt(index);
1065 } else {
1066 desc = new SuspendedSessionDesc();
1067 if (type != NULL) {
1068 desc->mType = *type;
1069 }
1070 sessionEffects.add(key, desc);
1071 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1072 }
1073 desc->mRefCount++;
1074 } else {
1075 if (index < 0) {
1076 return;
1077 }
1078 desc = sessionEffects.valueAt(index);
1079 if (--desc->mRefCount == 0) {
1080 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1081 sessionEffects.removeItemsAt(index);
1082 if (sessionEffects.isEmpty()) {
1083 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1084 sessionId);
1085 mSuspendedSessions.removeItem(sessionId);
1086 }
1087 }
1088 }
1089 if (!sessionEffects.isEmpty()) {
1090 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1091 }
1092}
1093
1094void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1095 bool enabled,
1096 int sessionId)
1097{
1098 Mutex::Autolock _l(mLock);
1099 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1100}
1101
1102void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1103 bool enabled,
1104 int sessionId)
1105{
1106 if (mType != RECORD) {
1107 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1108 // another session. This gives the priority to well behaved effect control panels
1109 // and applications not using global effects.
1110 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1111 // global effects
1112 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
1113 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1114 }
1115 }
1116
1117 sp<EffectChain> chain = getEffectChain_l(sessionId);
1118 if (chain != 0) {
1119 chain->checkSuspendOnEffectEnabled(effect, enabled);
1120 }
1121}
1122
1123// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1124sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1125 const sp<AudioFlinger::Client>& client,
1126 const sp<IEffectClient>& effectClient,
1127 int32_t priority,
1128 int sessionId,
1129 effect_descriptor_t *desc,
1130 int *enabled,
Glenn Kasten9156ef32013-08-06 15:39:08 -07001131 status_t *status)
Eric Laurent81784c32012-11-19 14:55:58 -08001132{
1133 sp<EffectModule> effect;
1134 sp<EffectHandle> handle;
1135 status_t lStatus;
1136 sp<EffectChain> chain;
1137 bool chainCreated = false;
1138 bool effectCreated = false;
1139 bool effectRegistered = false;
1140
1141 lStatus = initCheck();
1142 if (lStatus != NO_ERROR) {
1143 ALOGW("createEffect_l() Audio driver not initialized.");
1144 goto Exit;
1145 }
1146
Andy Hung98ef9782014-03-04 14:46:50 -08001147 // Reject any effect on Direct output threads for now, since the format of
1148 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1149 if (mType == DIRECT) {
1150 ALOGW("createEffect_l() Cannot add effect %s on Direct output type thread %s",
Glenn Kastend7dca052015-03-05 16:05:54 -08001151 desc->name, mThreadName);
Andy Hung98ef9782014-03-04 14:46:50 -08001152 lStatus = BAD_VALUE;
1153 goto Exit;
1154 }
1155
Andy Hung389cfdb2014-08-07 17:49:53 -07001156 // Reject any effect on mixer or duplicating multichannel sinks.
Andy Hung9a592762014-07-21 21:56:01 -07001157 // TODO: fix both format and multichannel issues with effects.
Andy Hung389cfdb2014-08-07 17:49:53 -07001158 if ((mType == MIXER || mType == DUPLICATING) && mChannelCount != FCC_2) {
1159 ALOGW("createEffect_l() Cannot add effect %s for multichannel(%d) %s threads",
1160 desc->name, mChannelCount, mType == MIXER ? "MIXER" : "DUPLICATING");
Andy Hung9a592762014-07-21 21:56:01 -07001161 lStatus = BAD_VALUE;
1162 goto Exit;
1163 }
1164
Eric Laurent5baf2af2013-09-12 17:37:00 -07001165 // Allow global effects only on offloaded and mixer threads
1166 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1167 switch (mType) {
1168 case MIXER:
1169 case OFFLOAD:
1170 break;
1171 case DIRECT:
1172 case DUPLICATING:
1173 case RECORD:
1174 default:
Glenn Kastend7dca052015-03-05 16:05:54 -08001175 ALOGW("createEffect_l() Cannot add global effect %s on thread %s",
1176 desc->name, mThreadName);
Eric Laurent5baf2af2013-09-12 17:37:00 -07001177 lStatus = BAD_VALUE;
1178 goto Exit;
1179 }
Eric Laurent81784c32012-11-19 14:55:58 -08001180 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07001181
Eric Laurent81784c32012-11-19 14:55:58 -08001182 // Only Pre processor effects are allowed on input threads and only on input threads
1183 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
1184 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
1185 desc->name, desc->flags, mType);
1186 lStatus = BAD_VALUE;
1187 goto Exit;
1188 }
1189
1190 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1191
1192 { // scope for mLock
1193 Mutex::Autolock _l(mLock);
1194
1195 // check for existing effect chain with the requested audio session
1196 chain = getEffectChain_l(sessionId);
1197 if (chain == 0) {
1198 // create a new chain for this session
1199 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1200 chain = new EffectChain(this, sessionId);
1201 addEffectChain_l(chain);
1202 chain->setStrategy(getStrategyForSession_l(sessionId));
1203 chainCreated = true;
1204 } else {
1205 effect = chain->getEffectFromDesc_l(desc);
1206 }
1207
1208 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1209
1210 if (effect == 0) {
1211 int id = mAudioFlinger->nextUniqueId();
1212 // Check CPU and memory usage
1213 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
1214 if (lStatus != NO_ERROR) {
1215 goto Exit;
1216 }
1217 effectRegistered = true;
1218 // create a new effect module if none present in the chain
1219 effect = new EffectModule(this, chain, desc, id, sessionId);
1220 lStatus = effect->status();
1221 if (lStatus != NO_ERROR) {
1222 goto Exit;
1223 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07001224 effect->setOffloaded(mType == OFFLOAD, mId);
1225
Eric Laurent81784c32012-11-19 14:55:58 -08001226 lStatus = chain->addEffect_l(effect);
1227 if (lStatus != NO_ERROR) {
1228 goto Exit;
1229 }
1230 effectCreated = true;
1231
1232 effect->setDevice(mOutDevice);
1233 effect->setDevice(mInDevice);
1234 effect->setMode(mAudioFlinger->getMode());
1235 effect->setAudioSource(mAudioSource);
1236 }
1237 // create effect handle and connect it to effect module
1238 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001239 lStatus = handle->initCheck();
1240 if (lStatus == OK) {
1241 lStatus = effect->addHandle(handle.get());
1242 }
Eric Laurent81784c32012-11-19 14:55:58 -08001243 if (enabled != NULL) {
1244 *enabled = (int)effect->isEnabled();
1245 }
1246 }
1247
1248Exit:
1249 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1250 Mutex::Autolock _l(mLock);
1251 if (effectCreated) {
1252 chain->removeEffect_l(effect);
1253 }
1254 if (effectRegistered) {
1255 AudioSystem::unregisterEffect(effect->id());
1256 }
1257 if (chainCreated) {
1258 removeEffectChain_l(chain);
1259 }
1260 handle.clear();
1261 }
1262
Glenn Kasten9156ef32013-08-06 15:39:08 -07001263 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001264 return handle;
1265}
1266
1267sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
1268{
1269 Mutex::Autolock _l(mLock);
1270 return getEffect_l(sessionId, effectId);
1271}
1272
1273sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
1274{
1275 sp<EffectChain> chain = getEffectChain_l(sessionId);
1276 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1277}
1278
1279// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1280// PlaybackThread::mLock held
1281status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1282{
1283 // check for existing effect chain with the requested audio session
1284 int sessionId = effect->sessionId();
1285 sp<EffectChain> chain = getEffectChain_l(sessionId);
1286 bool chainCreated = false;
1287
Eric Laurent5baf2af2013-09-12 17:37:00 -07001288 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
1289 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
1290 this, effect->desc().name, effect->desc().flags);
1291
Eric Laurent81784c32012-11-19 14:55:58 -08001292 if (chain == 0) {
1293 // create a new chain for this session
1294 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1295 chain = new EffectChain(this, sessionId);
1296 addEffectChain_l(chain);
1297 chain->setStrategy(getStrategyForSession_l(sessionId));
1298 chainCreated = true;
1299 }
1300 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1301
1302 if (chain->getEffectFromId_l(effect->id()) != 0) {
1303 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1304 this, effect->desc().name, chain.get());
1305 return BAD_VALUE;
1306 }
1307
Eric Laurent5baf2af2013-09-12 17:37:00 -07001308 effect->setOffloaded(mType == OFFLOAD, mId);
1309
Eric Laurent81784c32012-11-19 14:55:58 -08001310 status_t status = chain->addEffect_l(effect);
1311 if (status != NO_ERROR) {
1312 if (chainCreated) {
1313 removeEffectChain_l(chain);
1314 }
1315 return status;
1316 }
1317
1318 effect->setDevice(mOutDevice);
1319 effect->setDevice(mInDevice);
1320 effect->setMode(mAudioFlinger->getMode());
1321 effect->setAudioSource(mAudioSource);
1322 return NO_ERROR;
1323}
1324
1325void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
1326
1327 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
1328 effect_descriptor_t desc = effect->desc();
1329 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1330 detachAuxEffect_l(effect->id());
1331 }
1332
1333 sp<EffectChain> chain = effect->chain().promote();
1334 if (chain != 0) {
1335 // remove effect chain if removing last effect
1336 if (chain->removeEffect_l(effect) == 0) {
1337 removeEffectChain_l(chain);
1338 }
1339 } else {
1340 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1341 }
1342}
1343
1344void AudioFlinger::ThreadBase::lockEffectChains_l(
1345 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1346{
1347 effectChains = mEffectChains;
1348 for (size_t i = 0; i < mEffectChains.size(); i++) {
1349 mEffectChains[i]->lock();
1350 }
1351}
1352
1353void AudioFlinger::ThreadBase::unlockEffectChains(
1354 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1355{
1356 for (size_t i = 0; i < effectChains.size(); i++) {
1357 effectChains[i]->unlock();
1358 }
1359}
1360
1361sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
1362{
1363 Mutex::Autolock _l(mLock);
1364 return getEffectChain_l(sessionId);
1365}
1366
1367sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const
1368{
1369 size_t size = mEffectChains.size();
1370 for (size_t i = 0; i < size; i++) {
1371 if (mEffectChains[i]->sessionId() == sessionId) {
1372 return mEffectChains[i];
1373 }
1374 }
1375 return 0;
1376}
1377
1378void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1379{
1380 Mutex::Autolock _l(mLock);
1381 size_t size = mEffectChains.size();
1382 for (size_t i = 0; i < size; i++) {
1383 mEffectChains[i]->setMode_l(mode);
1384 }
1385}
1386
Eric Laurent83b88082014-06-20 18:31:16 -07001387void AudioFlinger::ThreadBase::getAudioPortConfig(struct audio_port_config *config)
1388{
1389 config->type = AUDIO_PORT_TYPE_MIX;
1390 config->ext.mix.handle = mId;
1391 config->sample_rate = mSampleRate;
1392 config->format = mFormat;
1393 config->channel_mask = mChannelMask;
1394 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1395 AUDIO_PORT_CONFIG_FORMAT;
1396}
1397
Eric Laurent72e3f392015-05-20 14:43:50 -07001398void AudioFlinger::ThreadBase::systemReady()
1399{
1400 Mutex::Autolock _l(mLock);
1401 if (mSystemReady) {
1402 return;
1403 }
1404 mSystemReady = true;
1405
1406 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1407 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1408 }
1409 mPendingConfigEvents.clear();
1410}
1411
Eric Laurent83b88082014-06-20 18:31:16 -07001412
Eric Laurent81784c32012-11-19 14:55:58 -08001413// ----------------------------------------------------------------------------
1414// Playback
1415// ----------------------------------------------------------------------------
1416
1417AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1418 AudioStreamOut* output,
1419 audio_io_handle_t id,
1420 audio_devices_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07001421 type_t type,
1422 bool systemReady)
1423 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type, systemReady),
Andy Hung2098f272014-02-27 14:00:06 -08001424 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001425 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001426 mMixerBuffer(NULL),
1427 mMixerBufferSize(0),
1428 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1429 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001430 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001431 mEffectBuffer(NULL),
1432 mEffectBufferSize(0),
1433 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1434 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001435 mSuspended(0), mBytesWritten(0),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001436 mActiveTracksGeneration(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001437 // mStreamTypes[] initialized in constructor body
1438 mOutput(output),
1439 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
1440 mMixerStatus(MIXER_IDLE),
1441 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001442 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001443 mBytesRemaining(0),
1444 mCurrentWriteLength(0),
1445 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001446 mWriteAckSequence(0),
1447 mDrainSequence(0),
Eric Laurentede6c3b2013-09-19 14:37:46 -07001448 mSignalPending(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001449 mScreenState(AudioFlinger::mScreenState),
1450 // index 0 is reserved for normal mixer's submix
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001451 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1),
Eric Laurentd1f69b02014-12-15 14:33:13 -08001452 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001453 // mLatchD, mLatchQ,
1454 mLatchDValid(false), mLatchQValid(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001455{
Glenn Kastend7dca052015-03-05 16:05:54 -08001456 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1457 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001458
1459 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1460 // it would be safer to explicitly pass initial masterVolume/masterMute as
1461 // parameter.
1462 //
1463 // If the HAL we are using has support for master volume or master mute,
1464 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1465 // and the mute set to false).
1466 mMasterVolume = audioFlinger->masterVolume_l();
1467 mMasterMute = audioFlinger->masterMute_l();
1468 if (mOutput && mOutput->audioHwDev) {
1469 if (mOutput->audioHwDev->canSetMasterVolume()) {
1470 mMasterVolume = 1.0;
1471 }
1472
1473 if (mOutput->audioHwDev->canSetMasterMute()) {
1474 mMasterMute = false;
1475 }
1476 }
1477
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001478 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001479
Eric Laurent223fd5c2014-11-11 13:43:36 -08001480 // ++ operator does not compile
Glenn Kasten66e46352014-01-16 17:44:23 -08001481 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001482 stream = (audio_stream_type_t) (stream + 1)) {
1483 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1484 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1485 }
Eric Laurent81784c32012-11-19 14:55:58 -08001486}
1487
1488AudioFlinger::PlaybackThread::~PlaybackThread()
1489{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001490 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001491 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001492 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001493 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001494}
1495
1496void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1497{
1498 dumpInternals(fd, args);
1499 dumpTracks(fd, args);
1500 dumpEffectChains(fd, args);
1501}
1502
Glenn Kasten0f11b512014-01-31 16:18:54 -08001503void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001504{
1505 const size_t SIZE = 256;
1506 char buffer[SIZE];
1507 String8 result;
1508
Marco Nelissenb2208842014-02-07 14:00:50 -08001509 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001510 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1511 const stream_type_t *st = &mStreamTypes[i];
1512 if (i > 0) {
1513 result.appendFormat(", ");
1514 }
1515 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1516 if (st->mute) {
1517 result.append("M");
1518 }
1519 }
1520 result.append("\n");
1521 write(fd, result.string(), result.length());
1522 result.clear();
1523
Eric Laurent81784c32012-11-19 14:55:58 -08001524 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1525 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001526 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001527 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001528
1529 size_t numtracks = mTracks.size();
1530 size_t numactive = mActiveTracks.size();
Elliott Hughes87cebad2014-05-22 10:14:43 -07001531 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001532 size_t numactiveseen = 0;
1533 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07001534 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08001535 Track::appendDumpHeader(result);
1536 for (size_t i = 0; i < numtracks; ++i) {
1537 sp<Track> track = mTracks[i];
1538 if (track != 0) {
1539 bool active = mActiveTracks.indexOf(track) >= 0;
1540 if (active) {
1541 numactiveseen++;
1542 }
1543 track->dump(buffer, SIZE, active);
1544 result.append(buffer);
1545 }
1546 }
1547 } else {
1548 result.append("\n");
1549 }
1550 if (numactiveseen != numactive) {
1551 // some tracks in the active list were not in the tracks list
1552 snprintf(buffer, SIZE, " The following tracks are in the active list but"
1553 " not in the track list\n");
1554 result.append(buffer);
1555 Track::appendDumpHeader(result);
1556 for (size_t i = 0; i < numactive; ++i) {
1557 sp<Track> track = mActiveTracks[i].promote();
1558 if (track != 0 && mTracks.indexOf(track) < 0) {
1559 track->dump(buffer, SIZE, true);
1560 result.append(buffer);
1561 }
1562 }
1563 }
1564
1565 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001566}
1567
1568void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1569{
Glenn Kasten97b7b752014-09-28 13:04:24 -07001570 dprintf(fd, "\nOutput thread %p type %d (%s):\n", this, type(), threadTypeToString(type()));
Glenn Kasten44182c22015-03-05 17:12:23 -08001571
1572 dumpBase(fd, args);
1573
Elliott Hughes87cebad2014-05-22 10:14:43 -07001574 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
1575 dprintf(fd, " Last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1576 dprintf(fd, " Total writes: %d\n", mNumWrites);
1577 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1578 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1579 dprintf(fd, " Suspend count: %d\n", mSuspended);
1580 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1581 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1582 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1583 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001584 AudioStreamOut *output = mOutput;
1585 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
1586 String8 flagsAsString = outputFlagsToString(flags);
1587 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n", output, flags, flagsAsString.string());
Eric Laurent81784c32012-11-19 14:55:58 -08001588}
1589
1590// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001591
1592void AudioFlinger::PlaybackThread::onFirstRef()
1593{
Glenn Kastend7dca052015-03-05 16:05:54 -08001594 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001595}
1596
1597// ThreadBase virtuals
1598void AudioFlinger::PlaybackThread::preExit()
1599{
1600 ALOGV(" preExit()");
1601 // FIXME this is using hard-coded strings but in the future, this functionality will be
1602 // converted to use audio HAL extensions required to support tunneling
1603 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1604}
1605
1606// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1607sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1608 const sp<AudioFlinger::Client>& client,
1609 audio_stream_type_t streamType,
1610 uint32_t sampleRate,
1611 audio_format_t format,
1612 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001613 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001614 const sp<IMemory>& sharedBuffer,
1615 int sessionId,
1616 IAudioFlinger::track_flags_t *flags,
1617 pid_t tid,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001618 int uid,
Eric Laurent81784c32012-11-19 14:55:58 -08001619 status_t *status)
1620{
Glenn Kasten74935e42013-12-19 08:56:45 -08001621 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001622 sp<Track> track;
1623 status_t lStatus;
1624
1625 bool isTimed = (*flags & IAudioFlinger::TRACK_TIMED) != 0;
1626
1627 // client expresses a preference for FAST, but we get the final say
1628 if (*flags & IAudioFlinger::TRACK_FAST) {
1629 if (
1630 // not timed
1631 (!isTimed) &&
1632 // either of these use cases:
1633 (
1634 // use case 1: shared buffer with any frame count
1635 (
1636 (sharedBuffer != 0)
1637 ) ||
Glenn Kasten1dfe2f92015-03-09 12:03:14 -07001638 // use case 2: frame count is default or at least as large as HAL
Eric Laurent81784c32012-11-19 14:55:58 -08001639 (
Glenn Kasten1dfe2f92015-03-09 12:03:14 -07001640 // we formerly checked for a callback handler (non-0 tid),
1641 // but that is no longer required for TRANSFER_OBTAIN mode
Eric Laurent81784c32012-11-19 14:55:58 -08001642 ((frameCount == 0) ||
Glenn Kastenb5fed682013-12-03 09:06:43 -08001643 (frameCount >= mFrameCount))
Eric Laurent81784c32012-11-19 14:55:58 -08001644 )
1645 ) &&
1646 // PCM data
1647 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07001648 // TODO: extract as a data library function that checks that a computationally
1649 // expensive downmixer is not required: isFastOutputChannelConversion()
Andy Hung9a592762014-07-21 21:56:01 -07001650 (channelMask == mChannelMask ||
Andy Hung1f439e12015-05-19 12:57:41 -07001651 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
1652 (channelMask == AUDIO_CHANNEL_OUT_MONO
1653 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001654 // hardware sample rate
1655 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001656 // normal mixer has an associated fast mixer
1657 hasFastMixer() &&
1658 // there are sufficient fast track slots available
1659 (mFastTrackAvailMask != 0)
1660 // FIXME test that MixerThread for this fast track has a capable output HAL
1661 // FIXME add a permission test also?
1662 ) {
1663 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1664 if (frameCount == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001665 // read the fast track multiplier property the first time it is needed
1666 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1667 if (ok != 0) {
1668 ALOGE("%s pthread_once failed: %d", __func__, ok);
1669 }
1670 frameCount = mFrameCount * sFastTrackMultiplier;
Eric Laurent81784c32012-11-19 14:55:58 -08001671 }
1672 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
1673 frameCount, mFrameCount);
1674 } else {
1675 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
Andy Hung6146c082014-03-18 11:56:15 -07001676 "mFrameCount=%d format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
1677 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001678 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Andy Hung6146c082014-03-18 11:56:15 -07001679 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001680 audio_is_linear_pcm(format),
1681 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
1682 *flags &= ~IAudioFlinger::TRACK_FAST;
Andy Hung0e48d252015-01-26 11:43:15 -08001683 }
1684 }
1685 // For normal PCM streaming tracks, update minimum frame count.
1686 // For compatibility with AudioTrack calculation, buffer depth is forced
1687 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1688 // This is probably too conservative, but legacy application code may depend on it.
1689 // If you change this calculation, also review the start threshold which is related.
1690 if (!(*flags & IAudioFlinger::TRACK_FAST)
1691 && audio_is_linear_pcm(format) && sharedBuffer == 0) {
Andy Hung8edb8dc2015-03-26 19:13:55 -07001692 // this must match AudioTrack.cpp calculateMinFrameCount().
1693 // TODO: Move to a common library
Eric Laurent81784c32012-11-19 14:55:58 -08001694 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1695 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1696 if (minBufCount < 2) {
1697 minBufCount = 2;
1698 }
Andy Hung8edb8dc2015-03-26 19:13:55 -07001699 // For normal mixing tracks, if speed is > 1.0f (normal), AudioTrack
1700 // or the client should compute and pass in a larger buffer request.
Andy Hung0e48d252015-01-26 11:43:15 -08001701 size_t minFrameCount =
Andy Hung8edb8dc2015-03-26 19:13:55 -07001702 minBufCount * sourceFramesNeededWithTimestretch(
1703 sampleRate, mNormalFrameCount,
1704 mSampleRate, AUDIO_TIMESTRETCH_SPEED_NORMAL /*speed*/);
Andy Hung0e48d252015-01-26 11:43:15 -08001705 if (frameCount < minFrameCount) { // including frameCount == 0
Eric Laurent81784c32012-11-19 14:55:58 -08001706 frameCount = minFrameCount;
1707 }
Eric Laurent81784c32012-11-19 14:55:58 -08001708 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001709 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001710
Glenn Kastenc3df8382014-03-13 15:05:25 -07001711 switch (mType) {
1712
1713 case DIRECT:
Glenn Kasten993fa062014-05-02 11:14:34 -07001714 if (audio_is_linear_pcm(format)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001715 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001716 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1717 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001718 sampleRate, format, channelMask, mOutput, mFormat);
1719 lStatus = BAD_VALUE;
1720 goto Exit;
1721 }
1722 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001723 break;
1724
1725 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001726 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001727 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1728 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001729 sampleRate, format, channelMask, mOutput, mFormat);
1730 lStatus = BAD_VALUE;
1731 goto Exit;
1732 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001733 break;
1734
1735 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07001736 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001737 ALOGE("createTrack_l() Bad parameter: format %#x \""
1738 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001739 format, mOutput, mFormat);
1740 lStatus = BAD_VALUE;
1741 goto Exit;
1742 }
Andy Hungcd044842014-08-07 11:04:34 -07001743 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08001744 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1745 lStatus = BAD_VALUE;
1746 goto Exit;
1747 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001748 break;
1749
Eric Laurent81784c32012-11-19 14:55:58 -08001750 }
1751
1752 lStatus = initCheck();
1753 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07001754 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08001755 goto Exit;
1756 }
1757
1758 { // scope for mLock
1759 Mutex::Autolock _l(mLock);
1760
1761 // all tracks in same audio session must share the same routing strategy otherwise
1762 // conflicts will happen when tracks are moved from one output to another by audio policy
1763 // manager
1764 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1765 for (size_t i = 0; i < mTracks.size(); ++i) {
1766 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07001767 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001768 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1769 if (sessionId == t->sessionId() && strategy != actual) {
1770 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1771 strategy, actual);
1772 lStatus = BAD_VALUE;
1773 goto Exit;
1774 }
1775 }
1776 }
1777
1778 if (!isTimed) {
1779 track = new Track(this, client, streamType, sampleRate, format,
Eric Laurent83b88082014-06-20 18:31:16 -07001780 channelMask, frameCount, NULL, sharedBuffer,
1781 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08001782 } else {
1783 track = TimedTrack::create(this, client, streamType, sampleRate, format,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001784 channelMask, frameCount, sharedBuffer, sessionId, uid);
Eric Laurent81784c32012-11-19 14:55:58 -08001785 }
Glenn Kasten03003332013-08-06 15:40:54 -07001786
1787 // new Track always returns non-NULL,
1788 // but TimedTrack::create() is a factory that could fail by returning NULL
1789 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
1790 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08001791 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001792 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08001793 goto Exit;
1794 }
1795 mTracks.add(track);
1796
1797 sp<EffectChain> chain = getEffectChain_l(sessionId);
1798 if (chain != 0) {
1799 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1800 track->setMainBuffer(chain->inBuffer());
1801 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1802 chain->incTrackCnt();
1803 }
1804
1805 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1806 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1807 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1808 // so ask activity manager to do this on our behalf
1809 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1810 }
1811 }
1812
1813 lStatus = NO_ERROR;
1814
1815Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001816 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001817 return track;
1818}
1819
1820uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1821{
1822 return latency;
1823}
1824
1825uint32_t AudioFlinger::PlaybackThread::latency() const
1826{
1827 Mutex::Autolock _l(mLock);
1828 return latency_l();
1829}
1830uint32_t AudioFlinger::PlaybackThread::latency_l() const
1831{
1832 if (initCheck() == NO_ERROR) {
1833 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
1834 } else {
1835 return 0;
1836 }
1837}
1838
1839void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1840{
1841 Mutex::Autolock _l(mLock);
1842 // Don't apply master volume in SW if our HAL can do it for us.
1843 if (mOutput && mOutput->audioHwDev &&
1844 mOutput->audioHwDev->canSetMasterVolume()) {
1845 mMasterVolume = 1.0;
1846 } else {
1847 mMasterVolume = value;
1848 }
1849}
1850
1851void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1852{
1853 Mutex::Autolock _l(mLock);
1854 // Don't apply master mute in SW if our HAL can do it for us.
1855 if (mOutput && mOutput->audioHwDev &&
1856 mOutput->audioHwDev->canSetMasterMute()) {
1857 mMasterMute = false;
1858 } else {
1859 mMasterMute = muted;
1860 }
1861}
1862
1863void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
1864{
1865 Mutex::Autolock _l(mLock);
1866 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001867 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001868}
1869
1870void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
1871{
1872 Mutex::Autolock _l(mLock);
1873 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001874 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001875}
1876
1877float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
1878{
1879 Mutex::Autolock _l(mLock);
1880 return mStreamTypes[stream].volume;
1881}
1882
1883// addTrack_l() must be called with ThreadBase::mLock held
1884status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1885{
1886 status_t status = ALREADY_EXISTS;
1887
1888 // set retry count for buffer fill
1889 track->mRetryCount = kMaxTrackStartupRetries;
1890 if (mActiveTracks.indexOf(track) < 0) {
1891 // the track is newly added, make sure it fills up all its
1892 // buffers before playing. This is to ensure the client will
1893 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07001894 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001895 TrackBase::track_state state = track->mState;
1896 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08001897 status = AudioSystem::startOutput(mId, track->streamType(),
1898 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001899 mLock.lock();
1900 // abort track was stopped/paused while we released the lock
1901 if (state != track->mState) {
1902 if (status == NO_ERROR) {
1903 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08001904 AudioSystem::stopOutput(mId, track->streamType(),
1905 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001906 mLock.lock();
1907 }
1908 return INVALID_OPERATION;
1909 }
1910 // abort if start is rejected by audio policy manager
1911 if (status != NO_ERROR) {
1912 return PERMISSION_DENIED;
1913 }
1914#ifdef ADD_BATTERY_DATA
1915 // to track the speaker usage
1916 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
1917#endif
1918 }
1919
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001920 track->mFillingUpStatus = track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent81784c32012-11-19 14:55:58 -08001921 track->mResetDone = false;
1922 track->mPresentationCompleteFrames = 0;
1923 mActiveTracks.add(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001924 mWakeLockUids.add(track->uid());
1925 mActiveTracksGeneration++;
Eric Laurentfd477972013-10-25 18:10:40 -07001926 mLatestActiveTrack = track;
Eric Laurentd0107bc2013-06-11 14:38:48 -07001927 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1928 if (chain != 0) {
1929 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
1930 track->sessionId());
1931 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08001932 }
1933
1934 status = NO_ERROR;
1935 }
1936
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08001937 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001938 return status;
1939}
1940
Eric Laurentbfb1b832013-01-07 09:53:42 -08001941bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08001942{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001943 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08001944 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001945 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
1946 track->mState = TrackBase::STOPPED;
1947 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08001948 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07001949 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001950 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08001951 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001952
1953 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08001954}
1955
1956void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1957{
1958 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
1959 mTracks.remove(track);
1960 deleteTrackName_l(track->name());
1961 // redundant as track is about to be destroyed, for dumpsys only
1962 track->mName = -1;
1963 if (track->isFastTrack()) {
1964 int index = track->mFastIndex;
1965 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
1966 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1967 mFastTrackAvailMask |= 1 << index;
1968 // redundant as track is about to be destroyed, for dumpsys only
1969 track->mFastIndex = -1;
1970 }
1971 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1972 if (chain != 0) {
1973 chain->decTrackCnt();
1974 }
1975}
1976
Eric Laurentede6c3b2013-09-19 14:37:46 -07001977void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001978{
1979 // Thread could be blocked waiting for async
1980 // so signal it to handle state changes immediately
1981 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1982 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1983 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001984 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001985}
1986
Eric Laurent81784c32012-11-19 14:55:58 -08001987String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1988{
Eric Laurent81784c32012-11-19 14:55:58 -08001989 Mutex::Autolock _l(mLock);
1990 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07001991 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08001992 }
1993
Glenn Kastend8ea6992013-07-16 14:17:15 -07001994 char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
1995 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08001996 free(s);
1997 return out_s8;
1998}
1999
Eric Laurent73e26b62015-04-27 16:55:58 -07002000void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event) {
2001 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2002 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002003
Eric Laurent73e26b62015-04-27 16:55:58 -07002004 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002005
2006 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002007 case AUDIO_OUTPUT_OPENED:
2008 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002009 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002010 desc->mChannelMask = mChannelMask;
2011 desc->mSamplingRate = mSampleRate;
2012 desc->mFormat = mFormat;
2013 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002014 // AudioFlinger::frameCount(audio_io_handle_t)
Eric Laurent73e26b62015-04-27 16:55:58 -07002015 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002016 break;
2017
Eric Laurent73e26b62015-04-27 16:55:58 -07002018 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002019 default:
2020 break;
2021 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002022 mAudioFlinger->ioConfigChanged(event, desc);
Eric Laurent81784c32012-11-19 14:55:58 -08002023}
2024
Eric Laurentbfb1b832013-01-07 09:53:42 -08002025void AudioFlinger::PlaybackThread::writeCallback()
2026{
2027 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002028 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002029}
2030
2031void AudioFlinger::PlaybackThread::drainCallback()
2032{
2033 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002034 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002035}
2036
Eric Laurent3b4529e2013-09-05 18:09:19 -07002037void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002038{
2039 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002040 // reject out of sequence requests
2041 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2042 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002043 mWaitWorkCV.signal();
2044 }
2045}
2046
Eric Laurent3b4529e2013-09-05 18:09:19 -07002047void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002048{
2049 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002050 // reject out of sequence requests
2051 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
2052 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002053 mWaitWorkCV.signal();
2054 }
2055}
2056
2057// static
2058int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
Glenn Kasten0f11b512014-01-31 16:18:54 -08002059 void *param __unused,
Eric Laurentbfb1b832013-01-07 09:53:42 -08002060 void *cookie)
2061{
2062 AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
2063 ALOGV("asyncCallback() event %d", event);
2064 switch (event) {
2065 case STREAM_CBK_EVENT_WRITE_READY:
2066 me->writeCallback();
2067 break;
2068 case STREAM_CBK_EVENT_DRAIN_READY:
2069 me->drainCallback();
2070 break;
2071 default:
2072 ALOGW("asyncCallback() unknown event %d", event);
2073 break;
2074 }
2075 return 0;
2076}
2077
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002078void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002079{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002080 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Eric Laurent81784c32012-11-19 14:55:58 -08002081 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
2082 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002083 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002084 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002085 }
Andy Hung9a592762014-07-21 21:56:01 -07002086 if ((mType == MIXER || mType == DUPLICATING)
2087 && !isValidPcmSinkChannelMask(mChannelMask)) {
2088 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2089 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002090 }
Andy Hunge5412692014-05-16 11:25:07 -07002091 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Andy Hung463be252014-07-10 16:56:07 -07002092 mHALFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
2093 mFormat = mHALFormat;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002094 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002095 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002096 }
Andy Hung6146c082014-03-18 11:56:15 -07002097 if ((mType == MIXER || mType == DUPLICATING)
2098 && !isValidPcmSinkFormat(mFormat)) {
2099 LOG_FATAL("HAL format %#x not supported for mixed output",
2100 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002101 }
Phil Burk062e67a2015-02-11 13:40:50 -08002102 mFrameSize = mOutput->getFrameSize();
Glenn Kasten70949c42013-08-06 07:40:12 -07002103 mBufferSize = mOutput->stream->common.get_buffer_size(&mOutput->stream->common);
2104 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002105 if (mFrameCount & 15) {
2106 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
2107 mFrameCount);
2108 }
2109
Eric Laurentbfb1b832013-01-07 09:53:42 -08002110 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
2111 (mOutput->stream->set_callback != NULL)) {
2112 if (mOutput->stream->set_callback(mOutput->stream,
2113 AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
2114 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002115 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002116 }
2117 }
2118
Eric Laurentd1f69b02014-12-15 14:33:13 -08002119 mHwSupportsPause = false;
2120 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
2121 if (mOutput->stream->pause != NULL) {
2122 if (mOutput->stream->resume != NULL) {
2123 mHwSupportsPause = true;
2124 } else {
2125 ALOGW("direct output implements pause but not resume");
2126 }
2127 } else if (mOutput->stream->resume != NULL) {
2128 ALOGW("direct output implements resume but not pause");
2129 }
2130 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002131 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2132 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2133 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002134
Andy Hungfbfc3952015-01-15 13:33:51 -08002135 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2136 // For best precision, we use float instead of the associated output
2137 // device format (typically PCM 16 bit).
2138
2139 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2140 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2141 mBufferSize = mFrameSize * mFrameCount;
2142
2143 // TODO: We currently use the associated output device channel mask and sample rate.
2144 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2145 // (if a valid mask) to avoid premature downmix.
2146 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2147 // instead of the output device sample rate to avoid loss of high frequency information.
2148 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2149 }
2150
Andy Hung09a50072014-02-27 14:30:47 -08002151 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002152 double multiplier = 1.0;
2153 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2154 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002155 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2156 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Eric Laurent81784c32012-11-19 14:55:58 -08002157 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2158 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2159 maxNormalFrameCount = maxNormalFrameCount & ~15;
2160 if (maxNormalFrameCount < minNormalFrameCount) {
2161 maxNormalFrameCount = minNormalFrameCount;
2162 }
2163 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2164 if (multiplier <= 1.0) {
2165 multiplier = 1.0;
2166 } else if (multiplier <= 2.0) {
2167 if (2 * mFrameCount <= maxNormalFrameCount) {
2168 multiplier = 2.0;
2169 } else {
2170 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2171 }
2172 } else {
2173 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
Andy Hung09a50072014-02-27 14:30:47 -08002174 // 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 -08002175 // track, but we sometimes have to do this to satisfy the maximum frame count
2176 // constraint)
2177 // FIXME this rounding up should not be done if no HAL SRC
2178 uint32_t truncMult = (uint32_t) multiplier;
2179 if ((truncMult & 1)) {
2180 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
2181 ++truncMult;
2182 }
2183 }
2184 multiplier = (double) truncMult;
2185 }
2186 }
2187 mNormalFrameCount = multiplier * mFrameCount;
2188 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002189 if (mType == MIXER || mType == DUPLICATING) {
2190 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2191 }
Andy Hung09a50072014-02-27 14:30:47 -08002192 ALOGI("HAL output buffer size %u frames, normal sink buffer size %u frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002193 mNormalFrameCount);
2194
Andy Hung08fb1742015-05-31 23:22:10 -07002195 // Check if we want to throttle the processing to no more than 2x normal rate
2196 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002197 mThreadThrottleTimeMs = 0;
2198 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002199 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2200
Andy Hung010a1a12014-03-13 13:57:33 -07002201 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2202 // Originally this was int16_t[] array, need to remove legacy implications.
2203 free(mSinkBuffer);
2204 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002205 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2206 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2207 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002208 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002209
Andy Hung69aed5f2014-02-25 17:24:40 -08002210 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2211 // drives the output.
2212 free(mMixerBuffer);
2213 mMixerBuffer = NULL;
2214 if (mMixerBufferEnabled) {
2215 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2216 mMixerBufferSize = mNormalFrameCount * mChannelCount
2217 * audio_bytes_per_sample(mMixerBufferFormat);
2218 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2219 }
Andy Hung98ef9782014-03-04 14:46:50 -08002220 free(mEffectBuffer);
2221 mEffectBuffer = NULL;
2222 if (mEffectBufferEnabled) {
2223 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
2224 mEffectBufferSize = mNormalFrameCount * mChannelCount
2225 * audio_bytes_per_sample(mEffectBufferFormat);
2226 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2227 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002228
Eric Laurent81784c32012-11-19 14:55:58 -08002229 // force reconfiguration of effect chains and engines to take new buffer size and audio
2230 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002231 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002232 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2233 // matter.
2234 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2235 Vector< sp<EffectChain> > effectChains = mEffectChains;
2236 for (size_t i = 0; i < effectChains.size(); i ++) {
2237 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2238 }
2239}
2240
2241
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002242status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002243{
2244 if (halFrames == NULL || dspFrames == NULL) {
2245 return BAD_VALUE;
2246 }
2247 Mutex::Autolock _l(mLock);
2248 if (initCheck() != NO_ERROR) {
2249 return INVALID_OPERATION;
2250 }
2251 size_t framesWritten = mBytesWritten / mFrameSize;
2252 *halFrames = framesWritten;
2253
2254 if (isSuspended()) {
2255 // return an estimation of rendered frames when the output is suspended
2256 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
2257 *dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0;
2258 return NO_ERROR;
2259 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002260 status_t status;
2261 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002262 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002263 *dspFrames = (size_t)frames;
2264 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002265 }
2266}
2267
2268uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
2269{
2270 Mutex::Autolock _l(mLock);
2271 uint32_t result = 0;
2272 if (getEffectChain_l(sessionId) != 0) {
2273 result = EFFECT_SESSION;
2274 }
2275
2276 for (size_t i = 0; i < mTracks.size(); ++i) {
2277 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002278 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002279 result |= TRACK_SESSION;
2280 break;
2281 }
2282 }
2283
2284 return result;
2285}
2286
2287uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
2288{
2289 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2290 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2291 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2292 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2293 }
2294 for (size_t i = 0; i < mTracks.size(); i++) {
2295 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002296 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002297 return AudioSystem::getStrategyForStream(track->streamType());
2298 }
2299 }
2300 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2301}
2302
2303
Phil Burk062e67a2015-02-11 13:40:50 -08002304AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002305{
2306 Mutex::Autolock _l(mLock);
2307 return mOutput;
2308}
2309
Phil Burk062e67a2015-02-11 13:40:50 -08002310AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002311{
2312 Mutex::Autolock _l(mLock);
2313 AudioStreamOut *output = mOutput;
2314 mOutput = NULL;
2315 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2316 // must push a NULL and wait for ack
2317 mOutputSink.clear();
2318 mPipeSink.clear();
2319 mNormalSink.clear();
2320 return output;
2321}
2322
2323// this method must always be called either with ThreadBase mLock held or inside the thread loop
2324audio_stream_t* AudioFlinger::PlaybackThread::stream() const
2325{
2326 if (mOutput == NULL) {
2327 return NULL;
2328 }
2329 return &mOutput->stream->common;
2330}
2331
2332uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2333{
2334 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2335}
2336
2337status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2338{
2339 if (!isValidSyncEvent(event)) {
2340 return BAD_VALUE;
2341 }
2342
2343 Mutex::Autolock _l(mLock);
2344
2345 for (size_t i = 0; i < mTracks.size(); ++i) {
2346 sp<Track> track = mTracks[i];
2347 if (event->triggerSession() == track->sessionId()) {
2348 (void) track->setSyncEvent(event);
2349 return NO_ERROR;
2350 }
2351 }
2352
2353 return NAME_NOT_FOUND;
2354}
2355
2356bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2357{
2358 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2359}
2360
2361void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2362 const Vector< sp<Track> >& tracksToRemove)
2363{
2364 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002365 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002366 for (size_t i = 0 ; i < count ; i++) {
2367 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002368 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002369 AudioSystem::stopOutput(mId, track->streamType(),
2370 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002371#ifdef ADD_BATTERY_DATA
2372 // to track the speaker usage
2373 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2374#endif
2375 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002376 AudioSystem::releaseOutput(mId, track->streamType(),
2377 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002378 }
Eric Laurent81784c32012-11-19 14:55:58 -08002379 }
2380 }
2381 }
Eric Laurent81784c32012-11-19 14:55:58 -08002382}
2383
2384void AudioFlinger::PlaybackThread::checkSilentMode_l()
2385{
2386 if (!mMasterMute) {
2387 char value[PROPERTY_VALUE_MAX];
2388 if (property_get("ro.audio.silent", value, "0") > 0) {
2389 char *endptr;
2390 unsigned long ul = strtoul(value, &endptr, 0);
2391 if (*endptr == '\0' && ul != 0) {
2392 ALOGD("Silence is golden");
2393 // The setprop command will not allow a property to be changed after
2394 // the first time it is set, so we don't have to worry about un-muting.
2395 setMasterMute_l(true);
2396 }
2397 }
2398 }
2399}
2400
2401// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002402ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002403{
2404 // FIXME rewrite to reduce number of system calls
2405 mLastWriteTime = systemTime();
2406 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002407 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002408 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002409
2410 // If an NBAIO sink is present, use it to write the normal mixer's submix
2411 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002412
Andy Hung010a1a12014-03-13 13:57:33 -07002413 const size_t count = mBytesRemaining / mFrameSize;
2414
Simon Wilson2d590962012-11-29 15:18:50 -08002415 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002416 // update the setpoint when AudioFlinger::mScreenState changes
2417 uint32_t screenState = AudioFlinger::mScreenState;
2418 if (screenState != mScreenState) {
2419 mScreenState = screenState;
2420 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2421 if (pipe != NULL) {
2422 pipe->setAvgFrames((mScreenState & 1) ?
2423 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2424 }
2425 }
Andy Hung010a1a12014-03-13 13:57:33 -07002426 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002427 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002428 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002429 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002430 } else {
2431 bytesWritten = framesWritten;
2432 }
Glenn Kastenefaa7ab2014-08-20 08:48:54 -07002433 mLatchDValid = false;
Glenn Kasten767094d2013-08-23 13:51:43 -07002434 status_t status = mNormalSink->getTimestamp(mLatchD.mTimestamp);
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002435 if (status == NO_ERROR) {
2436 size_t totalFramesWritten = mNormalSink->framesWritten();
2437 if (totalFramesWritten >= mLatchD.mTimestamp.mPosition) {
2438 mLatchD.mUnpresentedFrames = totalFramesWritten - mLatchD.mTimestamp.mPosition;
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002439 // mLatchD.mFramesReleased is set immediately before D is clocked into Q
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002440 mLatchDValid = true;
2441 }
2442 }
Eric Laurent81784c32012-11-19 14:55:58 -08002443 // otherwise use the HAL / AudioStreamOut directly
2444 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002445 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002446
Eric Laurentbfb1b832013-01-07 09:53:42 -08002447 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002448 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2449 mWriteAckSequence += 2;
2450 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002451 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002452 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002453 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002454 // FIXME We should have an implementation of timestamps for direct output threads.
2455 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002456 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002457 if (mUseAsyncWrite &&
2458 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2459 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002460 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002461 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002462 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002463 }
Eric Laurent81784c32012-11-19 14:55:58 -08002464 }
2465
Eric Laurent81784c32012-11-19 14:55:58 -08002466 mNumWrites++;
2467 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002468 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002469 return bytesWritten;
2470}
2471
2472void AudioFlinger::PlaybackThread::threadLoop_drain()
2473{
2474 if (mOutput->stream->drain) {
2475 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2476 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002477 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2478 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002479 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002480 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002481 }
2482 mOutput->stream->drain(mOutput->stream,
2483 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
2484 : AUDIO_DRAIN_ALL);
2485 }
2486}
2487
2488void AudioFlinger::PlaybackThread::threadLoop_exit()
2489{
Eric Laurent275e8e92014-11-30 15:14:47 -08002490 {
2491 Mutex::Autolock _l(mLock);
2492 for (size_t i = 0; i < mTracks.size(); i++) {
2493 sp<Track> track = mTracks[i];
2494 track->invalidate();
2495 }
2496 }
Eric Laurent81784c32012-11-19 14:55:58 -08002497}
2498
2499/*
2500The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002501 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002502 - mActiveSleepTimeUs from activeSleepTimeUs()
2503 - mIdleSleepTimeUs from idleSleepTimeUs()
2504 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only)
Eric Laurent81784c32012-11-19 14:55:58 -08002505 - maxPeriod from frame count and sample rate (MIXER only)
2506
2507The parameters that affect these derived values are:
2508 - frame count
2509 - frame size
2510 - sample rate
2511 - device type: A2DP or not
2512 - device latency
2513 - format: PCM or not
2514 - active sleep time
2515 - idle sleep time
2516*/
2517
2518void AudioFlinger::PlaybackThread::cacheParameters_l()
2519{
Andy Hung25c2dac2014-02-27 14:56:00 -08002520 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002521 mActiveSleepTimeUs = activeSleepTimeUs();
2522 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent81784c32012-11-19 14:55:58 -08002523}
2524
2525void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2526{
Glenn Kasten7c027242012-12-26 14:43:16 -08002527 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurent81784c32012-11-19 14:55:58 -08002528 this, streamType, mTracks.size());
2529 Mutex::Autolock _l(mLock);
2530
2531 size_t size = mTracks.size();
2532 for (size_t i = 0; i < size; i++) {
2533 sp<Track> t = mTracks[i];
2534 if (t->streamType() == streamType) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002535 t->invalidate();
Eric Laurent81784c32012-11-19 14:55:58 -08002536 }
2537 }
2538}
2539
2540status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2541{
2542 int session = chain->sessionId();
Andy Hung010a1a12014-03-13 13:57:33 -07002543 int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled
2544 ? mEffectBuffer : mSinkBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002545 bool ownsBuffer = false;
2546
2547 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
2548 if (session > 0) {
2549 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002550 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002551 if (mType != DIRECT) {
2552 size_t numSamples = mNormalFrameCount * mChannelCount;
2553 buffer = new int16_t[numSamples];
2554 memset(buffer, 0, numSamples * sizeof(int16_t));
2555 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2556 ownsBuffer = true;
2557 }
2558
2559 // Attach all tracks with same session ID to this chain.
2560 for (size_t i = 0; i < mTracks.size(); ++i) {
2561 sp<Track> track = mTracks[i];
2562 if (session == track->sessionId()) {
2563 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2564 buffer);
2565 track->setMainBuffer(buffer);
2566 chain->incTrackCnt();
2567 }
2568 }
2569
2570 // indicate all active tracks in the chain
2571 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2572 sp<Track> track = mActiveTracks[i].promote();
2573 if (track == 0) {
2574 continue;
2575 }
2576 if (session == track->sessionId()) {
2577 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2578 chain->incActiveTrackCnt();
2579 }
2580 }
2581 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002582 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08002583 chain->setInBuffer(buffer, ownsBuffer);
Andy Hung010a1a12014-03-13 13:57:33 -07002584 chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled
2585 ? mEffectBuffer : mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002586 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
2587 // chains list in order to be processed last as it contains output stage effects
2588 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2589 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
2590 // after track specific effects and before output stage
2591 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
2592 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
2593 // Effect chain for other sessions are inserted at beginning of effect
2594 // chains list to be processed before output mix effects. Relative order between other
2595 // sessions is not important
2596 size_t size = mEffectChains.size();
2597 size_t i = 0;
2598 for (i = 0; i < size; i++) {
2599 if (mEffectChains[i]->sessionId() < session) {
2600 break;
2601 }
2602 }
2603 mEffectChains.insertAt(chain, i);
2604 checkSuspendOnAddEffectChain_l(chain);
2605
2606 return NO_ERROR;
2607}
2608
2609size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2610{
2611 int session = chain->sessionId();
2612
2613 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2614
2615 for (size_t i = 0; i < mEffectChains.size(); i++) {
2616 if (chain == mEffectChains[i]) {
2617 mEffectChains.removeAt(i);
2618 // detach all active tracks from the chain
2619 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2620 sp<Track> track = mActiveTracks[i].promote();
2621 if (track == 0) {
2622 continue;
2623 }
2624 if (session == track->sessionId()) {
2625 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2626 chain.get(), session);
2627 chain->decActiveTrackCnt();
2628 }
2629 }
2630
2631 // detach all tracks with same session ID from this chain
2632 for (size_t i = 0; i < mTracks.size(); ++i) {
2633 sp<Track> track = mTracks[i];
2634 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002635 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002636 chain->decTrackCnt();
2637 }
2638 }
2639 break;
2640 }
2641 }
2642 return mEffectChains.size();
2643}
2644
2645status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2646 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2647{
2648 Mutex::Autolock _l(mLock);
2649 return attachAuxEffect_l(track, EffectId);
2650}
2651
2652status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2653 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2654{
2655 status_t status = NO_ERROR;
2656
2657 if (EffectId == 0) {
2658 track->setAuxBuffer(0, NULL);
2659 } else {
2660 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2661 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2662 if (effect != 0) {
2663 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2664 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2665 } else {
2666 status = INVALID_OPERATION;
2667 }
2668 } else {
2669 status = BAD_VALUE;
2670 }
2671 }
2672 return status;
2673}
2674
2675void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2676{
2677 for (size_t i = 0; i < mTracks.size(); ++i) {
2678 sp<Track> track = mTracks[i];
2679 if (track->auxEffectId() == effectId) {
2680 attachAuxEffect_l(track, 0);
2681 }
2682 }
2683}
2684
2685bool AudioFlinger::PlaybackThread::threadLoop()
2686{
2687 Vector< sp<Track> > tracksToRemove;
2688
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002689 mStandbyTimeNs = systemTime();
Eric Laurent81784c32012-11-19 14:55:58 -08002690
2691 // MIXER
2692 nsecs_t lastWarning = 0;
2693
2694 // DUPLICATING
2695 // FIXME could this be made local to while loop?
2696 writeFrames = 0;
2697
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002698 int lastGeneration = 0;
2699
Eric Laurent81784c32012-11-19 14:55:58 -08002700 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002701 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08002702
2703 if (mType == MIXER) {
2704 sleepTimeShift = 0;
2705 }
2706
2707 CpuStats cpuStats;
2708 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2709
2710 acquireWakeLock();
2711
Glenn Kasten9e58b552013-01-18 15:09:48 -08002712 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2713 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2714 // and then that string will be logged at the next convenient opportunity.
2715 const char *logString = NULL;
2716
Eric Laurent664539d2013-09-23 18:24:31 -07002717 checkSilentMode_l();
2718
Eric Laurent81784c32012-11-19 14:55:58 -08002719 while (!exitPending())
2720 {
2721 cpuStats.sample(myName);
2722
2723 Vector< sp<EffectChain> > effectChains;
2724
Eric Laurent81784c32012-11-19 14:55:58 -08002725 { // scope for mLock
2726
2727 Mutex::Autolock _l(mLock);
2728
Eric Laurent021cf962014-05-13 10:18:14 -07002729 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07002730
Glenn Kasten9e58b552013-01-18 15:09:48 -08002731 if (logString != NULL) {
2732 mNBLogWriter->logTimestamp();
2733 mNBLogWriter->log(logString);
2734 logString = NULL;
2735 }
2736
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002737 // Gather the framesReleased counters for all active tracks,
2738 // and latch them atomically with the timestamp.
2739 // FIXME We're using raw pointers as indices. A unique track ID would be a better index.
2740 mLatchD.mFramesReleased.clear();
2741 size_t size = mActiveTracks.size();
2742 for (size_t i = 0; i < size; i++) {
2743 sp<Track> t = mActiveTracks[i].promote();
2744 if (t != 0) {
2745 mLatchD.mFramesReleased.add(t.get(),
2746 t->mAudioTrackServerProxy->framesReleased());
2747 }
2748 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002749 if (mLatchDValid) {
2750 mLatchQ = mLatchD;
2751 mLatchDValid = false;
2752 mLatchQValid = true;
2753 }
2754
Eric Laurent81784c32012-11-19 14:55:58 -08002755 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002756 if (mSignalPending) {
2757 // A signal was raised while we were unlocked
2758 mSignalPending = false;
2759 } else if (waitingAsyncCallback_l()) {
2760 if (exitPending()) {
2761 break;
2762 }
Marco Nelissen078538c2015-05-12 09:17:57 -07002763 bool released = false;
2764 // The following works around a bug in the offload driver. Ideally we would release
2765 // the wake lock every time, but that causes the last offload buffer(s) to be
2766 // dropped while the device is on battery, so we need to hold a wake lock during
2767 // the drain phase.
2768 if (mBytesRemaining && !(mDrainSequence & 1)) {
2769 releaseWakeLock_l();
2770 released = true;
2771 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002772 mWakeLockUids.clear();
2773 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002774 ALOGV("wait async completion");
2775 mWaitWorkCV.wait(mLock);
2776 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07002777 if (released) {
2778 acquireWakeLock_l();
2779 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002780 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
2781 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002782
2783 continue;
2784 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002785 if ((!mActiveTracks.size() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08002786 isSuspended()) {
2787 // put audio hardware into standby after short delay
2788 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002789
2790 threadLoop_standby();
2791
2792 mStandby = true;
2793 }
2794
2795 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2796 // we're about to wait, flush the binder command buffer
2797 IPCThreadState::self()->flushCommands();
2798
2799 clearOutputTracks();
2800
2801 if (exitPending()) {
2802 break;
2803 }
2804
2805 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002806 mWakeLockUids.clear();
2807 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002808 // wait until we have something to do...
2809 ALOGV("%s going to sleep", myName.string());
2810 mWaitWorkCV.wait(mLock);
2811 ALOGV("%s waking up", myName.string());
2812 acquireWakeLock_l();
2813
2814 mMixerStatus = MIXER_IDLE;
2815 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2816 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002817 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002818 checkSilentMode_l();
2819
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002820 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
2821 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08002822 if (mType == MIXER) {
2823 sleepTimeShift = 0;
2824 }
2825
2826 continue;
2827 }
2828 }
Eric Laurent81784c32012-11-19 14:55:58 -08002829 // mMixerStatusIgnoringFastTracks is also updated internally
2830 mMixerStatus = prepareTracks_l(&tracksToRemove);
2831
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002832 // compare with previously applied list
2833 if (lastGeneration != mActiveTracksGeneration) {
2834 // update wakelock
2835 updateWakeLockUids_l(mWakeLockUids);
2836 lastGeneration = mActiveTracksGeneration;
2837 }
2838
Eric Laurent81784c32012-11-19 14:55:58 -08002839 // prevent any changes in effect chain list and in each effect chain
2840 // during mixing and effect process as the audio buffers could be deleted
2841 // or modified if an effect is created or deleted
2842 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002843 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08002844
Eric Laurentbfb1b832013-01-07 09:53:42 -08002845 if (mBytesRemaining == 0) {
2846 mCurrentWriteLength = 0;
2847 if (mMixerStatus == MIXER_TRACKS_READY) {
2848 // threadLoop_mix() sets mCurrentWriteLength
2849 threadLoop_mix();
2850 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
2851 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002852 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08002853 // must be written to HAL
2854 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002855 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08002856 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002857 }
2858 }
Andy Hung98ef9782014-03-04 14:46:50 -08002859 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002860 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08002861 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
2862 // or mSinkBuffer (if there are no effects).
2863 //
2864 // This is done pre-effects computation; if effects change to
2865 // support higher precision, this needs to move.
2866 //
2867 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002868 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08002869 if (mMixerBufferValid) {
2870 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
2871 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
2872
2873 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
2874 mNormalFrameCount * mChannelCount);
2875 }
2876
Eric Laurentbfb1b832013-01-07 09:53:42 -08002877 mBytesRemaining = mCurrentWriteLength;
2878 if (isSuspended()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002879 mSleepTimeUs = suspendSleepTimeUs();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002880 // simulate write to HAL when suspended
Andy Hung25c2dac2014-02-27 14:56:00 -08002881 mBytesWritten += mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002882 mBytesRemaining = 0;
2883 }
Eric Laurent81784c32012-11-19 14:55:58 -08002884
Eric Laurentbfb1b832013-01-07 09:53:42 -08002885 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002886 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002887 for (size_t i = 0; i < effectChains.size(); i ++) {
2888 effectChains[i]->process_l();
2889 }
Eric Laurent81784c32012-11-19 14:55:58 -08002890 }
2891 }
Eric Laurent59fe0102013-09-27 18:48:26 -07002892 // Process effect chains for offloaded thread even if no audio
2893 // was read from audio track: process only updates effect state
2894 // and thus does have to be synchronized with audio writes but may have
2895 // to be called while waiting for async write callback
2896 if (mType == OFFLOAD) {
2897 for (size_t i = 0; i < effectChains.size(); i ++) {
2898 effectChains[i]->process_l();
2899 }
2900 }
Eric Laurent81784c32012-11-19 14:55:58 -08002901
Andy Hung98ef9782014-03-04 14:46:50 -08002902 // Only if the Effects buffer is enabled and there is data in the
2903 // Effects buffer (buffer valid), we need to
2904 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002905 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08002906 if (mEffectBufferValid) {
2907 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
2908 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
2909 mNormalFrameCount * mChannelCount);
2910 }
2911
Eric Laurent81784c32012-11-19 14:55:58 -08002912 // enable changes in effect chain
2913 unlockEffectChains(effectChains);
2914
Eric Laurentbfb1b832013-01-07 09:53:42 -08002915 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002916 // mSleepTimeUs == 0 means we must write to audio hardware
2917 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07002918 ssize_t ret = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002919 if (mBytesRemaining) {
Andy Hung08fb1742015-05-31 23:22:10 -07002920 ret = threadLoop_write();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002921 if (ret < 0) {
2922 mBytesRemaining = 0;
2923 } else {
2924 mBytesWritten += ret;
2925 mBytesRemaining -= ret;
2926 }
2927 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
2928 (mMixerStatus == MIXER_DRAIN_ALL)) {
2929 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08002930 }
Andy Hung08fb1742015-05-31 23:22:10 -07002931 if (mType == MIXER && !mStandby) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07002932 // write blocked detection
2933 nsecs_t now = systemTime();
2934 nsecs_t delta = now - mLastWriteTime;
Andy Hung08fb1742015-05-31 23:22:10 -07002935 if (delta > maxPeriod) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07002936 mNumDelayedWrites++;
2937 if ((now - lastWarning) > kWarningThrottleNs) {
2938 ATRACE_NAME("underrun");
2939 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2940 ns2ms(delta), mNumDelayedWrites, this);
2941 lastWarning = now;
2942 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002943 }
Andy Hung08fb1742015-05-31 23:22:10 -07002944
2945 if (mThreadThrottle
2946 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
2947 && ret > 0) { // we wrote something
2948 // Limit MixerThread data processing to no more than twice the
2949 // expected processing rate.
2950 //
2951 // This helps prevent underruns with NuPlayer and other applications
2952 // which may set up buffers that are close to the minimum size, or use
2953 // deep buffers, and rely on a double-buffering sleep strategy to fill.
2954 //
2955 // The throttle smooths out sudden large data drains from the device,
2956 // e.g. when it comes out of standby, which often causes problems with
2957 // (1) mixer threads without a fast mixer (which has its own warm-up)
2958 // (2) minimum buffer sized tracks (even if the track is full,
2959 // the app won't fill fast enough to handle the sudden draw).
2960
2961 const int32_t deltaMs = delta / 1000000;
2962 const int32_t throttleMs = mHalfBufferMs - deltaMs;
2963 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
2964 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07002965 // notify of throttle start on verbose log
2966 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
2967 "mixer(%p) throttle begin:"
2968 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07002969 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07002970 mThreadThrottleTimeMs += throttleMs;
2971 } else {
2972 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
2973 if (diff > 0) {
2974 // notify of throttle end on debug log
2975 ALOGD("mixer(%p) throttle end: throttle time(%u)", this, diff);
2976 mThreadThrottleEndMs = mThreadThrottleTimeMs;
2977 }
Andy Hung08fb1742015-05-31 23:22:10 -07002978 }
2979 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002980 }
Eric Laurent81784c32012-11-19 14:55:58 -08002981
Eric Laurentbfb1b832013-01-07 09:53:42 -08002982 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07002983 ATRACE_BEGIN("sleep");
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002984 usleep(mSleepTimeUs);
Glenn Kastene7754022014-10-31 12:11:26 -07002985 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002986 }
Eric Laurent81784c32012-11-19 14:55:58 -08002987 }
2988
2989 // Finally let go of removed track(s), without the lock held
2990 // since we can't guarantee the destructors won't acquire that
2991 // same lock. This will also mutate and push a new fast mixer state.
2992 threadLoop_removeTracks(tracksToRemove);
2993 tracksToRemove.clear();
2994
2995 // FIXME I don't understand the need for this here;
2996 // it was in the original code but maybe the
2997 // assignment in saveOutputTracks() makes this unnecessary?
2998 clearOutputTracks();
2999
3000 // Effect chains will be actually deleted here if they were removed from
3001 // mEffectChains list during mixing or effects processing
3002 effectChains.clear();
3003
3004 // FIXME Note that the above .clear() is no longer necessary since effectChains
3005 // is now local to this block, but will keep it for now (at least until merge done).
3006 }
3007
Eric Laurentbfb1b832013-01-07 09:53:42 -08003008 threadLoop_exit();
3009
Eric Laurentcf817a22014-08-04 20:36:31 -07003010 if (!mStandby) {
3011 threadLoop_standby();
3012 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003013 }
3014
3015 releaseWakeLock();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003016 mWakeLockUids.clear();
3017 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08003018
3019 ALOGV("Thread %p type %d exiting", this, mType);
3020 return false;
3021}
3022
Eric Laurentbfb1b832013-01-07 09:53:42 -08003023// removeTracks_l() must be called with ThreadBase::mLock held
3024void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3025{
3026 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07003027 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003028 for (size_t i=0 ; i<count ; i++) {
3029 const sp<Track>& track = tracksToRemove.itemAt(i);
3030 mActiveTracks.remove(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003031 mWakeLockUids.remove(track->uid());
3032 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003033 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
3034 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3035 if (chain != 0) {
3036 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
3037 track->sessionId());
3038 chain->decActiveTrackCnt();
3039 }
3040 if (track->isTerminated()) {
3041 removeTrack_l(track);
3042 }
3043 }
3044 }
3045
3046}
Eric Laurent81784c32012-11-19 14:55:58 -08003047
Eric Laurentaccc1472013-09-20 09:36:34 -07003048status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3049{
3050 if (mNormalSink != 0) {
3051 return mNormalSink->getTimestamp(timestamp);
3052 }
Andy Hung9a1c8892014-12-03 11:37:42 -08003053 if ((mType == OFFLOAD || mType == DIRECT)
3054 && mOutput != NULL && mOutput->stream->get_presentation_position) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003055 uint64_t position64;
Phil Burk062e67a2015-02-11 13:40:50 -08003056 int ret = mOutput->getPresentationPosition(&position64, &timestamp.mTime);
Eric Laurentaccc1472013-09-20 09:36:34 -07003057 if (ret == 0) {
3058 timestamp.mPosition = (uint32_t)position64;
3059 return NO_ERROR;
3060 }
3061 }
3062 return INVALID_OPERATION;
3063}
Eric Laurent1c333e22014-05-20 10:48:17 -07003064
Eric Laurent054d9d32015-04-24 08:48:48 -07003065status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
3066 audio_patch_handle_t *handle)
3067{
3068 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3069 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3070 if (mFastMixer != 0) {
3071 FastMixerStateQueue *sq = mFastMixer->sq();
3072 FastMixerState *state = sq->begin();
3073 if (!(state->mCommand & FastMixerState::IDLE)) {
3074 previousCommand = state->mCommand;
3075 state->mCommand = FastMixerState::HOT_IDLE;
3076 sq->end();
3077 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3078 } else {
3079 sq->end(false /*didModify*/);
3080 }
3081 }
3082 status_t status = PlaybackThread::createAudioPatch_l(patch, handle);
3083
3084 if (!(previousCommand & FastMixerState::IDLE)) {
3085 ALOG_ASSERT(mFastMixer != 0);
3086 FastMixerStateQueue *sq = mFastMixer->sq();
3087 FastMixerState *state = sq->begin();
3088 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3089 state->mCommand = previousCommand;
3090 sq->end();
3091 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3092 }
3093
3094 return status;
3095}
3096
Eric Laurent1c333e22014-05-20 10:48:17 -07003097status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3098 audio_patch_handle_t *handle)
3099{
3100 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003101
3102 // store new device and send to effects
3103 audio_devices_t type = AUDIO_DEVICE_NONE;
3104 for (unsigned int i = 0; i < patch->num_sinks; i++) {
3105 type |= patch->sinks[i].ext.device.type;
3106 }
3107
3108#ifdef ADD_BATTERY_DATA
3109 // when changing the audio output device, call addBatteryData to notify
3110 // the change
3111 if (mOutDevice != type) {
3112 uint32_t params = 0;
3113 // check whether speaker is on
3114 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3115 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003116 }
3117
Eric Laurent054d9d32015-04-24 08:48:48 -07003118 audio_devices_t deviceWithoutSpeaker
3119 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3120 // check if any other device (except speaker) is on
3121 if (type & deviceWithoutSpeaker) {
3122 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3123 }
3124
3125 if (params != 0) {
3126 addBatteryData(params);
3127 }
3128 }
3129#endif
3130
3131 for (size_t i = 0; i < mEffectChains.size(); i++) {
3132 mEffectChains[i]->setDevice_l(type);
3133 }
3134 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003135 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003136
3137 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003138 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
3139 status = hwDevice->create_audio_patch(hwDevice,
3140 patch->num_sources,
3141 patch->sources,
3142 patch->num_sinks,
3143 patch->sinks,
3144 handle);
3145 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003146 char *address;
3147 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3148 //FIXME: we only support address on first sink with HAL version < 3.0
3149 address = audio_device_address_to_parameter(
3150 patch->sinks[0].ext.device.type,
3151 patch->sinks[0].ext.device.address);
3152 } else {
3153 address = (char *)calloc(1, 1);
3154 }
3155 AudioParameter param = AudioParameter(String8(address));
3156 free(address);
3157 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), (int)type);
3158 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3159 param.toString().string());
3160 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003161 }
Eric Laurent296fb132015-05-01 11:38:42 -07003162 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent1c333e22014-05-20 10:48:17 -07003163 return status;
3164}
3165
Eric Laurent054d9d32015-04-24 08:48:48 -07003166status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3167{
3168 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3169 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3170 if (mFastMixer != 0) {
3171 FastMixerStateQueue *sq = mFastMixer->sq();
3172 FastMixerState *state = sq->begin();
3173 if (!(state->mCommand & FastMixerState::IDLE)) {
3174 previousCommand = state->mCommand;
3175 state->mCommand = FastMixerState::HOT_IDLE;
3176 sq->end();
3177 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3178 } else {
3179 sq->end(false /*didModify*/);
3180 }
3181 }
3182
3183 status_t status = PlaybackThread::releaseAudioPatch_l(handle);
3184
3185 if (!(previousCommand & FastMixerState::IDLE)) {
3186 ALOG_ASSERT(mFastMixer != 0);
3187 FastMixerStateQueue *sq = mFastMixer->sq();
3188 FastMixerState *state = sq->begin();
3189 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3190 state->mCommand = previousCommand;
3191 sq->end();
3192 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3193 }
3194
3195 return status;
3196}
3197
Eric Laurent1c333e22014-05-20 10:48:17 -07003198status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3199{
3200 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003201
3202 mOutDevice = AUDIO_DEVICE_NONE;
3203
Eric Laurent1c333e22014-05-20 10:48:17 -07003204 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
3205 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
3206 status = hwDevice->release_audio_patch(hwDevice, handle);
3207 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003208 AudioParameter param;
3209 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
3210 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3211 param.toString().string());
Eric Laurent1c333e22014-05-20 10:48:17 -07003212 }
3213 return status;
3214}
3215
Eric Laurent83b88082014-06-20 18:31:16 -07003216void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3217{
3218 Mutex::Autolock _l(mLock);
3219 mTracks.add(track);
3220}
3221
3222void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3223{
3224 Mutex::Autolock _l(mLock);
3225 destroyTrack_l(track);
3226}
3227
3228void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
3229{
3230 ThreadBase::getAudioPortConfig(config);
3231 config->role = AUDIO_PORT_ROLE_SOURCE;
3232 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3233 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
3234}
3235
Eric Laurent81784c32012-11-19 14:55:58 -08003236// ----------------------------------------------------------------------------
3237
3238AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurent72e3f392015-05-20 14:43:50 -07003239 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
3240 : PlaybackThread(audioFlinger, output, id, device, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08003241 // mAudioMixer below
3242 // mFastMixer below
3243 mFastMixerFutex(0)
3244 // mOutputSink below
3245 // mPipeSink below
3246 // mNormalSink below
3247{
3248 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07003249 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, "
Eric Laurent81784c32012-11-19 14:55:58 -08003250 "mFrameCount=%d, mNormalFrameCount=%d",
3251 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3252 mNormalFrameCount);
3253 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3254
Andy Hungfbfc3952015-01-15 13:33:51 -08003255 if (type == DUPLICATING) {
3256 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3257 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3258 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3259 return;
3260 }
Eric Laurent81784c32012-11-19 14:55:58 -08003261 // create an NBAIO sink for the HAL output stream, and negotiate
3262 mOutputSink = new AudioStreamOutSink(output->stream);
3263 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003264 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Eric Laurent81784c32012-11-19 14:55:58 -08003265 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
3266 ALOG_ASSERT(index == 0);
3267
3268 // initialize fast mixer depending on configuration
3269 bool initFastMixer;
3270 switch (kUseFastMixer) {
3271 case FastMixer_Never:
3272 initFastMixer = false;
3273 break;
3274 case FastMixer_Always:
3275 initFastMixer = true;
3276 break;
3277 case FastMixer_Static:
3278 case FastMixer_Dynamic:
3279 initFastMixer = mFrameCount < mNormalFrameCount;
3280 break;
3281 }
3282 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003283 audio_format_t fastMixerFormat;
3284 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3285 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3286 } else {
3287 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3288 }
3289 if (mFormat != fastMixerFormat) {
3290 // change our Sink format to accept our intermediate precision
3291 mFormat = fastMixerFormat;
3292 free(mSinkBuffer);
3293 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3294 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3295 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3296 }
Eric Laurent81784c32012-11-19 14:55:58 -08003297
3298 // create a MonoPipe to connect our submix to FastMixer
3299 NBAIO_Format format = mOutputSink->format();
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003300 NBAIO_Format origformat = format;
Andy Hung1258c1a2014-05-23 21:22:17 -07003301 // adjust format to match that of the Fast Mixer
Glenn Kasten97b7b752014-09-28 13:04:24 -07003302 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003303 format.mFormat = fastMixerFormat;
3304 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3305
Eric Laurent81784c32012-11-19 14:55:58 -08003306 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3307 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3308 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3309 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3310 const NBAIO_Format offers[1] = {format};
3311 size_t numCounterOffers = 0;
3312 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
3313 ALOG_ASSERT(index == 0);
3314 monoPipe->setAvgFrames((mScreenState & 1) ?
3315 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3316 mPipeSink = monoPipe;
3317
Glenn Kasten46909e72013-02-26 09:20:22 -08003318#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08003319 if (mTeeSinkOutputEnabled) {
3320 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003321 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
3322 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08003323 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003324 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003325 ALOG_ASSERT(index == 0);
3326 mTeeSink = teeSink;
3327 PipeReader *teeSource = new PipeReader(*teeSink);
3328 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003329 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003330 ALOG_ASSERT(index == 0);
3331 mTeeSource = teeSource;
3332 }
Glenn Kasten46909e72013-02-26 09:20:22 -08003333#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003334
3335 // create fast mixer and configure it initially with just one fast track for our submix
3336 mFastMixer = new FastMixer();
3337 FastMixerStateQueue *sq = mFastMixer->sq();
3338#ifdef STATE_QUEUE_DUMP
3339 sq->setObserverDump(&mStateQueueObserverDump);
3340 sq->setMutatorDump(&mStateQueueMutatorDump);
3341#endif
3342 FastMixerState *state = sq->begin();
3343 FastTrack *fastTrack = &state->mFastTracks[0];
3344 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3345 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3346 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003347 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3348 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003349 fastTrack->mGeneration++;
3350 state->mFastTracksGen++;
3351 state->mTrackMask = 1;
3352 // fast mixer will use the HAL output sink
3353 state->mOutputSink = mOutputSink.get();
3354 state->mOutputSinkGen++;
3355 state->mFrameCount = mFrameCount;
3356 state->mCommand = FastMixerState::COLD_IDLE;
3357 // already done in constructor initialization list
3358 //mFastMixerFutex = 0;
3359 state->mColdFutexAddr = &mFastMixerFutex;
3360 state->mColdGen++;
3361 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08003362#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003363 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08003364#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08003365 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3366 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003367 sq->end();
3368 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3369
3370 // start the fast mixer
3371 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3372 pid_t tid = mFastMixer->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003373 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003374
3375#ifdef AUDIO_WATCHDOG
3376 // create and start the watchdog
3377 mAudioWatchdog = new AudioWatchdog();
3378 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3379 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3380 tid = mAudioWatchdog->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003381 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003382#endif
3383
Eric Laurent81784c32012-11-19 14:55:58 -08003384 }
3385
3386 switch (kUseFastMixer) {
3387 case FastMixer_Never:
3388 case FastMixer_Dynamic:
3389 mNormalSink = mOutputSink;
3390 break;
3391 case FastMixer_Always:
3392 mNormalSink = mPipeSink;
3393 break;
3394 case FastMixer_Static:
3395 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3396 break;
3397 }
3398}
3399
3400AudioFlinger::MixerThread::~MixerThread()
3401{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003402 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003403 FastMixerStateQueue *sq = mFastMixer->sq();
3404 FastMixerState *state = sq->begin();
3405 if (state->mCommand == FastMixerState::COLD_IDLE) {
3406 int32_t old = android_atomic_inc(&mFastMixerFutex);
3407 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003408 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003409 }
3410 }
3411 state->mCommand = FastMixerState::EXIT;
3412 sq->end();
3413 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3414 mFastMixer->join();
3415 // Though the fast mixer thread has exited, it's state queue is still valid.
3416 // We'll use that extract the final state which contains one remaining fast track
3417 // corresponding to our sub-mix.
3418 state = sq->begin();
3419 ALOG_ASSERT(state->mTrackMask == 1);
3420 FastTrack *fastTrack = &state->mFastTracks[0];
3421 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3422 delete fastTrack->mBufferProvider;
3423 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003424 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003425#ifdef AUDIO_WATCHDOG
3426 if (mAudioWatchdog != 0) {
3427 mAudioWatchdog->requestExit();
3428 mAudioWatchdog->requestExitAndWait();
3429 mAudioWatchdog.clear();
3430 }
3431#endif
3432 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003433 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003434 delete mAudioMixer;
3435}
3436
3437
3438uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3439{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003440 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003441 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3442 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3443 }
3444 return latency;
3445}
3446
3447
3448void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3449{
3450 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3451}
3452
Eric Laurentbfb1b832013-01-07 09:53:42 -08003453ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003454{
3455 // FIXME we should only do one push per cycle; confirm this is true
3456 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003457 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003458 FastMixerStateQueue *sq = mFastMixer->sq();
3459 FastMixerState *state = sq->begin();
3460 if (state->mCommand != FastMixerState::MIX_WRITE &&
3461 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3462 if (state->mCommand == FastMixerState::COLD_IDLE) {
3463 int32_t old = android_atomic_inc(&mFastMixerFutex);
3464 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003465 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003466 }
3467#ifdef AUDIO_WATCHDOG
3468 if (mAudioWatchdog != 0) {
3469 mAudioWatchdog->resume();
3470 }
3471#endif
3472 }
3473 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08003474#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003475 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08003476 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08003477#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003478 sq->end();
3479 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3480 if (kUseFastMixer == FastMixer_Dynamic) {
3481 mNormalSink = mPipeSink;
3482 }
3483 } else {
3484 sq->end(false /*didModify*/);
3485 }
3486 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003487 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003488}
3489
3490void AudioFlinger::MixerThread::threadLoop_standby()
3491{
3492 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003493 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003494 FastMixerStateQueue *sq = mFastMixer->sq();
3495 FastMixerState *state = sq->begin();
3496 if (!(state->mCommand & FastMixerState::IDLE)) {
3497 state->mCommand = FastMixerState::COLD_IDLE;
3498 state->mColdFutexAddr = &mFastMixerFutex;
3499 state->mColdGen++;
3500 mFastMixerFutex = 0;
3501 sq->end();
3502 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3503 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3504 if (kUseFastMixer == FastMixer_Dynamic) {
3505 mNormalSink = mOutputSink;
3506 }
3507#ifdef AUDIO_WATCHDOG
3508 if (mAudioWatchdog != 0) {
3509 mAudioWatchdog->pause();
3510 }
3511#endif
3512 } else {
3513 sq->end(false /*didModify*/);
3514 }
3515 }
3516 PlaybackThread::threadLoop_standby();
3517}
3518
Eric Laurentbfb1b832013-01-07 09:53:42 -08003519bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3520{
3521 return false;
3522}
3523
3524bool AudioFlinger::PlaybackThread::shouldStandby_l()
3525{
3526 return !mStandby;
3527}
3528
3529bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3530{
3531 Mutex::Autolock _l(mLock);
3532 return waitingAsyncCallback_l();
3533}
3534
Eric Laurent81784c32012-11-19 14:55:58 -08003535// shared by MIXER and DIRECT, overridden by DUPLICATING
3536void AudioFlinger::PlaybackThread::threadLoop_standby()
3537{
3538 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08003539 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003540 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003541 // discard any pending drain or write ack by incrementing sequence
3542 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3543 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003544 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003545 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3546 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003547 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003548 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003549}
3550
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003551void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3552{
3553 ALOGV("signal playback thread");
3554 broadcast_l();
3555}
3556
Eric Laurent81784c32012-11-19 14:55:58 -08003557void AudioFlinger::MixerThread::threadLoop_mix()
3558{
3559 // obtain the presentation timestamp of the next output buffer
3560 int64_t pts;
3561 status_t status = INVALID_OPERATION;
3562
3563 if (mNormalSink != 0) {
3564 status = mNormalSink->getNextWriteTimestamp(&pts);
3565 } else {
3566 status = mOutputSink->getNextWriteTimestamp(&pts);
3567 }
3568
3569 if (status != NO_ERROR) {
3570 pts = AudioBufferProvider::kInvalidPTS;
3571 }
3572
3573 // mix buffers...
3574 mAudioMixer->process(pts);
Andy Hung25c2dac2014-02-27 14:56:00 -08003575 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003576 // increase sleep time progressively when application underrun condition clears.
3577 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3578 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3579 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003580 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003581 sleepTimeShift--;
3582 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003583 mSleepTimeUs = 0;
3584 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08003585 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003586
Eric Laurent81784c32012-11-19 14:55:58 -08003587}
3588
3589void AudioFlinger::MixerThread::threadLoop_sleepTime()
3590{
3591 // If no tracks are ready, sleep once for the duration of an output
3592 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003593 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003594 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003595 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
3596 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
3597 mSleepTimeUs = kMinThreadSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003598 }
3599 // reduce sleep time in case of consecutive application underruns to avoid
3600 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3601 // duration we would end up writing less data than needed by the audio HAL if
3602 // the condition persists.
3603 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3604 sleepTimeShift++;
3605 }
3606 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003607 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003608 }
3609 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003610 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3611 // before effects processing or output.
3612 if (mMixerBufferValid) {
3613 memset(mMixerBuffer, 0, mMixerBufferSize);
3614 } else {
3615 memset(mSinkBuffer, 0, mSinkBufferSize);
3616 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003617 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003618 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3619 "anticipated start");
3620 }
3621 // TODO add standby time extension fct of effect tail
3622}
3623
3624// prepareTracks_l() must be called with ThreadBase::mLock held
3625AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3626 Vector< sp<Track> > *tracksToRemove)
3627{
3628
3629 mixer_state mixerStatus = MIXER_IDLE;
3630 // find out which tracks need to be processed
3631 size_t count = mActiveTracks.size();
3632 size_t mixedTracks = 0;
3633 size_t tracksWithEffect = 0;
3634 // counts only _active_ fast tracks
3635 size_t fastTracks = 0;
3636 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
3637
3638 float masterVolume = mMasterVolume;
3639 bool masterMute = mMasterMute;
3640
3641 if (masterMute) {
3642 masterVolume = 0;
3643 }
3644 // Delegate master volume control to effect in output mix effect chain if needed
3645 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3646 if (chain != 0) {
3647 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
3648 chain->setVolume_l(&v, &v);
3649 masterVolume = (float)((v + (1 << 23)) >> 24);
3650 chain.clear();
3651 }
3652
3653 // prepare a new state to push
3654 FastMixerStateQueue *sq = NULL;
3655 FastMixerState *state = NULL;
3656 bool didModify = false;
3657 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003658 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003659 sq = mFastMixer->sq();
3660 state = sq->begin();
3661 }
3662
Andy Hung69aed5f2014-02-25 17:24:40 -08003663 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08003664 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08003665
Eric Laurent81784c32012-11-19 14:55:58 -08003666 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003667 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003668 if (t == 0) {
3669 continue;
3670 }
3671
3672 // this const just means the local variable doesn't change
3673 Track* const track = t.get();
3674
3675 // process fast tracks
3676 if (track->isFastTrack()) {
3677
3678 // It's theoretically possible (though unlikely) for a fast track to be created
3679 // and then removed within the same normal mix cycle. This is not a problem, as
3680 // the track never becomes active so it's fast mixer slot is never touched.
3681 // The converse, of removing an (active) track and then creating a new track
3682 // at the identical fast mixer slot within the same normal mix cycle,
3683 // is impossible because the slot isn't marked available until the end of each cycle.
3684 int j = track->mFastIndex;
3685 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
3686 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
3687 FastTrack *fastTrack = &state->mFastTracks[j];
3688
3689 // Determine whether the track is currently in underrun condition,
3690 // and whether it had a recent underrun.
3691 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
3692 FastTrackUnderruns underruns = ftDump->mUnderruns;
3693 uint32_t recentFull = (underruns.mBitFields.mFull -
3694 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
3695 uint32_t recentPartial = (underruns.mBitFields.mPartial -
3696 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
3697 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
3698 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
3699 uint32_t recentUnderruns = recentPartial + recentEmpty;
3700 track->mObservedUnderruns = underruns;
3701 // don't count underruns that occur while stopping or pausing
3702 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07003703 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
3704 recentUnderruns > 0) {
3705 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
3706 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003707 }
3708
3709 // This is similar to the state machine for normal tracks,
3710 // with a few modifications for fast tracks.
3711 bool isActive = true;
3712 switch (track->mState) {
3713 case TrackBase::STOPPING_1:
3714 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08003715 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003716 track->mState = TrackBase::STOPPING_2;
3717 }
3718 break;
3719 case TrackBase::PAUSING:
3720 // ramp down is not yet implemented
3721 track->setPaused();
3722 break;
3723 case TrackBase::RESUMING:
3724 // ramp up is not yet implemented
3725 track->mState = TrackBase::ACTIVE;
3726 break;
3727 case TrackBase::ACTIVE:
3728 if (recentFull > 0 || recentPartial > 0) {
3729 // track has provided at least some frames recently: reset retry count
3730 track->mRetryCount = kMaxTrackRetries;
3731 }
3732 if (recentUnderruns == 0) {
3733 // no recent underruns: stay active
3734 break;
3735 }
3736 // there has recently been an underrun of some kind
3737 if (track->sharedBuffer() == 0) {
3738 // were any of the recent underruns "empty" (no frames available)?
3739 if (recentEmpty == 0) {
3740 // no, then ignore the partial underruns as they are allowed indefinitely
3741 break;
3742 }
3743 // there has recently been an "empty" underrun: decrement the retry counter
3744 if (--(track->mRetryCount) > 0) {
3745 break;
3746 }
3747 // indicate to client process that the track was disabled because of underrun;
3748 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003749 android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003750 // remove from active list, but state remains ACTIVE [confusing but true]
3751 isActive = false;
3752 break;
3753 }
3754 // fall through
3755 case TrackBase::STOPPING_2:
3756 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003757 case TrackBase::STOPPED:
3758 case TrackBase::FLUSHED: // flush() while active
3759 // Check for presentation complete if track is inactive
3760 // We have consumed all the buffers of this track.
3761 // This would be incomplete if we auto-paused on underrun
3762 {
3763 size_t audioHALFrames =
3764 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3765 size_t framesWritten = mBytesWritten / mFrameSize;
3766 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
3767 // track stays in active list until presentation is complete
3768 break;
3769 }
3770 }
3771 if (track->isStopping_2()) {
3772 track->mState = TrackBase::STOPPED;
3773 }
3774 if (track->isStopped()) {
3775 // Can't reset directly, as fast mixer is still polling this track
3776 // track->reset();
3777 // So instead mark this track as needing to be reset after push with ack
3778 resetMask |= 1 << i;
3779 }
3780 isActive = false;
3781 break;
3782 case TrackBase::IDLE:
3783 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08003784 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08003785 }
3786
3787 if (isActive) {
3788 // was it previously inactive?
3789 if (!(state->mTrackMask & (1 << j))) {
3790 ExtendedAudioBufferProvider *eabp = track;
3791 VolumeProvider *vp = track;
3792 fastTrack->mBufferProvider = eabp;
3793 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08003794 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003795 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08003796 fastTrack->mGeneration++;
3797 state->mTrackMask |= 1 << j;
3798 didModify = true;
3799 // no acknowledgement required for newly active tracks
3800 }
3801 // cache the combined master volume and stream type volume for fast mixer; this
3802 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08003803 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08003804 ++fastTracks;
3805 } else {
3806 // was it previously active?
3807 if (state->mTrackMask & (1 << j)) {
3808 fastTrack->mBufferProvider = NULL;
3809 fastTrack->mGeneration++;
3810 state->mTrackMask &= ~(1 << j);
3811 didModify = true;
3812 // If any fast tracks were removed, we must wait for acknowledgement
3813 // because we're about to decrement the last sp<> on those tracks.
3814 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3815 } else {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003816 LOG_ALWAYS_FATAL("fast track %d should have been active", j);
Eric Laurent81784c32012-11-19 14:55:58 -08003817 }
3818 tracksToRemove->add(track);
3819 // Avoids a misleading display in dumpsys
3820 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
3821 }
3822 continue;
3823 }
3824
3825 { // local variable scope to avoid goto warning
3826
3827 audio_track_cblk_t* cblk = track->cblk();
3828
3829 // The first time a track is added we wait
3830 // for all its buffers to be filled before processing it
3831 int name = track->name();
3832 // make sure that we have enough frames to mix one full buffer.
3833 // enforce this condition only once to enable draining the buffer in case the client
3834 // app does not call stop() and relies on underrun to stop:
3835 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
3836 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003837 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07003838 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07003839 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07003840
3841 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07003842 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07003843 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
3844 // add frames already consumed but not yet released by the resampler
3845 // because mAudioTrackServerProxy->framesReady() will include these frames
3846 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
3847
Eric Laurent81784c32012-11-19 14:55:58 -08003848 uint32_t minFrames = 1;
3849 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
3850 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003851 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08003852 }
Eric Laurent13e4c962013-12-20 17:36:01 -08003853
3854 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07003855 if (ATRACE_ENABLED()) {
3856 // I wish we had formatted trace names
3857 char traceName[16];
3858 strcpy(traceName, "nRdy");
3859 int name = track->name();
3860 if (AudioMixer::TRACK0 <= name &&
3861 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
3862 name -= AudioMixer::TRACK0;
3863 traceName[4] = (name / 10) + '0';
3864 traceName[5] = (name % 10) + '0';
3865 } else {
3866 traceName[4] = '?';
3867 traceName[5] = '?';
3868 }
3869 traceName[6] = '\0';
3870 ATRACE_INT(traceName, framesReady);
3871 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003872 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08003873 !track->isPaused() && !track->isTerminated())
3874 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003875 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003876
3877 mixedTracks++;
3878
Andy Hung69aed5f2014-02-25 17:24:40 -08003879 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
3880 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08003881 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08003882 if (track->mainBuffer() != mSinkBuffer &&
3883 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08003884 if (mEffectBufferEnabled) {
3885 mEffectBufferValid = true; // Later can set directly.
3886 }
Eric Laurent81784c32012-11-19 14:55:58 -08003887 chain = getEffectChain_l(track->sessionId());
3888 // Delegate volume control to effect in track effect chain if needed
3889 if (chain != 0) {
3890 tracksWithEffect++;
3891 } else {
3892 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
3893 "session %d",
3894 name, track->sessionId());
3895 }
3896 }
3897
3898
3899 int param = AudioMixer::VOLUME;
3900 if (track->mFillingUpStatus == Track::FS_FILLED) {
3901 // no ramp for the first volume setting
3902 track->mFillingUpStatus = Track::FS_ACTIVE;
3903 if (track->mState == TrackBase::RESUMING) {
3904 track->mState = TrackBase::ACTIVE;
3905 param = AudioMixer::RAMP_VOLUME;
3906 }
3907 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003908 // FIXME should not make a decision based on mServer
3909 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003910 // If the track is stopped before the first frame was mixed,
3911 // do not apply ramp
3912 param = AudioMixer::RAMP_VOLUME;
3913 }
3914
3915 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07003916 uint32_t vl, vr; // in U8.24 integer format
3917 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08003918 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07003919 vl = vr = 0;
3920 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08003921 if (track->isPausing()) {
3922 track->setPaused();
3923 }
3924 } else {
3925
3926 // read original volumes with volume control
3927 float typeVolume = mStreamTypes[track->streamType()].volume;
3928 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003929 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07003930 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07003931 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
3932 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08003933 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07003934 if (vlf > GAIN_FLOAT_UNITY) {
3935 ALOGV("Track left volume out of range: %.3g", vlf);
3936 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003937 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07003938 if (vrf > GAIN_FLOAT_UNITY) {
3939 ALOGV("Track right volume out of range: %.3g", vrf);
3940 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003941 }
3942 // now apply the master volume and stream type volume
Andy Hung6be49402014-05-30 10:42:03 -07003943 vlf *= v;
3944 vrf *= v;
Eric Laurent81784c32012-11-19 14:55:58 -08003945 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07003946 // then derive vl and vr as U8.24 versions for the effect chain
3947 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
3948 vl = (uint32_t) (scaleto8_24 * vlf);
3949 vr = (uint32_t) (scaleto8_24 * vrf);
3950 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08003951 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08003952 // send level comes from shared memory and so may be corrupt
3953 if (sendLevel > MAX_GAIN_INT) {
3954 ALOGV("Track send level out of range: %04X", sendLevel);
3955 sendLevel = MAX_GAIN_INT;
3956 }
Andy Hung6be49402014-05-30 10:42:03 -07003957 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
3958 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08003959 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003960
Eric Laurent81784c32012-11-19 14:55:58 -08003961 // Delegate volume control to effect in track effect chain if needed
3962 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3963 // Do not ramp volume if volume is controlled by effect
3964 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08003965 // Update remaining floating point volume levels
3966 vlf = (float)vl / (1 << 24);
3967 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08003968 track->mHasVolumeController = true;
3969 } else {
3970 // force no volume ramp when volume controller was just disabled or removed
3971 // from effect chain to avoid volume spike
3972 if (track->mHasVolumeController) {
3973 param = AudioMixer::VOLUME;
3974 }
3975 track->mHasVolumeController = false;
3976 }
3977
Eric Laurent81784c32012-11-19 14:55:58 -08003978 // XXX: these things DON'T need to be done each time
3979 mAudioMixer->setBufferProvider(name, track);
3980 mAudioMixer->enable(name);
3981
Andy Hung6be49402014-05-30 10:42:03 -07003982 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
3983 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
3984 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08003985 mAudioMixer->setParameter(
3986 name,
3987 AudioMixer::TRACK,
3988 AudioMixer::FORMAT, (void *)track->format());
3989 mAudioMixer->setParameter(
3990 name,
3991 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003992 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07003993 mAudioMixer->setParameter(
3994 name,
3995 AudioMixer::TRACK,
3996 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08003997 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07003998 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003999 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08004000 if (reqSampleRate == 0) {
4001 reqSampleRate = mSampleRate;
4002 } else if (reqSampleRate > maxSampleRate) {
4003 reqSampleRate = maxSampleRate;
4004 }
Eric Laurent81784c32012-11-19 14:55:58 -08004005 mAudioMixer->setParameter(
4006 name,
4007 AudioMixer::RESAMPLE,
4008 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004009 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004010
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004011 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004012 mAudioMixer->setParameter(
4013 name,
4014 AudioMixer::TIMESTRETCH,
4015 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004016 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004017
Andy Hung69aed5f2014-02-25 17:24:40 -08004018 /*
4019 * Select the appropriate output buffer for the track.
4020 *
Andy Hung98ef9782014-03-04 14:46:50 -08004021 * Tracks with effects go into their own effects chain buffer
4022 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08004023 *
4024 * Other tracks can use mMixerBuffer for higher precision
4025 * channel accumulation. If this buffer is enabled
4026 * (mMixerBufferEnabled true), then selected tracks will accumulate
4027 * into it.
4028 *
4029 */
4030 if (mMixerBufferEnabled
4031 && (track->mainBuffer() == mSinkBuffer
4032 || track->mainBuffer() == mMixerBuffer)) {
4033 mAudioMixer->setParameter(
4034 name,
4035 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004036 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08004037 mAudioMixer->setParameter(
4038 name,
4039 AudioMixer::TRACK,
4040 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
4041 // TODO: override track->mainBuffer()?
4042 mMixerBufferValid = true;
4043 } else {
4044 mAudioMixer->setParameter(
4045 name,
4046 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004047 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08004048 mAudioMixer->setParameter(
4049 name,
4050 AudioMixer::TRACK,
4051 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
4052 }
Eric Laurent81784c32012-11-19 14:55:58 -08004053 mAudioMixer->setParameter(
4054 name,
4055 AudioMixer::TRACK,
4056 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
4057
4058 // reset retry count
4059 track->mRetryCount = kMaxTrackRetries;
4060
4061 // If one track is ready, set the mixer ready if:
4062 // - the mixer was not ready during previous round OR
4063 // - no other track is not ready
4064 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
4065 mixerStatus != MIXER_TRACKS_ENABLED) {
4066 mixerStatus = MIXER_TRACKS_READY;
4067 }
4068 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004069 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hung08fb1742015-05-31 23:22:10 -07004070 ALOGV("track(%p) underrun, framesReady(%zu) < framesDesired(%zd)",
4071 track, framesReady, desiredFrames);
Glenn Kasten82aaf942013-07-17 16:05:07 -07004072 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004073 }
Eric Laurent81784c32012-11-19 14:55:58 -08004074 // clear effect chain input buffer if an active track underruns to avoid sending
4075 // previous audio buffer again to effects
4076 chain = getEffectChain_l(track->sessionId());
4077 if (chain != 0) {
4078 chain->clearInputBuffer();
4079 }
4080
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004081 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004082 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
4083 track->isStopped() || track->isPaused()) {
4084 // We have consumed all the buffers of this track.
4085 // Remove it from the list of active tracks.
4086 // TODO: use actual buffer filling status instead of latency when available from
4087 // audio HAL
4088 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
4089 size_t framesWritten = mBytesWritten / mFrameSize;
4090 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
4091 if (track->isStopped()) {
4092 track->reset();
4093 }
4094 tracksToRemove->add(track);
4095 }
4096 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08004097 // No buffers for this track. Give it a few chances to
4098 // fill a buffer, then remove it from active list.
4099 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004100 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004101 tracksToRemove->add(track);
4102 // indicate to client process that the track was disabled because of underrun;
4103 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07004104 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08004105 // If one track is not ready, mark the mixer also not ready if:
4106 // - the mixer was ready during previous round OR
4107 // - no other track is ready
4108 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
4109 mixerStatus != MIXER_TRACKS_READY) {
4110 mixerStatus = MIXER_TRACKS_ENABLED;
4111 }
4112 }
4113 mAudioMixer->disable(name);
4114 }
4115
4116 } // local variable scope to avoid goto warning
4117track_is_ready: ;
4118
4119 }
4120
4121 // Push the new FastMixer state if necessary
4122 bool pauseAudioWatchdog = false;
4123 if (didModify) {
4124 state->mFastTracksGen++;
4125 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4126 if (kUseFastMixer == FastMixer_Dynamic &&
4127 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4128 state->mCommand = FastMixerState::COLD_IDLE;
4129 state->mColdFutexAddr = &mFastMixerFutex;
4130 state->mColdGen++;
4131 mFastMixerFutex = 0;
4132 if (kUseFastMixer == FastMixer_Dynamic) {
4133 mNormalSink = mOutputSink;
4134 }
4135 // If we go into cold idle, need to wait for acknowledgement
4136 // so that fast mixer stops doing I/O.
4137 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4138 pauseAudioWatchdog = true;
4139 }
Eric Laurent81784c32012-11-19 14:55:58 -08004140 }
4141 if (sq != NULL) {
4142 sq->end(didModify);
4143 sq->push(block);
4144 }
4145#ifdef AUDIO_WATCHDOG
4146 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4147 mAudioWatchdog->pause();
4148 }
4149#endif
4150
4151 // Now perform the deferred reset on fast tracks that have stopped
4152 while (resetMask != 0) {
4153 size_t i = __builtin_ctz(resetMask);
4154 ALOG_ASSERT(i < count);
4155 resetMask &= ~(1 << i);
4156 sp<Track> t = mActiveTracks[i].promote();
4157 if (t == 0) {
4158 continue;
4159 }
4160 Track* track = t.get();
4161 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
4162 track->reset();
4163 }
4164
4165 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004166 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004167
Eric Laurent97d547d2014-09-02 14:45:53 -07004168 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
4169 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07004170 }
4171
4172 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07004173 // as long as there are effects we should clear the effects buffer, to avoid
4174 // passing a non-clean buffer to the effect chain
4175 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07004176 }
Andy Hung69aed5f2014-02-25 17:24:40 -08004177 // sink or mix buffer must be cleared if all tracks are connected to an
4178 // effect chain as in this case the mixer will not write to the sink or mix buffer
4179 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08004180 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4181 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08004182 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08004183 if (mMixerBufferValid) {
4184 memset(mMixerBuffer, 0, mMixerBufferSize);
4185 // TODO: In testing, mSinkBuffer below need not be cleared because
4186 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
4187 // after mixing.
4188 //
4189 // To enforce this guarantee:
4190 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4191 // (mixedTracks == 0 && fastTracks > 0))
4192 // must imply MIXER_TRACKS_READY.
4193 // Later, we may clear buffers regardless, and skip much of this logic.
4194 }
Andy Hung98ef9782014-03-04 14:46:50 -08004195 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07004196 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004197 }
4198
4199 // if any fast tracks, then status is ready
4200 mMixerStatusIgnoringFastTracks = mixerStatus;
4201 if (fastTracks > 0) {
4202 mixerStatus = MIXER_TRACKS_READY;
4203 }
4204 return mixerStatus;
4205}
4206
4207// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07004208int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
4209 audio_format_t format, int sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08004210{
Andy Hunge8a1ced2014-05-09 15:02:21 -07004211 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08004212}
4213
4214// deleteTrackName_l() must be called with ThreadBase::mLock held
4215void AudioFlinger::MixerThread::deleteTrackName_l(int name)
4216{
4217 ALOGV("remove track (%d) and delete from mixer", name);
4218 mAudioMixer->deleteTrackName(name);
4219}
4220
Eric Laurent10351942014-05-08 18:49:52 -07004221// checkForNewParameter_l() must be called with ThreadBase::mLock held
4222bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
4223 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004224{
Eric Laurent81784c32012-11-19 14:55:58 -08004225 bool reconfig = false;
4226
Eric Laurent10351942014-05-08 18:49:52 -07004227 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004228
Eric Laurent10351942014-05-08 18:49:52 -07004229 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
4230 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004231 if (mFastMixer != 0) {
Eric Laurent10351942014-05-08 18:49:52 -07004232 FastMixerStateQueue *sq = mFastMixer->sq();
4233 FastMixerState *state = sq->begin();
4234 if (!(state->mCommand & FastMixerState::IDLE)) {
4235 previousCommand = state->mCommand;
4236 state->mCommand = FastMixerState::HOT_IDLE;
4237 sq->end();
4238 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
4239 } else {
4240 sq->end(false /*didModify*/);
Eric Laurent81784c32012-11-19 14:55:58 -08004241 }
Eric Laurent10351942014-05-08 18:49:52 -07004242 }
Eric Laurent81784c32012-11-19 14:55:58 -08004243
Eric Laurent10351942014-05-08 18:49:52 -07004244 AudioParameter param = AudioParameter(keyValuePair);
4245 int value;
4246 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4247 reconfig = true;
4248 }
4249 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004250 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004251 status = BAD_VALUE;
4252 } else {
4253 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08004254 reconfig = true;
4255 }
Eric Laurent10351942014-05-08 18:49:52 -07004256 }
4257 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004258 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004259 status = BAD_VALUE;
4260 } else {
4261 // no need to save value, since it's constant
4262 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004263 }
Eric Laurent10351942014-05-08 18:49:52 -07004264 }
4265 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4266 // do not accept frame count changes if tracks are open as the track buffer
4267 // size depends on frame count and correct behavior would not be guaranteed
4268 // if frame count is changed after track creation
4269 if (!mTracks.isEmpty()) {
4270 status = INVALID_OPERATION;
4271 } else {
4272 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004273 }
Eric Laurent10351942014-05-08 18:49:52 -07004274 }
4275 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004276#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07004277 // when changing the audio output device, call addBatteryData to notify
4278 // the change
4279 if (mOutDevice != value) {
4280 uint32_t params = 0;
4281 // check whether speaker is on
4282 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
4283 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08004284 }
Eric Laurent10351942014-05-08 18:49:52 -07004285
4286 audio_devices_t deviceWithoutSpeaker
4287 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
4288 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07004289 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07004290 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4291 }
4292
4293 if (params != 0) {
4294 addBatteryData(params);
4295 }
4296 }
Eric Laurent81784c32012-11-19 14:55:58 -08004297#endif
4298
Eric Laurent10351942014-05-08 18:49:52 -07004299 // forward device change to effects that have requested to be
4300 // aware of attached audio device.
4301 if (value != AUDIO_DEVICE_NONE) {
4302 mOutDevice = value;
4303 for (size_t i = 0; i < mEffectChains.size(); i++) {
4304 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08004305 }
4306 }
Eric Laurent10351942014-05-08 18:49:52 -07004307 }
Eric Laurent81784c32012-11-19 14:55:58 -08004308
Eric Laurent10351942014-05-08 18:49:52 -07004309 if (status == NO_ERROR) {
4310 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4311 keyValuePair.string());
4312 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004313 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004314 mStandby = true;
4315 mBytesWritten = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004316 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Eric Laurent10351942014-05-08 18:49:52 -07004317 keyValuePair.string());
Eric Laurent81784c32012-11-19 14:55:58 -08004318 }
Eric Laurent10351942014-05-08 18:49:52 -07004319 if (status == NO_ERROR && reconfig) {
4320 readOutputParameters_l();
4321 delete mAudioMixer;
4322 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4323 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07004324 int name = getTrackName_l(mTracks[i]->mChannelMask,
4325 mTracks[i]->mFormat, mTracks[i]->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07004326 if (name < 0) {
4327 break;
4328 }
4329 mTracks[i]->mName = name;
4330 }
Eric Laurent73e26b62015-04-27 16:55:58 -07004331 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004332 }
Eric Laurent81784c32012-11-19 14:55:58 -08004333 }
4334
4335 if (!(previousCommand & FastMixerState::IDLE)) {
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004336 ALOG_ASSERT(mFastMixer != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08004337 FastMixerStateQueue *sq = mFastMixer->sq();
4338 FastMixerState *state = sq->begin();
4339 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
4340 state->mCommand = previousCommand;
4341 sq->end();
4342 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4343 }
4344
4345 return reconfig;
4346}
4347
4348
4349void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
4350{
4351 const size_t SIZE = 256;
4352 char buffer[SIZE];
4353 String8 result;
4354
4355 PlaybackThread::dumpInternals(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07004356 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Elliott Hughes87cebad2014-05-22 10:14:43 -07004357 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Eric Laurent81784c32012-11-19 14:55:58 -08004358
4359 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten4182c4e2013-07-15 14:45:07 -07004360 const FastMixerDumpState copy(mFastMixerDumpState);
Eric Laurent81784c32012-11-19 14:55:58 -08004361 copy.dump(fd);
4362
4363#ifdef STATE_QUEUE_DUMP
4364 // Similar for state queue
4365 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4366 observerCopy.dump(fd);
4367 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4368 mutatorCopy.dump(fd);
4369#endif
4370
Glenn Kasten46909e72013-02-26 09:20:22 -08004371#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08004372 // Write the tee output to a .wav file
4373 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08004374#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004375
4376#ifdef AUDIO_WATCHDOG
4377 if (mAudioWatchdog != 0) {
4378 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4379 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4380 wdCopy.dump(fd);
4381 }
4382#endif
4383}
4384
4385uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4386{
4387 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4388}
4389
4390uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4391{
4392 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4393}
4394
4395void AudioFlinger::MixerThread::cacheParameters_l()
4396{
4397 PlaybackThread::cacheParameters_l();
4398
4399 // FIXME: Relaxed timing because of a certain device that can't meet latency
4400 // Should be reduced to 2x after the vendor fixes the driver issue
4401 // increase threshold again due to low power audio mode. The way this warning
4402 // threshold is calculated and its usefulness should be reconsidered anyway.
4403 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4404}
4405
4406// ----------------------------------------------------------------------------
4407
4408AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07004409 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device, bool systemReady)
4410 : PlaybackThread(audioFlinger, output, id, device, DIRECT, systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08004411 // mLeftVolFloat, mRightVolFloat
4412{
4413}
4414
Eric Laurentbfb1b832013-01-07 09:53:42 -08004415AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4416 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07004417 ThreadBase::type_t type, bool systemReady)
4418 : PlaybackThread(audioFlinger, output, id, device, type, systemReady)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004419 // mLeftVolFloat, mRightVolFloat
4420{
4421}
4422
Eric Laurent81784c32012-11-19 14:55:58 -08004423AudioFlinger::DirectOutputThread::~DirectOutputThread()
4424{
4425}
4426
Eric Laurentbfb1b832013-01-07 09:53:42 -08004427void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
4428{
4429 audio_track_cblk_t* cblk = track->cblk();
4430 float left, right;
4431
4432 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4433 left = right = 0;
4434 } else {
4435 float typeVolume = mStreamTypes[track->streamType()].volume;
4436 float v = mMasterVolume * typeVolume;
4437 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004438 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4439 left = float_from_gain(gain_minifloat_unpack_left(vlr));
4440 if (left > GAIN_FLOAT_UNITY) {
4441 left = GAIN_FLOAT_UNITY;
4442 }
4443 left *= v;
4444 right = float_from_gain(gain_minifloat_unpack_right(vlr));
4445 if (right > GAIN_FLOAT_UNITY) {
4446 right = GAIN_FLOAT_UNITY;
4447 }
4448 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004449 }
4450
4451 if (lastTrack) {
4452 if (left != mLeftVolFloat || right != mRightVolFloat) {
4453 mLeftVolFloat = left;
4454 mRightVolFloat = right;
4455
4456 // Convert volumes from float to 8.24
4457 uint32_t vl = (uint32_t)(left * (1 << 24));
4458 uint32_t vr = (uint32_t)(right * (1 << 24));
4459
4460 // Delegate volume control to effect in track effect chain if needed
4461 // only one effect chain can be present on DirectOutputThread, so if
4462 // there is one, the track is connected to it
4463 if (!mEffectChains.isEmpty()) {
4464 mEffectChains[0]->setVolume_l(&vl, &vr);
4465 left = (float)vl / (1 << 24);
4466 right = (float)vr / (1 << 24);
4467 }
4468 if (mOutput->stream->set_volume) {
4469 mOutput->stream->set_volume(mOutput->stream, left, right);
4470 }
4471 }
4472 }
4473}
4474
Phil Burk43b4dcc2015-06-09 16:53:44 -07004475void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
4476{
4477 sp<Track> previousTrack = mPreviousTrack.promote();
4478 sp<Track> latestTrack = mLatestActiveTrack.promote();
4479
4480 if (previousTrack != 0 && latestTrack != 0 &&
4481 (previousTrack->sessionId() != latestTrack->sessionId())) {
4482 mFlushPending = true;
4483 }
4484 PlaybackThread::onAddNewTrack_l();
4485}
Eric Laurentbfb1b832013-01-07 09:53:42 -08004486
Eric Laurent81784c32012-11-19 14:55:58 -08004487AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4488 Vector< sp<Track> > *tracksToRemove
4489)
4490{
Eric Laurentd595b7c2013-04-03 17:27:56 -07004491 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08004492 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004493 bool doHwPause = false;
4494 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004495
4496 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07004497 for (size_t i = 0; i < count; i++) {
4498 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08004499 // The track died recently
4500 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004501 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08004502 }
4503
Phil Burk43b4dcc2015-06-09 16:53:44 -07004504 if (t->isInvalid()) {
4505 ALOGW("An invalidated track shouldn't be in active list");
4506 tracksToRemove->add(t);
4507 continue;
4508 }
4509
Eric Laurent81784c32012-11-19 14:55:58 -08004510 Track* const track = t.get();
4511 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07004512 // Only consider last track started for volume and mixer state control.
4513 // In theory an older track could underrun and restart after the new one starts
4514 // but as we only care about the transition phase between two tracks on a
4515 // direct output, it is not a problem to ignore the underrun case.
4516 sp<Track> l = mLatestActiveTrack.promote();
4517 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08004518
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004519 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004520 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004521 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004522 doHwPause = true;
4523 mHwPaused = true;
4524 }
4525 tracksToRemove->add(track);
4526 } else if (track->isFlushPending()) {
4527 track->flushAck();
4528 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004529 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004530 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004531 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004532 track->resumeAck();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004533 if (last && mHwPaused) {
4534 doHwResume = true;
4535 mHwPaused = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004536 }
4537 }
4538
Eric Laurent81784c32012-11-19 14:55:58 -08004539 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08004540 // for all its buffers to be filled before processing it.
4541 // Allow draining the buffer in case the client
4542 // app does not call stop() and relies on underrun to stop:
4543 // hence the test on (track->mRetryCount > 1).
4544 // If retryCount<=1 then track is about to underrun and be removed.
Eric Laurent81784c32012-11-19 14:55:58 -08004545 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08004546 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
4547 && (track->mRetryCount > 1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004548 minFrames = mNormalFrameCount;
4549 } else {
4550 minFrames = 1;
4551 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004552
Eric Laurentab5cdba2014-06-09 17:22:27 -07004553 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4554 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08004555 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004556 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08004557
4558 if (track->mFillingUpStatus == Track::FS_FILLED) {
4559 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004560 // make sure processVolume_l() will apply new volume even if 0
4561 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004562 if (!mHwSupportsPause) {
4563 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08004564 }
4565 }
4566
4567 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004568 processVolume_l(track, last);
4569 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004570 sp<Track> previousTrack = mPreviousTrack.promote();
4571 if (previousTrack != 0) {
4572 if (track != previousTrack.get()) {
4573 // Flush any data still being written from last track
4574 mBytesRemaining = 0;
4575 // flush data already sent if changing audio session as audio
4576 // comes from a different source. Also invalidate previous track to force a
4577 // seek when resuming.
4578 if (previousTrack->sessionId() != track->sessionId()) {
4579 previousTrack->invalidate();
4580 }
4581 }
4582 }
4583 mPreviousTrack = track;
4584
Eric Laurentd595b7c2013-04-03 17:27:56 -07004585 // reset retry count
4586 track->mRetryCount = kMaxTrackRetriesDirect;
4587 mActiveTrack = t;
4588 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07004589 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004590 doHwResume = true;
4591 mHwPaused = false;
4592 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004593 }
Eric Laurent81784c32012-11-19 14:55:58 -08004594 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004595 // clear effect chain input buffer if the last active track started underruns
4596 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07004597 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004598 mEffectChains[0]->clearInputBuffer();
4599 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004600 if (track->isStopping_1()) {
4601 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07004602 if (last && mHwPaused) {
4603 doHwResume = true;
4604 mHwPaused = false;
4605 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004606 }
4607 if ((track->sharedBuffer() != 0) || track->isStopped() ||
4608 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004609 // We have consumed all the buffers of this track.
4610 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07004611 size_t audioHALFrames;
4612 if (audio_is_linear_pcm(mFormat)) {
4613 audioHALFrames = (latency_l() * mSampleRate) / 1000;
4614 } else {
4615 audioHALFrames = 0;
4616 }
4617
Eric Laurent81784c32012-11-19 14:55:58 -08004618 size_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07004619 if (mStandby || !last ||
4620 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004621 if (track->isStopping_2()) {
4622 track->mState = TrackBase::STOPPED;
4623 }
Eric Laurent81784c32012-11-19 14:55:58 -08004624 if (track->isStopped()) {
4625 track->reset();
4626 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004627 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08004628 }
4629 } else {
4630 // No buffers for this track. Give it a few chances to
4631 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07004632 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08004633 if (--(track->mRetryCount) <= 0) {
4634 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07004635 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004636 // indicate to client process that the track was disabled because of underrun;
4637 // it will then automatically call start() when data is available
4638 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004639 } else if (last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004640 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07004641 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004642 doHwPause = true;
4643 mHwPaused = true;
4644 }
Eric Laurent81784c32012-11-19 14:55:58 -08004645 }
4646 }
4647 }
4648 }
4649
Eric Laurentd1f69b02014-12-15 14:33:13 -08004650 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07004651 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004652 for (size_t i = 0; i < mTracks.size(); i++) {
4653 if (mTracks[i]->isFlushPending()) {
4654 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004655 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004656 }
4657 }
4658 }
4659
4660 // make sure the pause/flush/resume sequence is executed in the right order.
4661 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4662 // before flush and then resume HW. This can happen in case of pause/flush/resume
4663 // if resume is received before pause is executed.
4664 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07004665 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004666 mOutput->stream->pause(mOutput->stream);
4667 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004668 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004669 flushHw_l();
4670 }
4671 if (mHwSupportsPause && !mStandby && doHwResume) {
4672 mOutput->stream->resume(mOutput->stream);
4673 }
Eric Laurent81784c32012-11-19 14:55:58 -08004674 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004675 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004676
4677 return mixerStatus;
4678}
4679
4680void AudioFlinger::DirectOutputThread::threadLoop_mix()
4681{
Eric Laurent81784c32012-11-19 14:55:58 -08004682 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08004683 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004684 // output audio to hardware
4685 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07004686 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004687 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08004688 status_t status = mActiveTrack->getNextBuffer(&buffer);
4689 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08004690 memset(curBuf, 0, frameCount * mFrameSize);
4691 break;
4692 }
4693 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
4694 frameCount -= buffer.frameCount;
4695 curBuf += buffer.frameCount * mFrameSize;
4696 mActiveTrack->releaseBuffer(&buffer);
4697 }
Andy Hung2098f272014-02-27 14:00:06 -08004698 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004699 mSleepTimeUs = 0;
4700 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08004701 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004702}
4703
4704void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
4705{
Eric Laurentd1f69b02014-12-15 14:33:13 -08004706 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004707 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004708 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004709 return;
4710 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004711 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004712 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004713 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004714 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004715 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004716 }
4717 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08004718 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004719 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004720 }
4721}
4722
Eric Laurentd1f69b02014-12-15 14:33:13 -08004723void AudioFlinger::DirectOutputThread::threadLoop_exit()
4724{
4725 {
4726 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08004727 for (size_t i = 0; i < mTracks.size(); i++) {
4728 if (mTracks[i]->isFlushPending()) {
4729 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004730 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004731 }
4732 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004733 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004734 flushHw_l();
4735 }
4736 }
4737 PlaybackThread::threadLoop_exit();
4738}
4739
4740// must be called with thread mutex locked
4741bool AudioFlinger::DirectOutputThread::shouldStandby_l()
4742{
4743 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07004744 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004745
4746 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4747 // after a timeout and we will enter standby then.
4748 if (mTracks.size() > 0) {
4749 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07004750 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
4751 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004752 }
4753
Eric Laurent5cff4032015-05-26 13:49:58 -07004754 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08004755}
4756
Eric Laurent81784c32012-11-19 14:55:58 -08004757// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004758int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Andy Hunge8a1ced2014-05-09 15:02:21 -07004759 audio_format_t format __unused, int sessionId __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004760{
4761 return 0;
4762}
4763
4764// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004765void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004766{
4767}
4768
Eric Laurent10351942014-05-08 18:49:52 -07004769// checkForNewParameter_l() must be called with ThreadBase::mLock held
4770bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
4771 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004772{
4773 bool reconfig = false;
4774
Eric Laurent10351942014-05-08 18:49:52 -07004775 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004776
Eric Laurent10351942014-05-08 18:49:52 -07004777 AudioParameter param = AudioParameter(keyValuePair);
4778 int value;
4779 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4780 // forward device change to effects that have requested to be
4781 // aware of attached audio device.
4782 if (value != AUDIO_DEVICE_NONE) {
4783 mOutDevice = value;
4784 for (size_t i = 0; i < mEffectChains.size(); i++) {
4785 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07004786 }
4787 }
Eric Laurent81784c32012-11-19 14:55:58 -08004788 }
Eric Laurent10351942014-05-08 18:49:52 -07004789 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4790 // do not accept frame count changes if tracks are open as the track buffer
4791 // size depends on frame count and correct behavior would not be garantied
4792 // if frame count is changed after track creation
4793 if (!mTracks.isEmpty()) {
4794 status = INVALID_OPERATION;
4795 } else {
4796 reconfig = true;
4797 }
4798 }
4799 if (status == NO_ERROR) {
4800 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4801 keyValuePair.string());
4802 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004803 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004804 mStandby = true;
4805 mBytesWritten = 0;
4806 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4807 keyValuePair.string());
4808 }
4809 if (status == NO_ERROR && reconfig) {
4810 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07004811 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004812 }
4813 }
4814
Eric Laurent81784c32012-11-19 14:55:58 -08004815 return reconfig;
4816}
4817
4818uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
4819{
4820 uint32_t time;
4821 if (audio_is_linear_pcm(mFormat)) {
4822 time = PlaybackThread::activeSleepTimeUs();
4823 } else {
4824 time = 10000;
4825 }
4826 return time;
4827}
4828
4829uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
4830{
4831 uint32_t time;
4832 if (audio_is_linear_pcm(mFormat)) {
4833 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
4834 } else {
4835 time = 10000;
4836 }
4837 return time;
4838}
4839
4840uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
4841{
4842 uint32_t time;
4843 if (audio_is_linear_pcm(mFormat)) {
4844 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
4845 } else {
4846 time = 10000;
4847 }
4848 return time;
4849}
4850
4851void AudioFlinger::DirectOutputThread::cacheParameters_l()
4852{
4853 PlaybackThread::cacheParameters_l();
4854
4855 // use shorter standby delay as on normal output to release
4856 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07004857 // no delay on outputs with HW A/V sync
4858 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004859 mStandbyDelayNs = 0;
Eric Laurent5cff4032015-05-26 13:49:58 -07004860 } else if ((mType == OFFLOAD) && !audio_is_linear_pcm(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004861 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07004862 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004863 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07004864 }
Eric Laurent81784c32012-11-19 14:55:58 -08004865}
4866
Eric Laurente659ef42014-09-29 13:06:46 -07004867void AudioFlinger::DirectOutputThread::flushHw_l()
4868{
Phil Burk062e67a2015-02-11 13:40:50 -08004869 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08004870 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07004871 mFlushPending = false;
Eric Laurente659ef42014-09-29 13:06:46 -07004872}
4873
Eric Laurent81784c32012-11-19 14:55:58 -08004874// ----------------------------------------------------------------------------
4875
Eric Laurentbfb1b832013-01-07 09:53:42 -08004876AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07004877 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004878 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07004879 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07004880 mWriteAckSequence(0),
4881 mDrainSequence(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004882{
4883}
4884
4885AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
4886{
4887}
4888
4889void AudioFlinger::AsyncCallbackThread::onFirstRef()
4890{
4891 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
4892}
4893
4894bool AudioFlinger::AsyncCallbackThread::threadLoop()
4895{
4896 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004897 uint32_t writeAckSequence;
4898 uint32_t drainSequence;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004899
4900 {
4901 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08004902 while (!((mWriteAckSequence & 1) ||
4903 (mDrainSequence & 1) ||
4904 exitPending())) {
4905 mWaitWorkCV.wait(mLock);
4906 }
4907
Eric Laurentbfb1b832013-01-07 09:53:42 -08004908 if (exitPending()) {
4909 break;
4910 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004911 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
4912 mWriteAckSequence, mDrainSequence);
4913 writeAckSequence = mWriteAckSequence;
4914 mWriteAckSequence &= ~1;
4915 drainSequence = mDrainSequence;
4916 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004917 }
4918 {
Eric Laurent4de95592013-09-26 15:28:21 -07004919 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
4920 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004921 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004922 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004923 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004924 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004925 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004926 }
4927 }
4928 }
4929 }
4930 return false;
4931}
4932
4933void AudioFlinger::AsyncCallbackThread::exit()
4934{
4935 ALOGV("AsyncCallbackThread::exit");
4936 Mutex::Autolock _l(mLock);
4937 requestExit();
4938 mWaitWorkCV.broadcast();
4939}
4940
Eric Laurent3b4529e2013-09-05 18:09:19 -07004941void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004942{
4943 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004944 // bit 0 is cleared
4945 mWriteAckSequence = sequence << 1;
4946}
4947
4948void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
4949{
4950 Mutex::Autolock _l(mLock);
4951 // ignore unexpected callbacks
4952 if (mWriteAckSequence & 2) {
4953 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004954 mWaitWorkCV.signal();
4955 }
4956}
4957
Eric Laurent3b4529e2013-09-05 18:09:19 -07004958void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004959{
4960 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004961 // bit 0 is cleared
4962 mDrainSequence = sequence << 1;
4963}
4964
4965void AudioFlinger::AsyncCallbackThread::resetDraining()
4966{
4967 Mutex::Autolock _l(mLock);
4968 // ignore unexpected callbacks
4969 if (mDrainSequence & 2) {
4970 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004971 mWaitWorkCV.signal();
4972 }
4973}
4974
4975
4976// ----------------------------------------------------------------------------
4977AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07004978 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady)
4979 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady),
Eric Laurentd7e59222013-11-15 12:02:28 -08004980 mPausedBytesRemaining(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004981{
Eric Laurentfd477972013-10-25 18:10:40 -07004982 //FIXME: mStandby should be set to true by ThreadBase constructor
4983 mStandby = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004984}
4985
Eric Laurentbfb1b832013-01-07 09:53:42 -08004986void AudioFlinger::OffloadThread::threadLoop_exit()
4987{
4988 if (mFlushPending || mHwPaused) {
4989 // If a flush is pending or track was paused, just discard buffered data
4990 flushHw_l();
4991 } else {
4992 mMixerStatus = MIXER_DRAIN_ALL;
4993 threadLoop_drain();
4994 }
Uday Gupta56604aa2014-05-13 11:19:17 -07004995 if (mUseAsyncWrite) {
4996 ALOG_ASSERT(mCallbackThread != 0);
4997 mCallbackThread->exit();
4998 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004999 PlaybackThread::threadLoop_exit();
5000}
5001
5002AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
5003 Vector< sp<Track> > *tracksToRemove
5004)
5005{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005006 size_t count = mActiveTracks.size();
5007
5008 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07005009 bool doHwPause = false;
5010 bool doHwResume = false;
5011
Eric Laurentede6c3b2013-09-19 14:37:46 -07005012 ALOGV("OffloadThread::prepareTracks_l active tracks %d", count);
5013
Eric Laurentbfb1b832013-01-07 09:53:42 -08005014 // find out which tracks need to be processed
5015 for (size_t i = 0; i < count; i++) {
5016 sp<Track> t = mActiveTracks[i].promote();
5017 // The track died recently
5018 if (t == 0) {
5019 continue;
5020 }
5021 Track* const track = t.get();
5022 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07005023 // Only consider last track started for volume and mixer state control.
5024 // In theory an older track could underrun and restart after the new one starts
5025 // but as we only care about the transition phase between two tracks on a
5026 // direct output, it is not a problem to ignore the underrun case.
5027 sp<Track> l = mLatestActiveTrack.promote();
5028 bool last = l.get() == track;
5029
Haynes Mathew George7844f672014-01-15 12:32:55 -08005030 if (track->isInvalid()) {
5031 ALOGW("An invalidated track shouldn't be in active list");
5032 tracksToRemove->add(track);
5033 continue;
5034 }
5035
5036 if (track->mState == TrackBase::IDLE) {
5037 ALOGW("An idle track shouldn't be in active list");
5038 continue;
5039 }
5040
Eric Laurentbfb1b832013-01-07 09:53:42 -08005041 if (track->isPausing()) {
5042 track->setPaused();
5043 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07005044 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07005045 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005046 mHwPaused = true;
5047 }
5048 // If we were part way through writing the mixbuffer to
5049 // the HAL we must save this until we resume
5050 // BUG - this will be wrong if a different track is made active,
5051 // in that case we want to discard the pending data in the
5052 // mixbuffer and tell the client to present it again when the
5053 // track is resumed
5054 mPausedWriteLength = mCurrentWriteLength;
5055 mPausedBytesRemaining = mBytesRemaining;
5056 mBytesRemaining = 0; // stop writing
5057 }
5058 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08005059 } else if (track->isFlushPending()) {
5060 track->flushAck();
5061 if (last) {
5062 mFlushPending = true;
5063 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005064 } else if (track->isResumePending()){
5065 track->resumeAck();
5066 if (last) {
5067 if (mPausedBytesRemaining) {
5068 // Need to continue write that was interrupted
5069 mCurrentWriteLength = mPausedWriteLength;
5070 mBytesRemaining = mPausedBytesRemaining;
5071 mPausedBytesRemaining = 0;
5072 }
5073 if (mHwPaused) {
5074 doHwResume = true;
5075 mHwPaused = false;
5076 // threadLoop_mix() will handle the case that we need to
5077 // resume an interrupted write
5078 }
5079 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005080 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005081
5082 // Do not handle new data in this iteration even if track->framesReady()
5083 mixerStatus = MIXER_TRACKS_ENABLED;
5084 }
5085 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07005086 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005087 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005088 if (track->mFillingUpStatus == Track::FS_FILLED) {
5089 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07005090 // make sure processVolume_l() will apply new volume even if 0
5091 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005092 }
5093
5094 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08005095 sp<Track> previousTrack = mPreviousTrack.promote();
5096 if (previousTrack != 0) {
5097 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08005098 // Flush any data still being written from last track
5099 mBytesRemaining = 0;
5100 if (mPausedBytesRemaining) {
5101 // Last track was paused so we also need to flush saved
5102 // mixbuffer state and invalidate track so that it will
5103 // re-submit that unwritten data when it is next resumed
5104 mPausedBytesRemaining = 0;
5105 // Invalidate is a bit drastic - would be more efficient
5106 // to have a flag to tell client that some of the
5107 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08005108 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005109 }
5110 // flush data already sent to the DSP if changing audio session as audio
5111 // comes from a different source. Also invalidate previous track to force a
5112 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08005113 if (previousTrack->sessionId() != track->sessionId()) {
5114 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005115 }
5116 }
5117 }
5118 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005119 // reset retry count
5120 track->mRetryCount = kMaxTrackRetriesOffload;
5121 mActiveTrack = t;
5122 mixerStatus = MIXER_TRACKS_READY;
5123 }
5124 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005125 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005126 if (track->isStopping_1()) {
5127 // Hardware buffer can hold a large amount of audio so we must
5128 // wait for all current track's data to drain before we say
5129 // that the track is stopped.
5130 if (mBytesRemaining == 0) {
5131 // Only start draining when all data in mixbuffer
5132 // has been written
5133 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
5134 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005135 // do not drain if no data was ever sent to HAL (mStandby == true)
5136 if (last && !mStandby) {
Eric Laurent1b9f9b12013-11-12 19:10:17 -08005137 // do not modify drain sequence if we are already draining. This happens
5138 // when resuming from pause after drain.
5139 if ((mDrainSequence & 1) == 0) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005140 mSleepTimeUs = 0;
5141 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent1b9f9b12013-11-12 19:10:17 -08005142 mixerStatus = MIXER_DRAIN_TRACK;
5143 mDrainSequence += 2;
5144 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005145 if (mHwPaused) {
5146 // It is possible to move from PAUSED to STOPPING_1 without
5147 // a resume so we must ensure hardware is running
Eric Laurent1b9f9b12013-11-12 19:10:17 -08005148 doHwResume = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005149 mHwPaused = false;
5150 }
5151 }
5152 }
5153 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005154 // Drain has completed or we are in standby, signal presentation complete
5155 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005156 track->mState = TrackBase::STOPPED;
5157 size_t audioHALFrames =
5158 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
5159 size_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08005160 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005161 track->presentationComplete(framesWritten, audioHALFrames);
5162 track->reset();
5163 tracksToRemove->add(track);
5164 }
5165 } else {
5166 // No buffers for this track. Give it a few chances to
5167 // fill a buffer, then remove it from active list.
5168 if (--(track->mRetryCount) <= 0) {
5169 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
5170 track->name());
5171 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08005172 // indicate to client process that the track was disabled because of underrun;
5173 // it will then automatically call start() when data is available
5174 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005175 } else if (last){
5176 mixerStatus = MIXER_TRACKS_ENABLED;
5177 }
5178 }
5179 }
5180 // compute volume for this track
5181 processVolume_l(track, last);
5182 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005183
Eric Laurentea0fade2013-10-04 16:23:48 -07005184 // make sure the pause/flush/resume sequence is executed in the right order.
5185 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5186 // before flush and then resume HW. This can happen in case of pause/flush/resume
5187 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07005188 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurent972a1732013-09-04 09:42:59 -07005189 mOutput->stream->pause(mOutput->stream);
5190 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005191 if (mFlushPending) {
5192 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005193 }
Eric Laurentfd477972013-10-25 18:10:40 -07005194 if (!mStandby && doHwResume) {
Eric Laurent972a1732013-09-04 09:42:59 -07005195 mOutput->stream->resume(mOutput->stream);
5196 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005197
Eric Laurentbfb1b832013-01-07 09:53:42 -08005198 // remove all the tracks that need to be...
5199 removeTracks_l(*tracksToRemove);
5200
5201 return mixerStatus;
5202}
5203
Eric Laurentbfb1b832013-01-07 09:53:42 -08005204// must be called with thread mutex locked
5205bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
5206{
Eric Laurent3b4529e2013-09-05 18:09:19 -07005207 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
5208 mWriteAckSequence, mDrainSequence);
5209 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005210 return true;
5211 }
5212 return false;
5213}
5214
Eric Laurentbfb1b832013-01-07 09:53:42 -08005215bool AudioFlinger::OffloadThread::waitingAsyncCallback()
5216{
5217 Mutex::Autolock _l(mLock);
5218 return waitingAsyncCallback_l();
5219}
5220
5221void AudioFlinger::OffloadThread::flushHw_l()
5222{
Eric Laurente659ef42014-09-29 13:06:46 -07005223 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005224 // Flush anything still waiting in the mixbuffer
5225 mCurrentWriteLength = 0;
5226 mBytesRemaining = 0;
5227 mPausedWriteLength = 0;
5228 mPausedBytesRemaining = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08005229
Eric Laurentbfb1b832013-01-07 09:53:42 -08005230 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005231 // discard any pending drain or write ack by incrementing sequence
5232 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5233 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005234 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005235 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5236 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005237 }
5238}
5239
5240// ----------------------------------------------------------------------------
5241
Eric Laurent81784c32012-11-19 14:55:58 -08005242AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07005243 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08005244 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
Eric Laurent72e3f392015-05-20 14:43:50 -07005245 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08005246 mWaitTimeMs(UINT_MAX)
5247{
5248 addOutputTrack(mainThread);
5249}
5250
5251AudioFlinger::DuplicatingThread::~DuplicatingThread()
5252{
5253 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5254 mOutputTracks[i]->destroy();
5255 }
5256}
5257
5258void AudioFlinger::DuplicatingThread::threadLoop_mix()
5259{
5260 // mix buffers...
5261 if (outputsReady(outputTracks)) {
5262 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
5263 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08005264 if (mMixerBufferValid) {
5265 memset(mMixerBuffer, 0, mMixerBufferSize);
5266 } else {
5267 memset(mSinkBuffer, 0, mSinkBufferSize);
5268 }
Eric Laurent81784c32012-11-19 14:55:58 -08005269 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005270 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005271 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005272 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005273 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005274}
5275
5276void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
5277{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005278 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005279 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005280 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005281 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005282 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005283 }
5284 } else if (mBytesWritten != 0) {
5285 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5286 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005287 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005288 } else {
5289 // flush remaining overflow buffers in output tracks
5290 writeFrames = 0;
5291 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005292 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005293 }
5294}
5295
Eric Laurentbfb1b832013-01-07 09:53:42 -08005296ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005297{
5298 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08005299 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005300 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07005301 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08005302 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005303}
5304
5305void AudioFlinger::DuplicatingThread::threadLoop_standby()
5306{
5307 // DuplicatingThread implements standby by stopping all tracks
5308 for (size_t i = 0; i < outputTracks.size(); i++) {
5309 outputTracks[i]->stop();
5310 }
5311}
5312
5313void AudioFlinger::DuplicatingThread::saveOutputTracks()
5314{
5315 outputTracks = mOutputTracks;
5316}
5317
5318void AudioFlinger::DuplicatingThread::clearOutputTracks()
5319{
5320 outputTracks.clear();
5321}
5322
5323void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
5324{
5325 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08005326 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
5327 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
5328 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
5329 const size_t frameCount =
5330 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
5331 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
5332 // from different OutputTracks and their associated MixerThreads (e.g. one may
5333 // nearly empty and the other may be dropping data).
5334
5335 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08005336 this,
5337 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08005338 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08005339 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005340 frameCount,
5341 IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08005342 if (outputTrack->cblk() != NULL) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005343 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
Eric Laurent81784c32012-11-19 14:55:58 -08005344 mOutputTracks.add(outputTrack);
Andy Hungc25b84a2015-01-14 19:04:10 -08005345 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005346 updateWaitTime_l();
5347 }
5348}
5349
5350void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
5351{
5352 Mutex::Autolock _l(mLock);
5353 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5354 if (mOutputTracks[i]->thread() == thread) {
5355 mOutputTracks[i]->destroy();
5356 mOutputTracks.removeAt(i);
5357 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07005358 if (thread->getOutput() == mOutput) {
5359 mOutput = NULL;
5360 }
Eric Laurent81784c32012-11-19 14:55:58 -08005361 return;
5362 }
5363 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07005364 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005365}
5366
5367// caller must hold mLock
5368void AudioFlinger::DuplicatingThread::updateWaitTime_l()
5369{
5370 mWaitTimeMs = UINT_MAX;
5371 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5372 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
5373 if (strong != 0) {
5374 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
5375 if (waitTimeMs < mWaitTimeMs) {
5376 mWaitTimeMs = waitTimeMs;
5377 }
5378 }
5379 }
5380}
5381
5382
5383bool AudioFlinger::DuplicatingThread::outputsReady(
5384 const SortedVector< sp<OutputTrack> > &outputTracks)
5385{
5386 for (size_t i = 0; i < outputTracks.size(); i++) {
5387 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
5388 if (thread == 0) {
5389 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
5390 outputTracks[i].get());
5391 return false;
5392 }
5393 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5394 // see note at standby() declaration
5395 if (playbackThread->standby() && !playbackThread->isSuspended()) {
5396 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
5397 thread.get());
5398 return false;
5399 }
5400 }
5401 return true;
5402}
5403
5404uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
5405{
5406 return (mWaitTimeMs * 1000) / 2;
5407}
5408
5409void AudioFlinger::DuplicatingThread::cacheParameters_l()
5410{
5411 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
5412 updateWaitTime_l();
5413
5414 MixerThread::cacheParameters_l();
5415}
5416
5417// ----------------------------------------------------------------------------
5418// Record
5419// ----------------------------------------------------------------------------
5420
5421AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5422 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08005423 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08005424 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07005425 audio_devices_t inDevice,
5426 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08005427#ifdef TEE_SINK
5428 , const sp<NBAIO_Sink>& teeSink
5429#endif
5430 ) :
Eric Laurent72e3f392015-05-20 14:43:50 -07005431 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005432 mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005433 // mRsmpInFrames and mRsmpInFramesP2 are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005434 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08005435#ifdef TEE_SINK
5436 , mTeeSink(teeSink)
5437#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07005438 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
5439 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005440 // mFastCapture below
5441 , mFastCaptureFutex(0)
5442 // mInputSource
5443 // mPipeSink
5444 // mPipeSource
5445 , mPipeFramesP2(0)
5446 // mPipeMemory
5447 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005448 , mFastTrackAvail(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005449{
Glenn Kastend7dca052015-03-05 16:05:54 -08005450 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
5451 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08005452
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005453 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005454
5455 // create an NBAIO source for the HAL input stream, and negotiate
5456 mInputSource = new AudioStreamInSource(input->stream);
5457 size_t numCounterOffers = 0;
5458 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
5459 ssize_t index = mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
5460 ALOG_ASSERT(index == 0);
5461
5462 // initialize fast capture depending on configuration
5463 bool initFastCapture;
5464 switch (kUseFastCapture) {
5465 case FastCapture_Never:
5466 initFastCapture = false;
5467 break;
5468 case FastCapture_Always:
5469 initFastCapture = true;
5470 break;
5471 case FastCapture_Static:
5472 uint32_t primaryOutputSampleRate;
5473 {
5474 AutoMutex _l(audioFlinger->mHardwareLock);
5475 primaryOutputSampleRate = audioFlinger->mPrimaryOutputSampleRate;
5476 }
5477 initFastCapture =
5478 // either capture sample rate is same as (a reasonable) primary output sample rate
Andy Hungdb4c0312015-05-06 08:46:52 -07005479 ((isMusicRate(primaryOutputSampleRate) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005480 (mSampleRate == primaryOutputSampleRate)) ||
5481 // or primary output sample rate is unknown, and capture sample rate is reasonable
5482 ((primaryOutputSampleRate == 0) &&
Andy Hungdb4c0312015-05-06 08:46:52 -07005483 isMusicRate(mSampleRate))) &&
Glenn Kasten9f81de32014-07-27 15:02:23 -07005484 // and the buffer size is < 12 ms
5485 (mFrameCount * 1000) / mSampleRate < 12;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005486 break;
5487 // case FastCapture_Dynamic:
5488 }
5489
5490 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07005491 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005492 NBAIO_Format format = mInputSource->format();
Glenn Kasten49d00ad2014-07-21 11:22:03 -07005493 size_t pipeFramesP2 = roundup(mSampleRate / 25); // double-buffering of 20 ms each
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005494 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
5495 void *pipeBuffer;
5496 const sp<MemoryDealer> roHeap(readOnlyHeap());
5497 sp<IMemory> pipeMemory;
5498 if ((roHeap == 0) ||
5499 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
5500 (pipeBuffer = pipeMemory->pointer()) == NULL) {
5501 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
5502 goto failed;
5503 }
5504 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
5505 memset(pipeBuffer, 0, pipeSize);
5506 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
5507 const NBAIO_Format offers[1] = {format};
5508 size_t numCounterOffers = 0;
5509 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
5510 ALOG_ASSERT(index == 0);
5511 mPipeSink = pipe;
5512 PipeReader *pipeReader = new PipeReader(*pipe);
5513 numCounterOffers = 0;
5514 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
5515 ALOG_ASSERT(index == 0);
5516 mPipeSource = pipeReader;
5517 mPipeFramesP2 = pipeFramesP2;
5518 mPipeMemory = pipeMemory;
5519
5520 // create fast capture
5521 mFastCapture = new FastCapture();
5522 FastCaptureStateQueue *sq = mFastCapture->sq();
5523#ifdef STATE_QUEUE_DUMP
5524 // FIXME
5525#endif
5526 FastCaptureState *state = sq->begin();
5527 state->mCblk = NULL;
5528 state->mInputSource = mInputSource.get();
5529 state->mInputSourceGen++;
5530 state->mPipeSink = pipe;
5531 state->mPipeSinkGen++;
5532 state->mFrameCount = mFrameCount;
5533 state->mCommand = FastCaptureState::COLD_IDLE;
5534 // already done in constructor initialization list
5535 //mFastCaptureFutex = 0;
5536 state->mColdFutexAddr = &mFastCaptureFutex;
5537 state->mColdGen++;
5538 state->mDumpState = &mFastCaptureDumpState;
5539#ifdef TEE_SINK
5540 // FIXME
5541#endif
5542 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
5543 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
5544 sq->end();
5545 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5546
5547 // start the fast capture
5548 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
5549 pid_t tid = mFastCapture->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07005550 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005551#ifdef AUDIO_WATCHDOG
5552 // FIXME
5553#endif
5554
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005555 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005556 }
5557failed: ;
5558
5559 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08005560}
5561
Eric Laurent81784c32012-11-19 14:55:58 -08005562AudioFlinger::RecordThread::~RecordThread()
5563{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005564 if (mFastCapture != 0) {
5565 FastCaptureStateQueue *sq = mFastCapture->sq();
5566 FastCaptureState *state = sq->begin();
5567 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5568 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5569 if (old == -1) {
5570 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5571 }
5572 }
5573 state->mCommand = FastCaptureState::EXIT;
5574 sq->end();
5575 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5576 mFastCapture->join();
5577 mFastCapture.clear();
5578 }
5579 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07005580 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07005581 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08005582}
5583
5584void AudioFlinger::RecordThread::onFirstRef()
5585{
Glenn Kastend7dca052015-03-05 16:05:54 -08005586 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08005587}
5588
Eric Laurent81784c32012-11-19 14:55:58 -08005589bool AudioFlinger::RecordThread::threadLoop()
5590{
Eric Laurent81784c32012-11-19 14:55:58 -08005591 nsecs_t lastWarning = 0;
5592
5593 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08005594
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005595reacquire_wakelock:
5596 sp<RecordTrack> activeTrack;
Glenn Kasten2b806402013-11-20 16:37:38 -08005597 int activeTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005598 {
5599 Mutex::Autolock _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005600 size_t size = mActiveTracks.size();
5601 activeTracksGen = mActiveTracksGen;
5602 if (size > 0) {
5603 // FIXME an arbitrary choice
5604 activeTrack = mActiveTracks[0];
5605 acquireWakeLock_l(activeTrack->uid());
5606 if (size > 1) {
5607 SortedVector<int> tmp;
5608 for (size_t i = 0; i < size; i++) {
5609 tmp.add(mActiveTracks[i]->uid());
5610 }
5611 updateWakeLockUids_l(tmp);
5612 }
5613 } else {
5614 acquireWakeLock_l(-1);
5615 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005616 }
5617
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005618 // used to request a deferred sleep, to be executed later while mutex is unlocked
5619 uint32_t sleepUs = 0;
5620
5621 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005622 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005623 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07005624
Glenn Kasten5edadd42013-08-14 16:30:49 -07005625 // sleep with mutex unlocked
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005626 if (sleepUs > 0) {
Glenn Kastene7754022014-10-31 12:11:26 -07005627 ATRACE_BEGIN("sleep");
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005628 usleep(sleepUs);
Glenn Kastene7754022014-10-31 12:11:26 -07005629 ATRACE_END();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005630 sleepUs = 0;
Glenn Kasten5edadd42013-08-14 16:30:49 -07005631 }
5632
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005633 // activeTracks accumulates a copy of a subset of mActiveTracks
5634 Vector< sp<RecordTrack> > activeTracks;
5635
Glenn Kasten735f45f2014-08-18 15:51:59 -07005636 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005637 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07005638
Glenn Kasten735f45f2014-08-18 15:51:59 -07005639 // reference to a fast track which is about to be removed
5640 sp<RecordTrack> fastTrackToRemove;
5641
Eric Laurent81784c32012-11-19 14:55:58 -08005642 { // scope for mLock
5643 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08005644
Eric Laurent021cf962014-05-13 10:18:14 -07005645 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005646
Eric Laurent000a4192014-01-29 15:17:32 -08005647 // check exitPending here because checkForNewParameters_l() and
5648 // checkForNewParameters_l() can temporarily release mLock
5649 if (exitPending()) {
5650 break;
5651 }
5652
Glenn Kasten2b806402013-11-20 16:37:38 -08005653 // if no active track(s), then standby and release wakelock
5654 size_t size = mActiveTracks.size();
5655 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07005656 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005657 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08005658 releaseWakeLock_l();
5659 ALOGV("RecordThread: loop stopping");
5660 // go to sleep
5661 mWaitWorkCV.wait(mLock);
5662 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005663 goto reacquire_wakelock;
5664 }
5665
Glenn Kasten2b806402013-11-20 16:37:38 -08005666 if (mActiveTracksGen != activeTracksGen) {
5667 activeTracksGen = mActiveTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005668 SortedVector<int> tmp;
Glenn Kasten2b806402013-11-20 16:37:38 -08005669 for (size_t i = 0; i < size; i++) {
5670 tmp.add(mActiveTracks[i]->uid());
5671 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005672 updateWakeLockUids_l(tmp);
Eric Laurent81784c32012-11-19 14:55:58 -08005673 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005674
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005675 bool doBroadcast = false;
5676 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07005677
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005678 activeTrack = mActiveTracks[i];
5679 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07005680 if (activeTrack->isFastTrack()) {
5681 ALOG_ASSERT(fastTrackToRemove == 0);
5682 fastTrackToRemove = activeTrack;
5683 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005684 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08005685 mActiveTracks.remove(activeTrack);
5686 mActiveTracksGen++;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005687 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07005688 continue;
5689 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005690
5691 TrackBase::track_state activeTrackState = activeTrack->mState;
5692 switch (activeTrackState) {
5693
5694 case TrackBase::PAUSING:
5695 mActiveTracks.remove(activeTrack);
5696 mActiveTracksGen++;
5697 doBroadcast = true;
5698 size--;
5699 continue;
5700
5701 case TrackBase::STARTING_1:
5702 sleepUs = 10000;
5703 i++;
5704 continue;
5705
5706 case TrackBase::STARTING_2:
5707 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005708 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07005709 activeTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005710 break;
5711
5712 case TrackBase::ACTIVE:
5713 break;
5714
5715 case TrackBase::IDLE:
5716 i++;
5717 continue;
5718
5719 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08005720 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07005721 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005722
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005723 activeTracks.add(activeTrack);
5724 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07005725
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005726 if (activeTrack->isFastTrack()) {
5727 ALOG_ASSERT(!mFastTrackAvail);
5728 ALOG_ASSERT(fastTrack == 0);
5729 fastTrack = activeTrack;
5730 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005731 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005732 if (doBroadcast) {
5733 mStartStopCond.broadcast();
5734 }
5735
5736 // sleep if there are no active tracks to process
5737 if (activeTracks.size() == 0) {
5738 if (sleepUs == 0) {
5739 sleepUs = kRecordThreadSleepUs;
5740 }
5741 continue;
5742 }
5743 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07005744
Eric Laurent81784c32012-11-19 14:55:58 -08005745 lockEffectChains_l(effectChains);
5746 }
5747
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005748 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07005749
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005750 size_t size = effectChains.size();
5751 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005752 // thread mutex is not locked, but effect chain is locked
5753 effectChains[i]->process_l();
5754 }
5755
Glenn Kasten735f45f2014-08-18 15:51:59 -07005756 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005757 if (mFastCapture != 0) {
5758 FastCaptureStateQueue *sq = mFastCapture->sq();
5759 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07005760 bool didModify = false;
5761 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005762 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
5763 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
5764 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5765 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5766 if (old == -1) {
5767 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5768 }
5769 }
5770 state->mCommand = FastCaptureState::READ_WRITE;
5771#if 0 // FIXME
5772 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08005773 FastThreadDumpState::kSamplingNforLowRamDevice :
5774 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005775#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07005776 didModify = true;
5777 }
5778 audio_track_cblk_t *cblkOld = state->mCblk;
5779 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
5780 if (cblkNew != cblkOld) {
5781 state->mCblk = cblkNew;
5782 // block until acked if removing a fast track
5783 if (cblkOld != NULL) {
5784 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
5785 }
5786 didModify = true;
5787 }
5788 sq->end(didModify);
5789 if (didModify) {
5790 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005791#if 0
5792 if (kUseFastCapture == FastCapture_Dynamic) {
5793 mNormalSource = mPipeSource;
5794 }
5795#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005796 }
5797 }
5798
Glenn Kasten735f45f2014-08-18 15:51:59 -07005799 // now run the fast track destructor with thread mutex unlocked
5800 fastTrackToRemove.clear();
5801
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005802 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
5803 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
5804 // slow, then this RecordThread will overrun by not calling HAL read often enough.
5805 // If destination is non-contiguous, first read past the nominal end of buffer, then
5806 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005807
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005808 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005809 ssize_t framesRead;
5810
5811 // If an NBAIO source is present, use it to read the normal capture's data
5812 if (mPipeSource != 0) {
5813 size_t framesToRead = mBufferSize / mFrameSize;
Andy Hung57446612015-04-19 23:56:46 -07005814 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005815 framesToRead, AudioBufferProvider::kInvalidPTS);
5816 if (framesRead == 0) {
5817 // since pipe is non-blocking, simulate blocking input
5818 sleepUs = (framesToRead * 1000000LL) / mSampleRate;
5819 }
5820 // otherwise use the HAL / AudioStreamIn directly
5821 } else {
5822 ssize_t bytesRead = mInput->stream->read(mInput->stream,
Andy Hung57446612015-04-19 23:56:46 -07005823 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005824 if (bytesRead < 0) {
5825 framesRead = bytesRead;
5826 } else {
5827 framesRead = bytesRead / mFrameSize;
5828 }
5829 }
5830
5831 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
5832 ALOGE("read failed: framesRead=%d", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005833 // Force input into standby so that it tries to recover at next read attempt
5834 inputStandBy();
5835 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005836 }
5837 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005838 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005839 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005840 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005841
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005842 if (mTeeSink != 0) {
Andy Hung57446612015-04-19 23:56:46 -07005843 (void) mTeeSink->write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005844 }
5845 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005846 {
5847 size_t part1 = mRsmpInFramesP2 - rear;
5848 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07005849 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005850 (framesRead - part1) * mFrameSize);
5851 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005852 }
5853 rear = mRsmpInRear += framesRead;
5854
5855 size = activeTracks.size();
5856 // loop over each active track
5857 for (size_t i = 0; i < size; i++) {
5858 activeTrack = activeTracks[i];
5859
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005860 // skip fast tracks, as those are handled directly by FastCapture
5861 if (activeTrack->isFastTrack()) {
5862 continue;
5863 }
5864
Andy Hung73c02e42015-03-29 01:13:58 -07005865 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07005866 // TODO: Update the activeTrack buffer converter in case of reconfigure.
5867
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005868 enum {
5869 OVERRUN_UNKNOWN,
5870 OVERRUN_TRUE,
5871 OVERRUN_FALSE
5872 } overrun = OVERRUN_UNKNOWN;
5873
5874 // loop over getNextBuffer to handle circular sink
5875 for (;;) {
5876
5877 activeTrack->mSink.frameCount = ~0;
5878 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
5879 size_t framesOut = activeTrack->mSink.frameCount;
5880 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
5881
Andy Hung73c02e42015-03-29 01:13:58 -07005882 // check available frames and handle overrun conditions
5883 // if the record track isn't draining fast enough.
5884 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005885 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07005886 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
5887 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005888 overrun = OVERRUN_TRUE;
5889 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005890 if (framesOut == 0 || framesIn == 0) {
5891 break;
5892 }
5893
Andy Hung6770c6f2015-04-07 13:43:36 -07005894 // Don't allow framesOut to be larger than what is possible with resampling
5895 // from framesIn.
5896 // This isn't strictly necessary but helps limit buffer resizing in
5897 // RecordBufferConverter. TODO: remove when no longer needed.
5898 framesOut = min(framesOut,
5899 destinationFramesPossible(
5900 framesIn, mSampleRate, activeTrack->mSampleRate));
Andy Hung97a893e2015-03-29 01:03:07 -07005901 // process frames from the RecordThread buffer provider to the RecordTrack buffer
5902 framesOut = activeTrack->mRecordBufferConverter->convert(
5903 activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005904
5905 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
5906 overrun = OVERRUN_FALSE;
5907 }
5908
5909 if (activeTrack->mFramesToDrop == 0) {
5910 if (framesOut > 0) {
5911 activeTrack->mSink.frameCount = framesOut;
5912 activeTrack->releaseBuffer(&activeTrack->mSink);
5913 }
5914 } else {
5915 // FIXME could do a partial drop of framesOut
5916 if (activeTrack->mFramesToDrop > 0) {
5917 activeTrack->mFramesToDrop -= framesOut;
5918 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005919 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005920 }
5921 } else {
5922 activeTrack->mFramesToDrop += framesOut;
5923 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
5924 activeTrack->mSyncStartEvent->isCancelled()) {
5925 ALOGW("Synced record %s, session %d, trigger session %d",
5926 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
5927 activeTrack->sessionId(),
5928 (activeTrack->mSyncStartEvent != 0) ?
5929 activeTrack->mSyncStartEvent->triggerSession() : 0);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005930 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005931 }
5932 }
5933 }
5934
5935 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005936 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005937 }
5938 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005939
5940 switch (overrun) {
5941 case OVERRUN_TRUE:
5942 // client isn't retrieving buffers fast enough
5943 if (!activeTrack->setOverflow()) {
5944 nsecs_t now = systemTime();
5945 // FIXME should lastWarning per track?
5946 if ((now - lastWarning) > kWarningThrottleNs) {
5947 ALOGW("RecordThread: buffer overflow");
5948 lastWarning = now;
5949 }
5950 }
5951 break;
5952 case OVERRUN_FALSE:
5953 activeTrack->clearOverflow();
5954 break;
5955 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005956 break;
5957 }
5958
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005959 }
5960
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005961unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08005962 // enable changes in effect chain
5963 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005964 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08005965 }
5966
Glenn Kasten93e471f2013-08-19 08:40:07 -07005967 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08005968
5969 {
5970 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07005971 for (size_t i = 0; i < mTracks.size(); i++) {
5972 sp<RecordTrack> track = mTracks[i];
5973 track->invalidate();
5974 }
Glenn Kasten2b806402013-11-20 16:37:38 -08005975 mActiveTracks.clear();
5976 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08005977 mStartStopCond.broadcast();
5978 }
5979
5980 releaseWakeLock();
5981
5982 ALOGV("RecordThread %p exiting", this);
5983 return false;
5984}
5985
Glenn Kasten93e471f2013-08-19 08:40:07 -07005986void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08005987{
5988 if (!mStandby) {
5989 inputStandBy();
5990 mStandby = true;
5991 }
5992}
5993
5994void AudioFlinger::RecordThread::inputStandBy()
5995{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005996 // Idle the fast capture if it's currently running
5997 if (mFastCapture != 0) {
5998 FastCaptureStateQueue *sq = mFastCapture->sq();
5999 FastCaptureState *state = sq->begin();
6000 if (!(state->mCommand & FastCaptureState::IDLE)) {
6001 state->mCommand = FastCaptureState::COLD_IDLE;
6002 state->mColdFutexAddr = &mFastCaptureFutex;
6003 state->mColdGen++;
6004 mFastCaptureFutex = 0;
6005 sq->end();
6006 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
6007 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
6008#if 0
6009 if (kUseFastCapture == FastCapture_Dynamic) {
6010 // FIXME
6011 }
6012#endif
6013#ifdef AUDIO_WATCHDOG
6014 // FIXME
6015#endif
6016 } else {
6017 sq->end(false /*didModify*/);
6018 }
6019 }
Eric Laurent81784c32012-11-19 14:55:58 -08006020 mInput->stream->common.standby(&mInput->stream->common);
6021}
6022
Glenn Kasten05997e22014-03-13 15:08:33 -07006023// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07006024sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08006025 const sp<AudioFlinger::Client>& client,
6026 uint32_t sampleRate,
6027 audio_format_t format,
6028 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08006029 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08006030 int sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07006031 size_t *notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08006032 int uid,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07006033 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08006034 pid_t tid,
6035 status_t *status)
6036{
Glenn Kasten74935e42013-12-19 08:56:45 -08006037 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08006038 sp<RecordTrack> track;
6039 status_t lStatus;
6040
Glenn Kasten90e58b12013-07-31 16:16:02 -07006041 // client expresses a preference for FAST, but we get the final say
6042 if (*flags & IAudioFlinger::TRACK_FAST) {
6043 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07006044 // we formerly checked for a callback handler (non-0 tid),
6045 // but that is no longer required for TRANSFER_OBTAIN mode
6046 //
Glenn Kasten74105912014-07-03 12:28:53 -07006047 // frame count is not specified, or is exactly the pipe depth
6048 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006049 // PCM data
6050 audio_is_linear_pcm(format) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006051 // native format
6052 (format == mFormat) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006053 // native channel mask
6054 (channelMask == mChannelMask) &&
6055 // native hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07006056 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006057 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006058 hasFastCapture() &&
6059 // there are sufficient fast track slots available
6060 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07006061 ) {
Glenn Kasten74105912014-07-03 12:28:53 -07006062 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%u mFrameCount=%u",
Glenn Kasten90e58b12013-07-31 16:16:02 -07006063 frameCount, mFrameCount);
6064 } else {
Glenn Kasten74105912014-07-03 12:28:53 -07006065 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%u mFrameCount=%u mPipeFramesP2=%u "
6066 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006067 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Glenn Kasten74105912014-07-03 12:28:53 -07006068 frameCount, mFrameCount, mPipeFramesP2,
6069 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
6070 hasFastCapture(), tid, mFastTrackAvail);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006071 *flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kasten74105912014-07-03 12:28:53 -07006072 }
6073 }
6074
6075 // compute track buffer size in frames, and suggest the notification frame count
6076 if (*flags & IAudioFlinger::TRACK_FAST) {
6077 // fast track: frame count is exactly the pipe depth
6078 frameCount = mPipeFramesP2;
6079 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
6080 *notificationFrames = mFrameCount;
6081 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006082 // not fast track: max notification period is resampled equivalent of one HAL buffer time
6083 // or 20 ms if there is a fast capture
6084 // TODO This could be a roundupRatio inline, and const
6085 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
6086 * sampleRate + mSampleRate - 1) / mSampleRate;
6087 // minimum number of notification periods is at least kMinNotifications,
6088 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
6089 static const size_t kMinNotifications = 3;
6090 static const uint32_t kMinMs = 30;
6091 // TODO This could be a roundupRatio inline
6092 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
6093 // TODO This could be a roundupRatio inline
6094 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
6095 maxNotificationFrames;
6096 const size_t minFrameCount = maxNotificationFrames *
6097 max(kMinNotifications, minNotificationsByMs);
6098 frameCount = max(frameCount, minFrameCount);
6099 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
6100 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07006101 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07006102 }
Glenn Kasten74935e42013-12-19 08:56:45 -08006103 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07006104
Glenn Kasten15e57982013-09-24 11:52:37 -07006105 lStatus = initCheck();
6106 if (lStatus != NO_ERROR) {
6107 ALOGE("createRecordTrack_l() audio driver not initialized");
6108 goto Exit;
6109 }
Eric Laurent81784c32012-11-19 14:55:58 -08006110
6111 { // scope for mLock
6112 Mutex::Autolock _l(mLock);
6113
6114 track = new RecordTrack(this, client, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07006115 format, channelMask, frameCount, NULL, sessionId, uid,
6116 *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08006117
Glenn Kasten03003332013-08-06 15:40:54 -07006118 lStatus = track->initCheck();
6119 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07006120 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08006121 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08006122 goto Exit;
6123 }
6124 mTracks.add(track);
6125
6126 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6127 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6128 mAudioFlinger->btNrecIsOff();
6129 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6130 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006131
6132 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
6133 pid_t callingPid = IPCThreadState::self()->getCallingPid();
6134 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
6135 // so ask activity manager to do this on our behalf
6136 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
6137 }
Eric Laurent81784c32012-11-19 14:55:58 -08006138 }
Glenn Kasten05997e22014-03-13 15:08:33 -07006139
Eric Laurent81784c32012-11-19 14:55:58 -08006140 lStatus = NO_ERROR;
6141
6142Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07006143 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08006144 return track;
6145}
6146
6147status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
6148 AudioSystem::sync_event_t event,
6149 int triggerSession)
6150{
6151 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
6152 sp<ThreadBase> strongMe = this;
6153 status_t status = NO_ERROR;
6154
6155 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006156 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006157 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006158 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08006159 triggerSession,
6160 recordTrack->sessionId(),
6161 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006162 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08006163 // Sync event can be cancelled by the trigger session if the track is not in a
6164 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006165 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006166 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006167 } else {
6168 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006169 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006170 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08006171 }
6172 }
6173
6174 {
Glenn Kasten47c20702013-08-13 15:37:35 -07006175 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08006176 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006177 if (mActiveTracks.indexOf(recordTrack) >= 0) {
6178 if (recordTrack->mState == TrackBase::PAUSING) {
6179 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006180 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006181 } else {
6182 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08006183 }
6184 return status;
6185 }
6186
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006187 // TODO consider other ways of handling this, such as changing the state to :STARTING and
6188 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
6189 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006190 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08006191 mActiveTracks.add(recordTrack);
6192 mActiveTracksGen++;
Eric Laurent83b88082014-06-20 18:31:16 -07006193 status_t status = NO_ERROR;
6194 if (recordTrack->isExternalTrack()) {
6195 mLock.unlock();
Eric Laurent4dc68062014-07-28 17:26:49 -07006196 status = AudioSystem::startInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006197 mLock.lock();
6198 // FIXME should verify that recordTrack is still in mActiveTracks
6199 if (status != NO_ERROR) {
6200 mActiveTracks.remove(recordTrack);
6201 mActiveTracksGen++;
6202 recordTrack->clearSyncStartEvent();
6203 ALOGV("RecordThread::start error %d", status);
6204 return status;
6205 }
Eric Laurent81784c32012-11-19 14:55:58 -08006206 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006207 // Catch up with current buffer indices if thread is already running.
6208 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
6209 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
6210 // see previously buffered data before it called start(), but with greater risk of overrun.
6211
Andy Hung73c02e42015-03-29 01:13:58 -07006212 recordTrack->mResamplerBufferProvider->reset();
Andy Hung97a893e2015-03-29 01:03:07 -07006213 // clear any converter state as new data will be discontinuous
6214 recordTrack->mRecordBufferConverter->reset();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006215 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08006216 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08006217 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08006218 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006219 ALOGV("Record failed to start");
6220 status = BAD_VALUE;
6221 goto startError;
6222 }
Eric Laurent81784c32012-11-19 14:55:58 -08006223 return status;
6224 }
Glenn Kasten7c027242012-12-26 14:43:16 -08006225
Eric Laurent81784c32012-11-19 14:55:58 -08006226startError:
Eric Laurent83b88082014-06-20 18:31:16 -07006227 if (recordTrack->isExternalTrack()) {
Eric Laurent4dc68062014-07-28 17:26:49 -07006228 AudioSystem::stopInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006229 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006230 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006231 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08006232 return status;
6233}
6234
Eric Laurent81784c32012-11-19 14:55:58 -08006235void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6236{
6237 sp<SyncEvent> strongEvent = event.promote();
6238
6239 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08006240 sp<RefBase> ptr = strongEvent->cookie().promote();
6241 if (ptr != 0) {
6242 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
6243 recordTrack->handleSyncStartEvent(strongEvent);
6244 }
Eric Laurent81784c32012-11-19 14:55:58 -08006245 }
6246}
6247
Glenn Kastena8356f62013-07-25 14:37:52 -07006248bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08006249 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07006250 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006251 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08006252 return false;
6253 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006254 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08006255 recordTrack->mState = TrackBase::PAUSING;
6256 // do not wait for mStartStopCond if exiting
6257 if (exitPending()) {
6258 return true;
6259 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006260 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08006261 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006262 // if we have been restarted, recordTrack is in mActiveTracks here
6263 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006264 ALOGV("Record stopped OK");
6265 return true;
6266 }
6267 return false;
6268}
6269
Glenn Kasten0f11b512014-01-31 16:18:54 -08006270bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08006271{
6272 return false;
6273}
6274
Glenn Kasten0f11b512014-01-31 16:18:54 -08006275status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006276{
6277#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
6278 if (!isValidSyncEvent(event)) {
6279 return BAD_VALUE;
6280 }
6281
6282 int eventSession = event->triggerSession();
6283 status_t ret = NAME_NOT_FOUND;
6284
6285 Mutex::Autolock _l(mLock);
6286
6287 for (size_t i = 0; i < mTracks.size(); i++) {
6288 sp<RecordTrack> track = mTracks[i];
6289 if (eventSession == track->sessionId()) {
6290 (void) track->setSyncEvent(event);
6291 ret = NO_ERROR;
6292 }
6293 }
6294 return ret;
6295#else
6296 return BAD_VALUE;
6297#endif
6298}
6299
6300// destroyTrack_l() must be called with ThreadBase::mLock held
6301void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6302{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006303 track->terminate();
6304 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08006305 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08006306 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006307 removeTrack_l(track);
6308 }
6309}
6310
6311void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6312{
6313 mTracks.remove(track);
6314 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006315 if (track->isFastTrack()) {
6316 ALOG_ASSERT(!mFastTrackAvail);
6317 mFastTrackAvail = true;
6318 }
Eric Laurent81784c32012-11-19 14:55:58 -08006319}
6320
6321void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6322{
6323 dumpInternals(fd, args);
6324 dumpTracks(fd, args);
6325 dumpEffectChains(fd, args);
6326}
6327
6328void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6329{
Elliott Hughes87cebad2014-05-22 10:14:43 -07006330 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08006331
Glenn Kasten44182c22015-03-05 17:12:23 -08006332 dumpBase(fd, args);
6333
6334 if (mActiveTracks.size() == 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006335 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006336 }
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006337 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006338 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08006339
6340 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
6341 const FastCaptureDumpState copy(mFastCaptureDumpState);
6342 copy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006343}
6344
Glenn Kasten0f11b512014-01-31 16:18:54 -08006345void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006346{
6347 const size_t SIZE = 256;
6348 char buffer[SIZE];
6349 String8 result;
6350
Marco Nelissenb2208842014-02-07 14:00:50 -08006351 size_t numtracks = mTracks.size();
6352 size_t numactive = mActiveTracks.size();
6353 size_t numactiveseen = 0;
Elliott Hughes87cebad2014-05-22 10:14:43 -07006354 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08006355 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006356 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08006357 RecordTrack::appendDumpHeader(result);
6358 for (size_t i = 0; i < numtracks ; ++i) {
6359 sp<RecordTrack> track = mTracks[i];
6360 if (track != 0) {
6361 bool active = mActiveTracks.indexOf(track) >= 0;
6362 if (active) {
6363 numactiveseen++;
6364 }
6365 track->dump(buffer, SIZE, active);
6366 result.append(buffer);
6367 }
Eric Laurent81784c32012-11-19 14:55:58 -08006368 }
Marco Nelissenb2208842014-02-07 14:00:50 -08006369 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006370 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006371 }
6372
Marco Nelissenb2208842014-02-07 14:00:50 -08006373 if (numactiveseen != numactive) {
6374 snprintf(buffer, SIZE, " The following tracks are in the active list but"
6375 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006376 result.append(buffer);
6377 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08006378 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08006379 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08006380 if (mTracks.indexOf(track) < 0) {
6381 track->dump(buffer, SIZE, true);
6382 result.append(buffer);
6383 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006384 }
Eric Laurent81784c32012-11-19 14:55:58 -08006385
6386 }
6387 write(fd, result.string(), result.size());
6388}
6389
Andy Hung73c02e42015-03-29 01:13:58 -07006390
6391void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
6392{
6393 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6394 RecordThread *recordThread = (RecordThread *) threadBase.get();
6395 mRsmpInFront = recordThread->mRsmpInRear;
6396 mRsmpInUnrel = 0;
6397}
6398
6399void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
6400 size_t *framesAvailable, bool *hasOverrun)
6401{
6402 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6403 RecordThread *recordThread = (RecordThread *) threadBase.get();
6404 const int32_t rear = recordThread->mRsmpInRear;
6405 const int32_t front = mRsmpInFront;
6406 const ssize_t filled = rear - front;
6407
6408 size_t framesIn;
6409 bool overrun = false;
6410 if (filled < 0) {
6411 // should not happen, but treat like a massive overrun and re-sync
6412 framesIn = 0;
6413 mRsmpInFront = rear;
6414 overrun = true;
6415 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
6416 framesIn = (size_t) filled;
6417 } else {
6418 // client is not keeping up with server, but give it latest data
6419 framesIn = recordThread->mRsmpInFrames;
6420 mRsmpInFront = /* front = */ rear - framesIn;
6421 overrun = true;
6422 }
6423 if (framesAvailable != NULL) {
6424 *framesAvailable = framesIn;
6425 }
6426 if (hasOverrun != NULL) {
6427 *hasOverrun = overrun;
6428 }
6429}
6430
Eric Laurent81784c32012-11-19 14:55:58 -08006431// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006432status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
6433 AudioBufferProvider::Buffer* buffer, int64_t pts __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006434{
Andy Hung73c02e42015-03-29 01:13:58 -07006435 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006436 if (threadBase == 0) {
6437 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006438 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006439 return NOT_ENOUGH_DATA;
6440 }
6441 RecordThread *recordThread = (RecordThread *) threadBase.get();
6442 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07006443 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07006444 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006445 // FIXME should not be P2 (don't want to increase latency)
6446 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006447 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07006448 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006449 front &= recordThread->mRsmpInFramesP2 - 1;
6450 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07006451 if (part1 > (size_t) filled) {
6452 part1 = filled;
6453 }
6454 size_t ask = buffer->frameCount;
6455 ALOG_ASSERT(ask > 0);
6456 if (part1 > ask) {
6457 part1 = ask;
6458 }
6459 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07006460 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07006461 buffer->raw = NULL;
6462 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07006463 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07006464 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08006465 }
6466
Andy Hung57446612015-04-19 23:56:46 -07006467 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07006468 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07006469 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08006470 return NO_ERROR;
6471}
6472
6473// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006474void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
6475 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006476{
Glenn Kasten85948432013-08-19 12:09:05 -07006477 size_t stepCount = buffer->frameCount;
6478 if (stepCount == 0) {
6479 return;
6480 }
Andy Hung73c02e42015-03-29 01:13:58 -07006481 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
6482 mRsmpInUnrel -= stepCount;
6483 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07006484 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006485 buffer->frameCount = 0;
6486}
6487
Andy Hung97a893e2015-03-29 01:03:07 -07006488AudioFlinger::RecordThread::RecordBufferConverter::RecordBufferConverter(
6489 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6490 uint32_t srcSampleRate,
6491 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6492 uint32_t dstSampleRate) :
6493 mSrcChannelMask(AUDIO_CHANNEL_INVALID), // updateParameters will set following vars
6494 // mSrcFormat
6495 // mSrcSampleRate
6496 // mDstChannelMask
6497 // mDstFormat
6498 // mDstSampleRate
6499 // mSrcChannelCount
6500 // mDstChannelCount
6501 // mDstFrameSize
6502 mBuf(NULL), mBufFrames(0), mBufFrameSize(0),
Andy Hungd330ee42015-04-20 13:23:41 -07006503 mResampler(NULL),
6504 mIsLegacyDownmix(false),
6505 mIsLegacyUpmix(false),
6506 mRequiresFloat(false),
6507 mInputConverterProvider(NULL)
Andy Hung97a893e2015-03-29 01:03:07 -07006508{
6509 (void)updateParameters(srcChannelMask, srcFormat, srcSampleRate,
6510 dstChannelMask, dstFormat, dstSampleRate);
6511}
6512
6513AudioFlinger::RecordThread::RecordBufferConverter::~RecordBufferConverter() {
6514 free(mBuf);
6515 delete mResampler;
Andy Hungd330ee42015-04-20 13:23:41 -07006516 delete mInputConverterProvider;
Andy Hung97a893e2015-03-29 01:03:07 -07006517}
6518
6519size_t AudioFlinger::RecordThread::RecordBufferConverter::convert(void *dst,
6520 AudioBufferProvider *provider, size_t frames)
6521{
Andy Hungd330ee42015-04-20 13:23:41 -07006522 if (mInputConverterProvider != NULL) {
6523 mInputConverterProvider->setBufferProvider(provider);
6524 provider = mInputConverterProvider;
6525 }
6526
6527 if (mResampler == NULL) {
Andy Hung97a893e2015-03-29 01:03:07 -07006528 ALOGVV("NO RESAMPLING sampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6529 mSrcSampleRate, mSrcFormat, mDstFormat);
6530
6531 AudioBufferProvider::Buffer buffer;
6532 for (size_t i = frames; i > 0; ) {
6533 buffer.frameCount = i;
6534 status_t status = provider->getNextBuffer(&buffer, 0);
6535 if (status != OK || buffer.frameCount == 0) {
6536 frames -= i; // cannot fill request.
6537 break;
6538 }
Andy Hungd330ee42015-04-20 13:23:41 -07006539 // format convert to destination buffer
6540 convertNoResampler(dst, buffer.raw, buffer.frameCount);
Andy Hung97a893e2015-03-29 01:03:07 -07006541
6542 dst = (int8_t*)dst + buffer.frameCount * mDstFrameSize;
6543 i -= buffer.frameCount;
6544 provider->releaseBuffer(&buffer);
6545 }
6546 } else {
6547 ALOGVV("RESAMPLING mSrcSampleRate:%u mDstSampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6548 mSrcSampleRate, mDstSampleRate, mSrcFormat, mDstFormat);
6549
Andy Hungd330ee42015-04-20 13:23:41 -07006550 // reallocate buffer if needed
6551 if (mBufFrameSize != 0 && mBufFrames < frames) {
6552 free(mBuf);
6553 mBufFrames = frames;
6554 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
6555 }
Andy Hung97a893e2015-03-29 01:03:07 -07006556 // resampler accumulates, but we only have one source track
Andy Hungd330ee42015-04-20 13:23:41 -07006557 memset(mBuf, 0, frames * mBufFrameSize);
6558 frames = mResampler->resample((int32_t*)mBuf, frames, provider);
6559 // format convert to destination buffer
6560 convertResampler(dst, mBuf, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006561 }
6562 return frames;
6563}
6564
6565status_t AudioFlinger::RecordThread::RecordBufferConverter::updateParameters(
6566 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6567 uint32_t srcSampleRate,
6568 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6569 uint32_t dstSampleRate)
6570{
6571 // quick evaluation if there is any change.
6572 if (mSrcFormat == srcFormat
6573 && mSrcChannelMask == srcChannelMask
6574 && mSrcSampleRate == srcSampleRate
6575 && mDstFormat == dstFormat
6576 && mDstChannelMask == dstChannelMask
6577 && mDstSampleRate == dstSampleRate) {
6578 return NO_ERROR;
6579 }
6580
Andy Hungdb4c0312015-05-06 08:46:52 -07006581 ALOGV("RecordBufferConverter updateParameters srcMask:%#x dstMask:%#x"
6582 " srcFormat:%#x dstFormat:%#x srcRate:%u dstRate:%u",
6583 srcChannelMask, dstChannelMask, srcFormat, dstFormat, srcSampleRate, dstSampleRate);
Andy Hung97a893e2015-03-29 01:03:07 -07006584 const bool valid =
6585 audio_is_input_channel(srcChannelMask)
6586 && audio_is_input_channel(dstChannelMask)
6587 && audio_is_valid_format(srcFormat) && audio_is_linear_pcm(srcFormat)
6588 && audio_is_valid_format(dstFormat) && audio_is_linear_pcm(dstFormat)
6589 && (srcSampleRate <= dstSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX)
6590 ; // no upsampling checks for now
6591 if (!valid) {
6592 return BAD_VALUE;
6593 }
6594
6595 mSrcFormat = srcFormat;
6596 mSrcChannelMask = srcChannelMask;
6597 mSrcSampleRate = srcSampleRate;
6598 mDstFormat = dstFormat;
6599 mDstChannelMask = dstChannelMask;
6600 mDstSampleRate = dstSampleRate;
6601
6602 // compute derived parameters
6603 mSrcChannelCount = audio_channel_count_from_in_mask(srcChannelMask);
6604 mDstChannelCount = audio_channel_count_from_in_mask(dstChannelMask);
6605 mDstFrameSize = mDstChannelCount * audio_bytes_per_sample(mDstFormat);
6606
Andy Hungd330ee42015-04-20 13:23:41 -07006607 // do we need to resample?
6608 delete mResampler;
6609 mResampler = NULL;
6610 if (mSrcSampleRate != mDstSampleRate) {
6611 mResampler = AudioResampler::create(AUDIO_FORMAT_PCM_FLOAT,
6612 mSrcChannelCount, mDstSampleRate);
6613 mResampler->setSampleRate(mSrcSampleRate);
6614 mResampler->setVolume(AudioMixer::UNITY_GAIN_FLOAT, AudioMixer::UNITY_GAIN_FLOAT);
6615 }
6616
6617 // are we running legacy channel conversion modes?
6618 mIsLegacyDownmix = (mSrcChannelMask == AUDIO_CHANNEL_IN_STEREO
6619 || mSrcChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK)
6620 && mDstChannelMask == AUDIO_CHANNEL_IN_MONO;
6621 mIsLegacyUpmix = mSrcChannelMask == AUDIO_CHANNEL_IN_MONO
6622 && (mDstChannelMask == AUDIO_CHANNEL_IN_STEREO
6623 || mDstChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK);
6624
6625 // do we need to process in float?
6626 mRequiresFloat = mResampler != NULL || mIsLegacyDownmix || mIsLegacyUpmix;
6627
6628 // do we need a staging buffer to convert for destination (we can still optimize this)?
6629 // we use mBufFrameSize > 0 to indicate both frame size as well as buffer necessity
6630 if (mResampler != NULL) {
6631 mBufFrameSize = max(mSrcChannelCount, FCC_2)
6632 * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
6633 } else if ((mIsLegacyUpmix || mIsLegacyDownmix) && mDstFormat != AUDIO_FORMAT_PCM_FLOAT) {
6634 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
6635 } else if (mSrcChannelMask != mDstChannelMask && mDstFormat != mSrcFormat) {
Andy Hung97a893e2015-03-29 01:03:07 -07006636 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(mSrcFormat);
6637 } else {
6638 mBufFrameSize = 0;
6639 }
6640 mBufFrames = 0; // force the buffer to be resized.
6641
Andy Hungd330ee42015-04-20 13:23:41 -07006642 // do we need an input converter buffer provider to give us float?
6643 delete mInputConverterProvider;
6644 mInputConverterProvider = NULL;
6645 if (mRequiresFloat && mSrcFormat != AUDIO_FORMAT_PCM_FLOAT) {
6646 mInputConverterProvider = new ReformatBufferProvider(
6647 audio_channel_count_from_in_mask(mSrcChannelMask),
6648 mSrcFormat,
6649 AUDIO_FORMAT_PCM_FLOAT,
6650 256 /* provider buffer frame count */);
6651 }
6652
6653 // do we need a remixer to do channel mask conversion
6654 if (!mIsLegacyDownmix && !mIsLegacyUpmix && mSrcChannelMask != mDstChannelMask) {
6655 (void) memcpy_by_index_array_initialization_from_channel_mask(
6656 mIdxAry, ARRAY_SIZE(mIdxAry), mDstChannelMask, mSrcChannelMask);
Andy Hung97a893e2015-03-29 01:03:07 -07006657 }
6658 return NO_ERROR;
6659}
6660
Andy Hungd330ee42015-04-20 13:23:41 -07006661void AudioFlinger::RecordThread::RecordBufferConverter::convertNoResampler(
6662 void *dst, const void *src, size_t frames)
Andy Hung97a893e2015-03-29 01:03:07 -07006663{
Andy Hungd330ee42015-04-20 13:23:41 -07006664 // src is native type unless there is legacy upmix or downmix, whereupon it is float.
Andy Hung97a893e2015-03-29 01:03:07 -07006665 if (mBufFrameSize != 0 && mBufFrames < frames) {
6666 free(mBuf);
6667 mBufFrames = frames;
6668 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
6669 }
Andy Hungd330ee42015-04-20 13:23:41 -07006670 // do we need to do legacy upmix and downmix?
6671 if (mIsLegacyUpmix || mIsLegacyDownmix) {
Andy Hung97a893e2015-03-29 01:03:07 -07006672 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07006673 if (mIsLegacyUpmix) {
6674 upmix_to_stereo_float_from_mono_float((float *)dstBuf,
6675 (const float *)src, frames);
6676 } else /*mIsLegacyDownmix */ {
6677 downmix_to_mono_float_from_stereo_float((float *)dstBuf,
6678 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006679 }
Andy Hungd330ee42015-04-20 13:23:41 -07006680 if (mBuf != NULL) {
6681 memcpy_by_audio_format(dst, mDstFormat, mBuf, AUDIO_FORMAT_PCM_FLOAT,
6682 frames * mDstChannelCount);
6683 }
6684 return;
6685 }
6686 // do we need to do channel mask conversion?
6687 if (mSrcChannelMask != mDstChannelMask) {
Andy Hung97a893e2015-03-29 01:03:07 -07006688 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07006689 memcpy_by_index_array(dstBuf, mDstChannelCount,
6690 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mSrcFormat), frames);
6691 if (dstBuf == dst) {
6692 return; // format is the same
6693 }
6694 }
6695 // convert to destination buffer
6696 const void *convertBuf = mBuf != NULL ? mBuf : src;
6697 memcpy_by_audio_format(dst, mDstFormat, convertBuf, mSrcFormat,
6698 frames * mDstChannelCount);
6699}
6700
6701void AudioFlinger::RecordThread::RecordBufferConverter::convertResampler(
6702 void *dst, /*not-a-const*/ void *src, size_t frames)
6703{
6704 // src buffer format is ALWAYS float when entering this routine
6705 if (mIsLegacyUpmix) {
6706 ; // mono to stereo already handled by resampler
6707 } else if (mIsLegacyDownmix
6708 || (mSrcChannelMask == mDstChannelMask && mSrcChannelCount == 1)) {
6709 // the resampler outputs stereo for mono input channel (a feature?)
6710 // must convert to mono
6711 downmix_to_mono_float_from_stereo_float((float *)src,
6712 (const float *)src, frames);
6713 } else if (mSrcChannelMask != mDstChannelMask) {
6714 // convert to mono channel again for channel mask conversion (could be skipped
6715 // with further optimization).
Andy Hung97a893e2015-03-29 01:03:07 -07006716 if (mSrcChannelCount == 1) {
Andy Hungd330ee42015-04-20 13:23:41 -07006717 downmix_to_mono_float_from_stereo_float((float *)src,
6718 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006719 }
Andy Hungd330ee42015-04-20 13:23:41 -07006720 // convert to destination format (in place, OK as float is larger than other types)
6721 if (mDstFormat != AUDIO_FORMAT_PCM_FLOAT) {
6722 memcpy_by_audio_format(src, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
6723 frames * mSrcChannelCount);
6724 }
6725 // channel convert and save to dst
6726 memcpy_by_index_array(dst, mDstChannelCount,
6727 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mDstFormat), frames);
6728 return;
Andy Hung97a893e2015-03-29 01:03:07 -07006729 }
Andy Hungd330ee42015-04-20 13:23:41 -07006730 // convert to destination format and save to dst
6731 memcpy_by_audio_format(dst, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
6732 frames * mDstChannelCount);
Andy Hung97a893e2015-03-29 01:03:07 -07006733}
6734
Eric Laurent10351942014-05-08 18:49:52 -07006735bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
6736 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006737{
6738 bool reconfig = false;
6739
Eric Laurent10351942014-05-08 18:49:52 -07006740 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006741
Eric Laurent10351942014-05-08 18:49:52 -07006742 audio_format_t reqFormat = mFormat;
6743 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07006744 // TODO this may change if we want to support capture from HDMI PCM multi channel (e.g on TVs).
Eric Laurent10351942014-05-08 18:49:52 -07006745 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
6746
6747 AudioParameter param = AudioParameter(keyValuePair);
6748 int value;
6749 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
6750 // channel count change can be requested. Do we mandate the first client defines the
6751 // HAL sampling rate and channel count or do we allow changes on the fly?
6752 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6753 samplingRate = value;
6754 reconfig = true;
6755 }
6756 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07006757 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07006758 status = BAD_VALUE;
6759 } else {
6760 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08006761 reconfig = true;
6762 }
Eric Laurent10351942014-05-08 18:49:52 -07006763 }
6764 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
6765 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07006766 if (!audio_is_input_channel(mask) ||
6767 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07006768 status = BAD_VALUE;
6769 } else {
6770 channelMask = mask;
6771 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006772 }
Eric Laurent10351942014-05-08 18:49:52 -07006773 }
6774 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6775 // do not accept frame count changes if tracks are open as the track buffer
6776 // size depends on frame count and correct behavior would not be guaranteed
6777 // if frame count is changed after track creation
6778 if (mActiveTracks.size() > 0) {
6779 status = INVALID_OPERATION;
6780 } else {
6781 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006782 }
Eric Laurent10351942014-05-08 18:49:52 -07006783 }
6784 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6785 // forward device change to effects that have requested to be
6786 // aware of attached audio device.
6787 for (size_t i = 0; i < mEffectChains.size(); i++) {
6788 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08006789 }
Eric Laurent81784c32012-11-19 14:55:58 -08006790
Eric Laurent10351942014-05-08 18:49:52 -07006791 // store input device and output device but do not forward output device to audio HAL.
6792 // Note that status is ignored by the caller for output device
6793 // (see AudioFlinger::setParameters()
6794 if (audio_is_output_devices(value)) {
6795 mOutDevice = value;
6796 status = BAD_VALUE;
6797 } else {
6798 mInDevice = value;
6799 // disable AEC and NS if the device is a BT SCO headset supporting those
6800 // pre processings
6801 if (mTracks.size() > 0) {
6802 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6803 mAudioFlinger->btNrecIsOff();
6804 for (size_t i = 0; i < mTracks.size(); i++) {
6805 sp<RecordTrack> track = mTracks[i];
6806 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
6807 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08006808 }
6809 }
6810 }
Eric Laurent10351942014-05-08 18:49:52 -07006811 }
6812 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
6813 mAudioSource != (audio_source_t)value) {
6814 // forward device change to effects that have requested to be
6815 // aware of attached audio device.
6816 for (size_t i = 0; i < mEffectChains.size(); i++) {
6817 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08006818 }
Eric Laurent10351942014-05-08 18:49:52 -07006819 mAudioSource = (audio_source_t)value;
6820 }
Glenn Kastene198c362013-08-13 09:13:36 -07006821
Eric Laurent10351942014-05-08 18:49:52 -07006822 if (status == NO_ERROR) {
6823 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6824 keyValuePair.string());
6825 if (status == INVALID_OPERATION) {
6826 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006827 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6828 keyValuePair.string());
Eric Laurent10351942014-05-08 18:49:52 -07006829 }
6830 if (reconfig) {
6831 if (status == BAD_VALUE &&
Andy Hung97a893e2015-03-29 01:03:07 -07006832 audio_is_linear_pcm(mInput->stream->common.get_format(&mInput->stream->common)) &&
6833 audio_is_linear_pcm(reqFormat) &&
Eric Laurent10351942014-05-08 18:49:52 -07006834 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
Andy Hung97a893e2015-03-29 01:03:07 -07006835 <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate)) &&
Andy Hunge5412692014-05-16 11:25:07 -07006836 audio_channel_count_from_in_mask(
Andy Hungd1abb8f2015-05-05 23:42:34 -07006837 mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07006838 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006839 }
Eric Laurent10351942014-05-08 18:49:52 -07006840 if (status == NO_ERROR) {
6841 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07006842 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08006843 }
6844 }
Eric Laurent81784c32012-11-19 14:55:58 -08006845 }
Eric Laurent10351942014-05-08 18:49:52 -07006846
Eric Laurent81784c32012-11-19 14:55:58 -08006847 return reconfig;
6848}
6849
6850String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6851{
Eric Laurent81784c32012-11-19 14:55:58 -08006852 Mutex::Autolock _l(mLock);
6853 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07006854 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08006855 }
6856
Glenn Kastend8ea6992013-07-16 14:17:15 -07006857 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
6858 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08006859 free(s);
6860 return out_s8;
6861}
6862
Eric Laurent73e26b62015-04-27 16:55:58 -07006863void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event) {
6864 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
6865
6866 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08006867
6868 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07006869 case AUDIO_INPUT_OPENED:
6870 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07006871 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07006872 desc->mChannelMask = mChannelMask;
6873 desc->mSamplingRate = mSampleRate;
6874 desc->mFormat = mFormat;
6875 desc->mFrameCount = mFrameCount;
6876 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006877 break;
6878
Eric Laurent73e26b62015-04-27 16:55:58 -07006879 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08006880 default:
6881 break;
6882 }
Eric Laurent73e26b62015-04-27 16:55:58 -07006883 mAudioFlinger->ioConfigChanged(event, desc);
Eric Laurent81784c32012-11-19 14:55:58 -08006884}
6885
Glenn Kastendeca2ae2014-02-07 10:25:56 -08006886void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006887{
Eric Laurent81784c32012-11-19 14:55:58 -08006888 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
6889 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Andy Hunge5412692014-05-16 11:25:07 -07006890 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Andy Hungd330ee42015-04-20 13:23:41 -07006891 if (mChannelCount > FCC_8) {
6892 ALOGE("HAL channel count %d > %d", mChannelCount, FCC_8);
6893 }
Andy Hung463be252014-07-10 16:56:07 -07006894 mHALFormat = mInput->stream->common.get_format(&mInput->stream->common);
6895 mFormat = mHALFormat;
Andy Hungd330ee42015-04-20 13:23:41 -07006896 if (!audio_is_linear_pcm(mFormat)) {
6897 ALOGE("HAL format %#x is not linear pcm", mFormat);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07006898 }
Eric Laurent665470b2014-07-03 16:37:08 -07006899 mFrameSize = audio_stream_in_frame_size(mInput->stream);
Glenn Kasten548efc92012-11-29 08:48:51 -08006900 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
6901 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006902 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08006903 // 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 -07006904 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08006905 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006906 // A larger value should allow more old data to be read after a track calls start(),
6907 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07006908 //
6909 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08006910 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07006911 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07006912 free(mRsmpInBuffer);
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006913
6914 // TODO optimize audio capture buffer sizes ...
6915 // Here we calculate the size of the sliding buffer used as a source
6916 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
6917 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
6918 // be better to have it derived from the pipe depth in the long term.
6919 // The current value is higher than necessary. However it should not add to latency.
6920
Glenn Kasten85948432013-08-19 12:09:05 -07006921 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Andy Hung57446612015-04-19 23:56:46 -07006922 (void)posix_memalign(&mRsmpInBuffer, 32, (mRsmpInFramesP2 + mFrameCount - 1) * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006923
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006924 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
6925 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08006926}
6927
Glenn Kasten5f972c02014-01-13 09:59:31 -08006928uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08006929{
6930 Mutex::Autolock _l(mLock);
6931 if (initCheck() != NO_ERROR) {
6932 return 0;
6933 }
6934
6935 return mInput->stream->get_input_frames_lost(mInput->stream);
6936}
6937
6938uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
6939{
6940 Mutex::Autolock _l(mLock);
6941 uint32_t result = 0;
6942 if (getEffectChain_l(sessionId) != 0) {
6943 result = EFFECT_SESSION;
6944 }
6945
6946 for (size_t i = 0; i < mTracks.size(); ++i) {
6947 if (sessionId == mTracks[i]->sessionId()) {
6948 result |= TRACK_SESSION;
6949 break;
6950 }
6951 }
6952
6953 return result;
6954}
6955
6956KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
6957{
6958 KeyedVector<int, bool> ids;
6959 Mutex::Autolock _l(mLock);
6960 for (size_t j = 0; j < mTracks.size(); ++j) {
6961 sp<RecordThread::RecordTrack> track = mTracks[j];
6962 int sessionId = track->sessionId();
6963 if (ids.indexOfKey(sessionId) < 0) {
6964 ids.add(sessionId, true);
6965 }
6966 }
6967 return ids;
6968}
6969
6970AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
6971{
6972 Mutex::Autolock _l(mLock);
6973 AudioStreamIn *input = mInput;
6974 mInput = NULL;
6975 return input;
6976}
6977
6978// this method must always be called either with ThreadBase mLock held or inside the thread loop
6979audio_stream_t* AudioFlinger::RecordThread::stream() const
6980{
6981 if (mInput == NULL) {
6982 return NULL;
6983 }
6984 return &mInput->stream->common;
6985}
6986
6987status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6988{
6989 // only one chain per input thread
6990 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07006991 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08006992 return INVALID_OPERATION;
6993 }
6994 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07006995 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08006996 chain->setInBuffer(NULL);
6997 chain->setOutBuffer(NULL);
6998
6999 checkSuspendOnAddEffectChain_l(chain);
7000
Eric Laurent1b928682014-10-02 19:41:47 -07007001 // make sure enabled pre processing effects state is communicated to the HAL as we
7002 // just moved them to a new input stream.
7003 chain->syncHalEffectsState();
7004
Eric Laurent81784c32012-11-19 14:55:58 -08007005 mEffectChains.add(chain);
7006
7007 return NO_ERROR;
7008}
7009
7010size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7011{
7012 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
7013 ALOGW_IF(mEffectChains.size() != 1,
7014 "removeEffectChain_l() %p invalid chain size %d on thread %p",
7015 chain.get(), mEffectChains.size(), this);
7016 if (mEffectChains.size() == 1) {
7017 mEffectChains.removeAt(0);
7018 }
7019 return 0;
7020}
7021
Eric Laurent1c333e22014-05-20 10:48:17 -07007022status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
7023 audio_patch_handle_t *handle)
7024{
7025 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007026
7027 // store new device and send to effects
7028 mInDevice = patch->sources[0].ext.device.type;
Eric Laurent296fb132015-05-01 11:38:42 -07007029 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07007030 for (size_t i = 0; i < mEffectChains.size(); i++) {
7031 mEffectChains[i]->setDevice_l(mInDevice);
7032 }
7033
7034 // disable AEC and NS if the device is a BT SCO headset supporting those
7035 // pre processings
7036 if (mTracks.size() > 0) {
7037 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7038 mAudioFlinger->btNrecIsOff();
7039 for (size_t i = 0; i < mTracks.size(); i++) {
7040 sp<RecordTrack> track = mTracks[i];
7041 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7042 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
7043 }
7044 }
7045
7046 // store new source and send to effects
7047 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7048 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07007049 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07007050 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07007051 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007052 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007053
Eric Laurent054d9d32015-04-24 08:48:48 -07007054 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007055 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
7056 status = hwDevice->create_audio_patch(hwDevice,
7057 patch->num_sources,
7058 patch->sources,
7059 patch->num_sinks,
7060 patch->sinks,
7061 handle);
7062 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007063 char *address;
7064 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
7065 address = audio_device_address_to_parameter(
7066 patch->sources[0].ext.device.type,
7067 patch->sources[0].ext.device.address);
7068 } else {
7069 address = (char *)calloc(1, 1);
7070 }
7071 AudioParameter param = AudioParameter(String8(address));
7072 free(address);
7073 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING),
7074 (int)patch->sources[0].ext.device.type);
7075 param.addInt(String8(AUDIO_PARAMETER_STREAM_INPUT_SOURCE),
7076 (int)patch->sinks[0].ext.mix.usecase.source);
7077 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7078 param.toString().string());
7079 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07007080 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007081
Eric Laurent296fb132015-05-01 11:38:42 -07007082 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
7083
Eric Laurent1c333e22014-05-20 10:48:17 -07007084 return status;
7085}
7086
7087status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
7088{
7089 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007090
7091 mInDevice = AUDIO_DEVICE_NONE;
7092
Eric Laurent1c333e22014-05-20 10:48:17 -07007093 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
7094 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
7095 status = hwDevice->release_audio_patch(hwDevice, handle);
7096 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007097 AudioParameter param;
7098 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
7099 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7100 param.toString().string());
Eric Laurent1c333e22014-05-20 10:48:17 -07007101 }
7102 return status;
7103}
7104
Eric Laurent83b88082014-06-20 18:31:16 -07007105void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
7106{
7107 Mutex::Autolock _l(mLock);
7108 mTracks.add(record);
7109}
7110
7111void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
7112{
7113 Mutex::Autolock _l(mLock);
7114 destroyTrack_l(record);
7115}
7116
7117void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
7118{
7119 ThreadBase::getAudioPortConfig(config);
7120 config->role = AUDIO_PORT_ROLE_SINK;
7121 config->ext.mix.hw_module = mInput->audioHwDev->handle();
7122 config->ext.mix.usecase.source = mAudioSource;
7123}
Eric Laurent1c333e22014-05-20 10:48:17 -07007124
Glenn Kasten63238ef2015-03-02 15:50:29 -08007125} // namespace android