blob: d3ea9d82ad2598e8d07796244feb923be6f2ee0c [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",
Eric Laurentb9d73332015-06-30 17:09:20 -0700378 AUDIO_DEVICE_OUT_IP, "IP",
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800379 AUDIO_DEVICE_NONE, "NONE", // must be last
380 }, mappingsIn[] = {
Glenn Kasten84d61ca2015-05-06 18:32:13 -0700381 AUDIO_DEVICE_IN_COMMUNICATION, "COMMUNICATION",
382 AUDIO_DEVICE_IN_AMBIENT, "AMBIENT",
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800383 AUDIO_DEVICE_IN_BUILTIN_MIC, "BUILTIN_MIC",
Glenn Kasten84d61ca2015-05-06 18:32:13 -0700384 AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET, "BLUETOOTH_SCO_HEADSET",
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800385 AUDIO_DEVICE_IN_WIRED_HEADSET, "WIRED_HEADSET",
Glenn Kasten84d61ca2015-05-06 18:32:13 -0700386 AUDIO_DEVICE_IN_AUX_DIGITAL, "AUX_DIGITAL",
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800387 AUDIO_DEVICE_IN_VOICE_CALL, "VOICE_CALL",
Glenn Kasten84d61ca2015-05-06 18:32:13 -0700388 AUDIO_DEVICE_IN_TELEPHONY_RX, "TELEPHONY_RX",
389 AUDIO_DEVICE_IN_BACK_MIC, "BACK_MIC",
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800390 AUDIO_DEVICE_IN_REMOTE_SUBMIX, "REMOTE_SUBMIX",
Glenn Kasten84d61ca2015-05-06 18:32:13 -0700391 AUDIO_DEVICE_IN_ANLG_DOCK_HEADSET, "ANLG_DOCK_HEADSET",
392 AUDIO_DEVICE_IN_DGTL_DOCK_HEADSET, "DGTL_DOCK_HEADSET",
393 AUDIO_DEVICE_IN_USB_ACCESSORY, "USB_ACCESSORY",
394 AUDIO_DEVICE_IN_USB_DEVICE, "USB_DEVICE",
395 AUDIO_DEVICE_IN_FM_TUNER, "FM_TUNER",
396 AUDIO_DEVICE_IN_TV_TUNER, "TV_TUNER",
397 AUDIO_DEVICE_IN_LINE, "LINE",
398 AUDIO_DEVICE_IN_SPDIF, "SPDIF",
399 AUDIO_DEVICE_IN_BLUETOOTH_A2DP, "BLUETOOTH_A2DP",
400 AUDIO_DEVICE_IN_LOOPBACK, "LOOPBACK",
Eric Laurentb9d73332015-06-30 17:09:20 -0700401 AUDIO_DEVICE_IN_IP, "IP",
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800402 AUDIO_DEVICE_NONE, "NONE", // must be last
403 };
404 String8 result;
405 audio_devices_t allDevices = AUDIO_DEVICE_NONE;
406 const mapping *entry;
407 if (devices & AUDIO_DEVICE_BIT_IN) {
408 devices &= ~AUDIO_DEVICE_BIT_IN;
409 entry = mappingsIn;
410 } else {
411 entry = mappingsOut;
412 }
413 for ( ; entry->mDevices != AUDIO_DEVICE_NONE; entry++) {
414 allDevices = (audio_devices_t) (allDevices | entry->mDevices);
415 if (devices & entry->mDevices) {
416 if (!result.isEmpty()) {
417 result.append("|");
418 }
419 result.append(entry->mString);
420 }
421 }
422 if (devices & ~allDevices) {
423 if (!result.isEmpty()) {
424 result.append("|");
425 }
426 result.appendFormat("0x%X", devices & ~allDevices);
427 }
428 if (result.isEmpty()) {
429 result.append(entry->mString);
430 }
431 return result;
432}
433
434String8 inputFlagsToString(audio_input_flags_t flags)
435{
436 static const struct mapping {
437 audio_input_flags_t mFlag;
438 const char * mString;
439 } mappings[] = {
440 AUDIO_INPUT_FLAG_FAST, "FAST",
441 AUDIO_INPUT_FLAG_HW_HOTWORD, "HW_HOTWORD",
442 AUDIO_INPUT_FLAG_NONE, "NONE", // must be last
443 };
444 String8 result;
445 audio_input_flags_t allFlags = AUDIO_INPUT_FLAG_NONE;
446 const mapping *entry;
447 for (entry = mappings; entry->mFlag != AUDIO_INPUT_FLAG_NONE; entry++) {
448 allFlags = (audio_input_flags_t) (allFlags | entry->mFlag);
449 if (flags & entry->mFlag) {
450 if (!result.isEmpty()) {
451 result.append("|");
452 }
453 result.append(entry->mString);
454 }
455 }
456 if (flags & ~allFlags) {
457 if (!result.isEmpty()) {
458 result.append("|");
459 }
460 result.appendFormat("0x%X", flags & ~allFlags);
461 }
462 if (result.isEmpty()) {
463 result.append(entry->mString);
464 }
465 return result;
466}
467
468String8 outputFlagsToString(audio_output_flags_t flags)
Glenn Kasten97b7b752014-09-28 13:04:24 -0700469{
470 static const struct mapping {
471 audio_output_flags_t mFlag;
472 const char * mString;
473 } mappings[] = {
474 AUDIO_OUTPUT_FLAG_DIRECT, "DIRECT",
475 AUDIO_OUTPUT_FLAG_PRIMARY, "PRIMARY",
476 AUDIO_OUTPUT_FLAG_FAST, "FAST",
477 AUDIO_OUTPUT_FLAG_DEEP_BUFFER, "DEEP_BUFFER",
Glenn Kastendfb0e112015-02-18 14:33:39 -0800478 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD, "COMPRESS_OFFLOAD",
Glenn Kasten97b7b752014-09-28 13:04:24 -0700479 AUDIO_OUTPUT_FLAG_NON_BLOCKING, "NON_BLOCKING",
480 AUDIO_OUTPUT_FLAG_HW_AV_SYNC, "HW_AV_SYNC",
481 AUDIO_OUTPUT_FLAG_NONE, "NONE", // must be last
482 };
483 String8 result;
484 audio_output_flags_t allFlags = AUDIO_OUTPUT_FLAG_NONE;
485 const mapping *entry;
486 for (entry = mappings; entry->mFlag != AUDIO_OUTPUT_FLAG_NONE; entry++) {
487 allFlags = (audio_output_flags_t) (allFlags | entry->mFlag);
488 if (flags & entry->mFlag) {
489 if (!result.isEmpty()) {
490 result.append("|");
491 }
492 result.append(entry->mString);
493 }
494 }
495 if (flags & ~allFlags) {
496 if (!result.isEmpty()) {
497 result.append("|");
498 }
499 result.appendFormat("0x%X", flags & ~allFlags);
500 }
501 if (result.isEmpty()) {
502 result.append(entry->mString);
503 }
504 return result;
505}
506
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800507const char *sourceToString(audio_source_t source)
508{
509 switch (source) {
510 case AUDIO_SOURCE_DEFAULT: return "default";
511 case AUDIO_SOURCE_MIC: return "mic";
512 case AUDIO_SOURCE_VOICE_UPLINK: return "voice uplink";
513 case AUDIO_SOURCE_VOICE_DOWNLINK: return "voice downlink";
514 case AUDIO_SOURCE_VOICE_CALL: return "voice call";
515 case AUDIO_SOURCE_CAMCORDER: return "camcorder";
516 case AUDIO_SOURCE_VOICE_RECOGNITION: return "voice recognition";
517 case AUDIO_SOURCE_VOICE_COMMUNICATION: return "voice communication";
518 case AUDIO_SOURCE_REMOTE_SUBMIX: return "remote submix";
519 case AUDIO_SOURCE_FM_TUNER: return "FM tuner";
520 case AUDIO_SOURCE_HOTWORD: return "hotword";
521 default: return "unknown";
522 }
523}
524
Eric Laurent81784c32012-11-19 14:55:58 -0800525AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -0700526 audio_devices_t outDevice, audio_devices_t inDevice, type_t type, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -0800527 : Thread(false /*canCallJava*/),
528 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700529 mAudioFlinger(audioFlinger),
Glenn Kasten70949c42013-08-06 07:40:12 -0700530 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800531 // are set by PlaybackThread::readOutputParameters_l() or
532 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700533 //FIXME: mStandby should be true here. Is this some kind of hack?
Eric Laurent81784c32012-11-19 14:55:58 -0800534 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
Eric Laurente8726fe2015-06-26 09:39:24 -0700535 mPrevInDevice(AUDIO_DEVICE_NONE), mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Eric Laurent81784c32012-11-19 14:55:58 -0800536 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700537 mDeathRecipient(new PMDeathRecipient(this)),
538 mSystemReady(systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -0800539{
Eric Laurent296fb132015-05-01 11:38:42 -0700540 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800541}
542
543AudioFlinger::ThreadBase::~ThreadBase()
544{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700545 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700546 mConfigEvents.clear();
547
Eric Laurent81784c32012-11-19 14:55:58 -0800548 // do not lock the mutex in destructor
549 releaseWakeLock_l();
550 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800551 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800552 binder->unlinkToDeath(mDeathRecipient);
553 }
554}
555
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700556status_t AudioFlinger::ThreadBase::readyToRun()
557{
558 status_t status = initCheck();
559 if (status == NO_ERROR) {
560 ALOGI("AudioFlinger's thread %p ready to run", this);
561 } else {
562 ALOGE("No working audio driver found.");
563 }
564 return status;
565}
566
Eric Laurent81784c32012-11-19 14:55:58 -0800567void AudioFlinger::ThreadBase::exit()
568{
569 ALOGV("ThreadBase::exit");
570 // do any cleanup required for exit to succeed
571 preExit();
572 {
573 // This lock prevents the following race in thread (uniprocessor for illustration):
574 // if (!exitPending()) {
575 // // context switch from here to exit()
576 // // exit() calls requestExit(), what exitPending() observes
577 // // exit() calls signal(), which is dropped since no waiters
578 // // context switch back from exit() to here
579 // mWaitWorkCV.wait(...);
580 // // now thread is hung
581 // }
582 AutoMutex lock(mLock);
583 requestExit();
584 mWaitWorkCV.broadcast();
585 }
586 // When Thread::requestExitAndWait is made virtual and this method is renamed to
587 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
588 requestExitAndWait();
589}
590
591status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
592{
593 status_t status;
594
595 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
596 Mutex::Autolock _l(mLock);
597
Eric Laurent10351942014-05-08 18:49:52 -0700598 return sendSetParameterConfigEvent_l(keyValuePairs);
599}
600
601// sendConfigEvent_l() must be called with ThreadBase::mLock held
602// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
603status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
604{
605 status_t status = NO_ERROR;
606
Eric Laurent72e3f392015-05-20 14:43:50 -0700607 if (event->mRequiresSystemReady && !mSystemReady) {
608 event->mWaitStatus = false;
609 mPendingConfigEvents.add(event);
610 return status;
611 }
Eric Laurent10351942014-05-08 18:49:52 -0700612 mConfigEvents.add(event);
613 ALOGV("sendConfigEvent_l() num events %d event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800614 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700615 mLock.unlock();
616 {
617 Mutex::Autolock _l(event->mLock);
618 while (event->mWaitStatus) {
619 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
620 event->mStatus = TIMED_OUT;
621 event->mWaitStatus = false;
622 }
623 }
624 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800625 }
Eric Laurent10351942014-05-08 18:49:52 -0700626 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800627 return status;
628}
629
Eric Laurent73e26b62015-04-27 16:55:58 -0700630void AudioFlinger::ThreadBase::sendIoConfigEvent(audio_io_config_event event)
Eric Laurent81784c32012-11-19 14:55:58 -0800631{
632 Mutex::Autolock _l(mLock);
Eric Laurent73e26b62015-04-27 16:55:58 -0700633 sendIoConfigEvent_l(event);
Eric Laurent81784c32012-11-19 14:55:58 -0800634}
635
636// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
Eric Laurent73e26b62015-04-27 16:55:58 -0700637void AudioFlinger::ThreadBase::sendIoConfigEvent_l(audio_io_config_event event)
Eric Laurent81784c32012-11-19 14:55:58 -0800638{
Eric Laurent73e26b62015-04-27 16:55:58 -0700639 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event);
Eric Laurent10351942014-05-08 18:49:52 -0700640 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800641}
642
Eric Laurent72e3f392015-05-20 14:43:50 -0700643void AudioFlinger::ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio)
644{
645 Mutex::Autolock _l(mLock);
646 sendPrioConfigEvent_l(pid, tid, prio);
647}
648
Eric Laurent81784c32012-11-19 14:55:58 -0800649// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
650void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
651{
Eric Laurent10351942014-05-08 18:49:52 -0700652 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio);
653 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800654}
655
Eric Laurent10351942014-05-08 18:49:52 -0700656// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
657status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800658{
Eric Laurent10351942014-05-08 18:49:52 -0700659 sp<ConfigEvent> configEvent = (ConfigEvent *)new SetParameterConfigEvent(keyValuePair);
660 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700661}
662
Eric Laurent1c333e22014-05-20 10:48:17 -0700663status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
664 const struct audio_patch *patch,
665 audio_patch_handle_t *handle)
666{
667 Mutex::Autolock _l(mLock);
668 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
669 status_t status = sendConfigEvent_l(configEvent);
670 if (status == NO_ERROR) {
671 CreateAudioPatchConfigEventData *data =
672 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
673 *handle = data->mHandle;
674 }
675 return status;
676}
677
678status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
679 const audio_patch_handle_t handle)
680{
681 Mutex::Autolock _l(mLock);
682 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
683 return sendConfigEvent_l(configEvent);
684}
685
686
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700687// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700688void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700689{
Eric Laurent10351942014-05-08 18:49:52 -0700690 bool configChanged = false;
691
Eric Laurent81784c32012-11-19 14:55:58 -0800692 while (!mConfigEvents.isEmpty()) {
Eric Laurent10351942014-05-08 18:49:52 -0700693 ALOGV("processConfigEvents_l() remaining events %d", mConfigEvents.size());
694 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800695 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700696 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700697 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700698 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
699 // FIXME Need to understand why this has to be done asynchronously
700 int err = requestPriority(data->mPid, data->mTid, data->mPrio,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700701 true /*asynchronous*/);
702 if (err != 0) {
703 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700704 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700705 }
706 } break;
707 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700708 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent73e26b62015-04-27 16:55:58 -0700709 ioConfigChanged(data->mEvent);
Eric Laurent10351942014-05-08 18:49:52 -0700710 } break;
711 case CFG_EVENT_SET_PARAMETER: {
712 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
713 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
714 configChanged = true;
Glenn Kastend5418eb2013-08-14 13:11:06 -0700715 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700716 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700717 case CFG_EVENT_CREATE_AUDIO_PATCH: {
718 CreateAudioPatchConfigEventData *data =
719 (CreateAudioPatchConfigEventData *)event->mData.get();
720 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
721 } break;
722 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
723 ReleaseAudioPatchConfigEventData *data =
724 (ReleaseAudioPatchConfigEventData *)event->mData.get();
725 event->mStatus = releaseAudioPatch_l(data->mHandle);
726 } break;
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700727 default:
Eric Laurent10351942014-05-08 18:49:52 -0700728 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700729 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800730 }
Eric Laurent10351942014-05-08 18:49:52 -0700731 {
732 Mutex::Autolock _l(event->mLock);
733 if (event->mWaitStatus) {
734 event->mWaitStatus = false;
735 event->mCond.signal();
736 }
737 }
738 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
739 }
740
741 if (configChanged) {
742 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800743 }
Eric Laurent81784c32012-11-19 14:55:58 -0800744}
745
Marco Nelissenb2208842014-02-07 14:00:50 -0800746String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
747 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700748 const audio_channel_representation_t representation =
749 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700750
751 switch (representation) {
752 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
753 if (output) {
754 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
755 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
756 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
757 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
758 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
759 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
760 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
761 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
762 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
763 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
764 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
765 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
766 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
767 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
768 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
769 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
770 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
771 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
772 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
773 } else {
774 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
775 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
776 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
777 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
778 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
779 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
780 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
781 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
782 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
783 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
784 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
785 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
786 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
787 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
788 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
789 }
790 const int len = s.length();
791 if (len > 2) {
792 char *str = s.lockBuffer(len); // needed?
793 s.unlockBuffer(len - 2); // remove trailing ", "
794 }
795 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800796 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700797 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
798 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
799 return s;
800 default:
801 s.appendFormat("unknown mask, representation:%d bits:%#x",
802 representation, audio_channel_mask_get_bits(mask));
803 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800804 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800805}
806
Glenn Kasten0f11b512014-01-31 16:18:54 -0800807void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800808{
809 const size_t SIZE = 256;
810 char buffer[SIZE];
811 String8 result;
812
813 bool locked = AudioFlinger::dumpTryLock(mLock);
814 if (!locked) {
Glenn Kasten97b7b752014-09-28 13:04:24 -0700815 dprintf(fd, "thread %p may be deadlocked\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -0800816 }
817
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800818 dprintf(fd, " Thread name: %s\n", mThreadName);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700819 dprintf(fd, " I/O handle: %d\n", mId);
820 dprintf(fd, " TID: %d\n", getTid());
821 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700822 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700823 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700824 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat));
Elliott Hughes87cebad2014-05-22 10:14:43 -0700825 dprintf(fd, " HAL buffer size: %u bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700826 dprintf(fd, " Channel count: %u\n", mChannelCount);
827 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800828 channelMaskToString(mChannelMask, mType != RECORD).string());
Glenn Kasten97b7b752014-09-28 13:04:24 -0700829 dprintf(fd, " Format: 0x%x (%s)\n", mFormat, formatToString(mFormat));
830 dprintf(fd, " Frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700831 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800832 size_t numConfig = mConfigEvents.size();
833 if (numConfig) {
834 for (size_t i = 0; i < numConfig; i++) {
835 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700836 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800837 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700838 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800839 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700840 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800841 }
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800842 dprintf(fd, " Output device: %#x (%s)\n", mOutDevice, devicesToString(mOutDevice).string());
843 dprintf(fd, " Input device: %#x (%s)\n", mInDevice, devicesToString(mInDevice).string());
844 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, sourceToString(mAudioSource));
Eric Laurent81784c32012-11-19 14:55:58 -0800845
846 if (locked) {
847 mLock.unlock();
848 }
849}
850
851void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
852{
853 const size_t SIZE = 256;
854 char buffer[SIZE];
855 String8 result;
856
Marco Nelissenb2208842014-02-07 14:00:50 -0800857 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000858 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800859 write(fd, buffer, strlen(buffer));
860
Marco Nelissenb2208842014-02-07 14:00:50 -0800861 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800862 sp<EffectChain> chain = mEffectChains[i];
863 if (chain != 0) {
864 chain->dump(fd, args);
865 }
866 }
867}
868
Marco Nelissene14a5d62013-10-03 08:51:24 -0700869void AudioFlinger::ThreadBase::acquireWakeLock(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800870{
871 Mutex::Autolock _l(mLock);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700872 acquireWakeLock_l(uid);
Eric Laurent81784c32012-11-19 14:55:58 -0800873}
874
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100875String16 AudioFlinger::ThreadBase::getWakeLockTag()
876{
877 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -0800878 case MIXER:
879 return String16("AudioMix");
880 case DIRECT:
881 return String16("AudioDirectOut");
882 case DUPLICATING:
883 return String16("AudioDup");
884 case RECORD:
885 return String16("AudioIn");
886 case OFFLOAD:
887 return String16("AudioOffload");
888 default:
889 ALOG_ASSERT(false);
890 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100891 }
892}
893
Marco Nelissene14a5d62013-10-03 08:51:24 -0700894void AudioFlinger::ThreadBase::acquireWakeLock_l(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800895{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800896 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800897 if (mPowerManager != 0) {
898 sp<IBinder> binder = new BBinder();
Marco Nelissene14a5d62013-10-03 08:51:24 -0700899 status_t status;
900 if (uid >= 0) {
Eric Laurent547789d2013-10-04 11:46:55 -0700901 status = mPowerManager->acquireWakeLockWithUid(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700902 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100903 getWakeLockTag(),
Marco Nelissene14a5d62013-10-03 08:51:24 -0700904 String16("media"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700905 uid,
906 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700907 } else {
Eric Laurent547789d2013-10-04 11:46:55 -0700908 status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700909 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100910 getWakeLockTag(),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700911 String16("media"),
912 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700913 }
Eric Laurent81784c32012-11-19 14:55:58 -0800914 if (status == NO_ERROR) {
915 mWakeLockToken = binder;
916 }
Glenn Kastend7dca052015-03-05 16:05:54 -0800917 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Eric Laurent81784c32012-11-19 14:55:58 -0800918 }
919}
920
921void AudioFlinger::ThreadBase::releaseWakeLock()
922{
923 Mutex::Autolock _l(mLock);
924 releaseWakeLock_l();
925}
926
927void AudioFlinger::ThreadBase::releaseWakeLock_l()
928{
929 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800930 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -0800931 if (mPowerManager != 0) {
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700932 mPowerManager->releaseWakeLock(mWakeLockToken, 0,
933 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800934 }
935 mWakeLockToken.clear();
936 }
937}
938
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800939void AudioFlinger::ThreadBase::updateWakeLockUids(const SortedVector<int> &uids) {
940 Mutex::Autolock _l(mLock);
941 updateWakeLockUids_l(uids);
942}
943
944void AudioFlinger::ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -0700945 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800946 // use checkService() to avoid blocking if power service is not up yet
947 sp<IBinder> binder =
948 defaultServiceManager()->checkService(String16("power"));
949 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800950 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800951 } else {
952 mPowerManager = interface_cast<IPowerManager>(binder);
953 binder->linkToDeath(mDeathRecipient);
954 }
955 }
956}
957
958void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<int> &uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800959 getPowerManager_l();
960 if (mWakeLockToken == NULL) {
961 ALOGE("no wake lock to update!");
962 return;
963 }
964 if (mPowerManager != 0) {
965 sp<IBinder> binder = new BBinder();
966 status_t status;
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700967 status = mPowerManager->updateWakeLockUids(mWakeLockToken, uids.size(), uids.array(),
968 true /* FIXME force oneway contrary to .aidl */);
Glenn Kastend7dca052015-03-05 16:05:54 -0800969 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800970 }
971}
972
Eric Laurent81784c32012-11-19 14:55:58 -0800973void AudioFlinger::ThreadBase::clearPowerManager()
974{
975 Mutex::Autolock _l(mLock);
976 releaseWakeLock_l();
977 mPowerManager.clear();
978}
979
Glenn Kasten0f11b512014-01-31 16:18:54 -0800980void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800981{
982 sp<ThreadBase> thread = mThread.promote();
983 if (thread != 0) {
984 thread->clearPowerManager();
985 }
986 ALOGW("power manager service died !!!");
987}
988
989void AudioFlinger::ThreadBase::setEffectSuspended(
990 const effect_uuid_t *type, bool suspend, int sessionId)
991{
992 Mutex::Autolock _l(mLock);
993 setEffectSuspended_l(type, suspend, sessionId);
994}
995
996void AudioFlinger::ThreadBase::setEffectSuspended_l(
997 const effect_uuid_t *type, bool suspend, int sessionId)
998{
999 sp<EffectChain> chain = getEffectChain_l(sessionId);
1000 if (chain != 0) {
1001 if (type != NULL) {
1002 chain->setEffectSuspended_l(type, suspend);
1003 } else {
1004 chain->setEffectSuspendedAll_l(suspend);
1005 }
1006 }
1007
1008 updateSuspendedSessions_l(type, suspend, sessionId);
1009}
1010
1011void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1012{
1013 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1014 if (index < 0) {
1015 return;
1016 }
1017
1018 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1019 mSuspendedSessions.valueAt(index);
1020
1021 for (size_t i = 0; i < sessionEffects.size(); i++) {
1022 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
1023 for (int j = 0; j < desc->mRefCount; j++) {
1024 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1025 chain->setEffectSuspendedAll_l(true);
1026 } else {
1027 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1028 desc->mType.timeLow);
1029 chain->setEffectSuspended_l(&desc->mType, true);
1030 }
1031 }
1032 }
1033}
1034
1035void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1036 bool suspend,
1037 int sessionId)
1038{
1039 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1040
1041 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1042
1043 if (suspend) {
1044 if (index >= 0) {
1045 sessionEffects = mSuspendedSessions.valueAt(index);
1046 } else {
1047 mSuspendedSessions.add(sessionId, sessionEffects);
1048 }
1049 } else {
1050 if (index < 0) {
1051 return;
1052 }
1053 sessionEffects = mSuspendedSessions.valueAt(index);
1054 }
1055
1056
1057 int key = EffectChain::kKeyForSuspendAll;
1058 if (type != NULL) {
1059 key = type->timeLow;
1060 }
1061 index = sessionEffects.indexOfKey(key);
1062
1063 sp<SuspendedSessionDesc> desc;
1064 if (suspend) {
1065 if (index >= 0) {
1066 desc = sessionEffects.valueAt(index);
1067 } else {
1068 desc = new SuspendedSessionDesc();
1069 if (type != NULL) {
1070 desc->mType = *type;
1071 }
1072 sessionEffects.add(key, desc);
1073 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1074 }
1075 desc->mRefCount++;
1076 } else {
1077 if (index < 0) {
1078 return;
1079 }
1080 desc = sessionEffects.valueAt(index);
1081 if (--desc->mRefCount == 0) {
1082 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1083 sessionEffects.removeItemsAt(index);
1084 if (sessionEffects.isEmpty()) {
1085 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1086 sessionId);
1087 mSuspendedSessions.removeItem(sessionId);
1088 }
1089 }
1090 }
1091 if (!sessionEffects.isEmpty()) {
1092 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1093 }
1094}
1095
1096void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1097 bool enabled,
1098 int sessionId)
1099{
1100 Mutex::Autolock _l(mLock);
1101 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1102}
1103
1104void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1105 bool enabled,
1106 int sessionId)
1107{
1108 if (mType != RECORD) {
1109 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1110 // another session. This gives the priority to well behaved effect control panels
1111 // and applications not using global effects.
1112 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1113 // global effects
1114 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
1115 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1116 }
1117 }
1118
1119 sp<EffectChain> chain = getEffectChain_l(sessionId);
1120 if (chain != 0) {
1121 chain->checkSuspendOnEffectEnabled(effect, enabled);
1122 }
1123}
1124
1125// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1126sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1127 const sp<AudioFlinger::Client>& client,
1128 const sp<IEffectClient>& effectClient,
1129 int32_t priority,
1130 int sessionId,
1131 effect_descriptor_t *desc,
1132 int *enabled,
Glenn Kasten9156ef32013-08-06 15:39:08 -07001133 status_t *status)
Eric Laurent81784c32012-11-19 14:55:58 -08001134{
1135 sp<EffectModule> effect;
1136 sp<EffectHandle> handle;
1137 status_t lStatus;
1138 sp<EffectChain> chain;
1139 bool chainCreated = false;
1140 bool effectCreated = false;
1141 bool effectRegistered = false;
1142
1143 lStatus = initCheck();
1144 if (lStatus != NO_ERROR) {
1145 ALOGW("createEffect_l() Audio driver not initialized.");
1146 goto Exit;
1147 }
1148
Andy Hung98ef9782014-03-04 14:46:50 -08001149 // Reject any effect on Direct output threads for now, since the format of
1150 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1151 if (mType == DIRECT) {
1152 ALOGW("createEffect_l() Cannot add effect %s on Direct output type thread %s",
Glenn Kastend7dca052015-03-05 16:05:54 -08001153 desc->name, mThreadName);
Andy Hung98ef9782014-03-04 14:46:50 -08001154 lStatus = BAD_VALUE;
1155 goto Exit;
1156 }
1157
Andy Hung389cfdb2014-08-07 17:49:53 -07001158 // Reject any effect on mixer or duplicating multichannel sinks.
Andy Hung9a592762014-07-21 21:56:01 -07001159 // TODO: fix both format and multichannel issues with effects.
Andy Hung389cfdb2014-08-07 17:49:53 -07001160 if ((mType == MIXER || mType == DUPLICATING) && mChannelCount != FCC_2) {
1161 ALOGW("createEffect_l() Cannot add effect %s for multichannel(%d) %s threads",
1162 desc->name, mChannelCount, mType == MIXER ? "MIXER" : "DUPLICATING");
Andy Hung9a592762014-07-21 21:56:01 -07001163 lStatus = BAD_VALUE;
1164 goto Exit;
1165 }
1166
Eric Laurent5baf2af2013-09-12 17:37:00 -07001167 // Allow global effects only on offloaded and mixer threads
1168 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1169 switch (mType) {
1170 case MIXER:
1171 case OFFLOAD:
1172 break;
1173 case DIRECT:
1174 case DUPLICATING:
1175 case RECORD:
1176 default:
Glenn Kastend7dca052015-03-05 16:05:54 -08001177 ALOGW("createEffect_l() Cannot add global effect %s on thread %s",
1178 desc->name, mThreadName);
Eric Laurent5baf2af2013-09-12 17:37:00 -07001179 lStatus = BAD_VALUE;
1180 goto Exit;
1181 }
Eric Laurent81784c32012-11-19 14:55:58 -08001182 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07001183
Eric Laurent81784c32012-11-19 14:55:58 -08001184 // Only Pre processor effects are allowed on input threads and only on input threads
1185 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
1186 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
1187 desc->name, desc->flags, mType);
1188 lStatus = BAD_VALUE;
1189 goto Exit;
1190 }
1191
1192 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1193
1194 { // scope for mLock
1195 Mutex::Autolock _l(mLock);
1196
1197 // check for existing effect chain with the requested audio session
1198 chain = getEffectChain_l(sessionId);
1199 if (chain == 0) {
1200 // create a new chain for this session
1201 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1202 chain = new EffectChain(this, sessionId);
1203 addEffectChain_l(chain);
1204 chain->setStrategy(getStrategyForSession_l(sessionId));
1205 chainCreated = true;
1206 } else {
1207 effect = chain->getEffectFromDesc_l(desc);
1208 }
1209
1210 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1211
1212 if (effect == 0) {
1213 int id = mAudioFlinger->nextUniqueId();
1214 // Check CPU and memory usage
1215 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
1216 if (lStatus != NO_ERROR) {
1217 goto Exit;
1218 }
1219 effectRegistered = true;
1220 // create a new effect module if none present in the chain
1221 effect = new EffectModule(this, chain, desc, id, sessionId);
1222 lStatus = effect->status();
1223 if (lStatus != NO_ERROR) {
1224 goto Exit;
1225 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07001226 effect->setOffloaded(mType == OFFLOAD, mId);
1227
Eric Laurent81784c32012-11-19 14:55:58 -08001228 lStatus = chain->addEffect_l(effect);
1229 if (lStatus != NO_ERROR) {
1230 goto Exit;
1231 }
1232 effectCreated = true;
1233
1234 effect->setDevice(mOutDevice);
1235 effect->setDevice(mInDevice);
1236 effect->setMode(mAudioFlinger->getMode());
1237 effect->setAudioSource(mAudioSource);
1238 }
1239 // create effect handle and connect it to effect module
1240 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001241 lStatus = handle->initCheck();
1242 if (lStatus == OK) {
1243 lStatus = effect->addHandle(handle.get());
1244 }
Eric Laurent81784c32012-11-19 14:55:58 -08001245 if (enabled != NULL) {
1246 *enabled = (int)effect->isEnabled();
1247 }
1248 }
1249
1250Exit:
1251 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1252 Mutex::Autolock _l(mLock);
1253 if (effectCreated) {
1254 chain->removeEffect_l(effect);
1255 }
1256 if (effectRegistered) {
1257 AudioSystem::unregisterEffect(effect->id());
1258 }
1259 if (chainCreated) {
1260 removeEffectChain_l(chain);
1261 }
1262 handle.clear();
1263 }
1264
Glenn Kasten9156ef32013-08-06 15:39:08 -07001265 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001266 return handle;
1267}
1268
1269sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
1270{
1271 Mutex::Autolock _l(mLock);
1272 return getEffect_l(sessionId, effectId);
1273}
1274
1275sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
1276{
1277 sp<EffectChain> chain = getEffectChain_l(sessionId);
1278 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1279}
1280
1281// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1282// PlaybackThread::mLock held
1283status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1284{
1285 // check for existing effect chain with the requested audio session
1286 int sessionId = effect->sessionId();
1287 sp<EffectChain> chain = getEffectChain_l(sessionId);
1288 bool chainCreated = false;
1289
Eric Laurent5baf2af2013-09-12 17:37:00 -07001290 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
1291 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
1292 this, effect->desc().name, effect->desc().flags);
1293
Eric Laurent81784c32012-11-19 14:55:58 -08001294 if (chain == 0) {
1295 // create a new chain for this session
1296 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1297 chain = new EffectChain(this, sessionId);
1298 addEffectChain_l(chain);
1299 chain->setStrategy(getStrategyForSession_l(sessionId));
1300 chainCreated = true;
1301 }
1302 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1303
1304 if (chain->getEffectFromId_l(effect->id()) != 0) {
1305 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1306 this, effect->desc().name, chain.get());
1307 return BAD_VALUE;
1308 }
1309
Eric Laurent5baf2af2013-09-12 17:37:00 -07001310 effect->setOffloaded(mType == OFFLOAD, mId);
1311
Eric Laurent81784c32012-11-19 14:55:58 -08001312 status_t status = chain->addEffect_l(effect);
1313 if (status != NO_ERROR) {
1314 if (chainCreated) {
1315 removeEffectChain_l(chain);
1316 }
1317 return status;
1318 }
1319
1320 effect->setDevice(mOutDevice);
1321 effect->setDevice(mInDevice);
1322 effect->setMode(mAudioFlinger->getMode());
1323 effect->setAudioSource(mAudioSource);
1324 return NO_ERROR;
1325}
1326
1327void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
1328
1329 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
1330 effect_descriptor_t desc = effect->desc();
1331 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1332 detachAuxEffect_l(effect->id());
1333 }
1334
1335 sp<EffectChain> chain = effect->chain().promote();
1336 if (chain != 0) {
1337 // remove effect chain if removing last effect
1338 if (chain->removeEffect_l(effect) == 0) {
1339 removeEffectChain_l(chain);
1340 }
1341 } else {
1342 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1343 }
1344}
1345
1346void AudioFlinger::ThreadBase::lockEffectChains_l(
1347 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1348{
1349 effectChains = mEffectChains;
1350 for (size_t i = 0; i < mEffectChains.size(); i++) {
1351 mEffectChains[i]->lock();
1352 }
1353}
1354
1355void AudioFlinger::ThreadBase::unlockEffectChains(
1356 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1357{
1358 for (size_t i = 0; i < effectChains.size(); i++) {
1359 effectChains[i]->unlock();
1360 }
1361}
1362
1363sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
1364{
1365 Mutex::Autolock _l(mLock);
1366 return getEffectChain_l(sessionId);
1367}
1368
1369sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const
1370{
1371 size_t size = mEffectChains.size();
1372 for (size_t i = 0; i < size; i++) {
1373 if (mEffectChains[i]->sessionId() == sessionId) {
1374 return mEffectChains[i];
1375 }
1376 }
1377 return 0;
1378}
1379
1380void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1381{
1382 Mutex::Autolock _l(mLock);
1383 size_t size = mEffectChains.size();
1384 for (size_t i = 0; i < size; i++) {
1385 mEffectChains[i]->setMode_l(mode);
1386 }
1387}
1388
Eric Laurent83b88082014-06-20 18:31:16 -07001389void AudioFlinger::ThreadBase::getAudioPortConfig(struct audio_port_config *config)
1390{
1391 config->type = AUDIO_PORT_TYPE_MIX;
1392 config->ext.mix.handle = mId;
1393 config->sample_rate = mSampleRate;
1394 config->format = mFormat;
1395 config->channel_mask = mChannelMask;
1396 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1397 AUDIO_PORT_CONFIG_FORMAT;
1398}
1399
Eric Laurent72e3f392015-05-20 14:43:50 -07001400void AudioFlinger::ThreadBase::systemReady()
1401{
1402 Mutex::Autolock _l(mLock);
1403 if (mSystemReady) {
1404 return;
1405 }
1406 mSystemReady = true;
1407
1408 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1409 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1410 }
1411 mPendingConfigEvents.clear();
1412}
1413
Eric Laurent83b88082014-06-20 18:31:16 -07001414
Eric Laurent81784c32012-11-19 14:55:58 -08001415// ----------------------------------------------------------------------------
1416// Playback
1417// ----------------------------------------------------------------------------
1418
1419AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1420 AudioStreamOut* output,
1421 audio_io_handle_t id,
1422 audio_devices_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07001423 type_t type,
1424 bool systemReady)
1425 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type, systemReady),
Andy Hung2098f272014-02-27 14:00:06 -08001426 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001427 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001428 mMixerBuffer(NULL),
1429 mMixerBufferSize(0),
1430 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1431 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001432 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001433 mEffectBuffer(NULL),
1434 mEffectBufferSize(0),
1435 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1436 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001437 mSuspended(0), mBytesWritten(0),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001438 mActiveTracksGeneration(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001439 // mStreamTypes[] initialized in constructor body
1440 mOutput(output),
1441 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
1442 mMixerStatus(MIXER_IDLE),
1443 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001444 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001445 mBytesRemaining(0),
1446 mCurrentWriteLength(0),
1447 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001448 mWriteAckSequence(0),
1449 mDrainSequence(0),
Eric Laurentede6c3b2013-09-19 14:37:46 -07001450 mSignalPending(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001451 mScreenState(AudioFlinger::mScreenState),
1452 // index 0 is reserved for normal mixer's submix
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001453 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1),
Eric Laurentd1f69b02014-12-15 14:33:13 -08001454 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001455 // mLatchD, mLatchQ,
1456 mLatchDValid(false), mLatchQValid(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001457{
Glenn Kastend7dca052015-03-05 16:05:54 -08001458 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1459 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001460
1461 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1462 // it would be safer to explicitly pass initial masterVolume/masterMute as
1463 // parameter.
1464 //
1465 // If the HAL we are using has support for master volume or master mute,
1466 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1467 // and the mute set to false).
1468 mMasterVolume = audioFlinger->masterVolume_l();
1469 mMasterMute = audioFlinger->masterMute_l();
1470 if (mOutput && mOutput->audioHwDev) {
1471 if (mOutput->audioHwDev->canSetMasterVolume()) {
1472 mMasterVolume = 1.0;
1473 }
1474
1475 if (mOutput->audioHwDev->canSetMasterMute()) {
1476 mMasterMute = false;
1477 }
1478 }
1479
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001480 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001481
Eric Laurent223fd5c2014-11-11 13:43:36 -08001482 // ++ operator does not compile
Glenn Kasten66e46352014-01-16 17:44:23 -08001483 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001484 stream = (audio_stream_type_t) (stream + 1)) {
1485 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1486 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1487 }
Eric Laurent81784c32012-11-19 14:55:58 -08001488}
1489
1490AudioFlinger::PlaybackThread::~PlaybackThread()
1491{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001492 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001493 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001494 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001495 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001496}
1497
1498void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1499{
1500 dumpInternals(fd, args);
1501 dumpTracks(fd, args);
1502 dumpEffectChains(fd, args);
1503}
1504
Glenn Kasten0f11b512014-01-31 16:18:54 -08001505void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001506{
1507 const size_t SIZE = 256;
1508 char buffer[SIZE];
1509 String8 result;
1510
Marco Nelissenb2208842014-02-07 14:00:50 -08001511 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001512 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1513 const stream_type_t *st = &mStreamTypes[i];
1514 if (i > 0) {
1515 result.appendFormat(", ");
1516 }
1517 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1518 if (st->mute) {
1519 result.append("M");
1520 }
1521 }
1522 result.append("\n");
1523 write(fd, result.string(), result.length());
1524 result.clear();
1525
Eric Laurent81784c32012-11-19 14:55:58 -08001526 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1527 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001528 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001529 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001530
1531 size_t numtracks = mTracks.size();
1532 size_t numactive = mActiveTracks.size();
Elliott Hughes87cebad2014-05-22 10:14:43 -07001533 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001534 size_t numactiveseen = 0;
1535 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07001536 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08001537 Track::appendDumpHeader(result);
1538 for (size_t i = 0; i < numtracks; ++i) {
1539 sp<Track> track = mTracks[i];
1540 if (track != 0) {
1541 bool active = mActiveTracks.indexOf(track) >= 0;
1542 if (active) {
1543 numactiveseen++;
1544 }
1545 track->dump(buffer, SIZE, active);
1546 result.append(buffer);
1547 }
1548 }
1549 } else {
1550 result.append("\n");
1551 }
1552 if (numactiveseen != numactive) {
1553 // some tracks in the active list were not in the tracks list
1554 snprintf(buffer, SIZE, " The following tracks are in the active list but"
1555 " not in the track list\n");
1556 result.append(buffer);
1557 Track::appendDumpHeader(result);
1558 for (size_t i = 0; i < numactive; ++i) {
1559 sp<Track> track = mActiveTracks[i].promote();
1560 if (track != 0 && mTracks.indexOf(track) < 0) {
1561 track->dump(buffer, SIZE, true);
1562 result.append(buffer);
1563 }
1564 }
1565 }
1566
1567 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001568}
1569
1570void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1571{
Glenn Kasten97b7b752014-09-28 13:04:24 -07001572 dprintf(fd, "\nOutput thread %p type %d (%s):\n", this, type(), threadTypeToString(type()));
Glenn Kasten44182c22015-03-05 17:12:23 -08001573
1574 dumpBase(fd, args);
1575
Elliott Hughes87cebad2014-05-22 10:14:43 -07001576 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
1577 dprintf(fd, " Last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1578 dprintf(fd, " Total writes: %d\n", mNumWrites);
1579 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1580 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1581 dprintf(fd, " Suspend count: %d\n", mSuspended);
1582 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1583 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1584 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1585 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001586 AudioStreamOut *output = mOutput;
1587 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
1588 String8 flagsAsString = outputFlagsToString(flags);
1589 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n", output, flags, flagsAsString.string());
Eric Laurent81784c32012-11-19 14:55:58 -08001590}
1591
1592// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001593
1594void AudioFlinger::PlaybackThread::onFirstRef()
1595{
Glenn Kastend7dca052015-03-05 16:05:54 -08001596 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001597}
1598
1599// ThreadBase virtuals
1600void AudioFlinger::PlaybackThread::preExit()
1601{
1602 ALOGV(" preExit()");
1603 // FIXME this is using hard-coded strings but in the future, this functionality will be
1604 // converted to use audio HAL extensions required to support tunneling
1605 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1606}
1607
1608// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1609sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1610 const sp<AudioFlinger::Client>& client,
1611 audio_stream_type_t streamType,
1612 uint32_t sampleRate,
1613 audio_format_t format,
1614 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001615 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001616 const sp<IMemory>& sharedBuffer,
1617 int sessionId,
1618 IAudioFlinger::track_flags_t *flags,
1619 pid_t tid,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001620 int uid,
Eric Laurent81784c32012-11-19 14:55:58 -08001621 status_t *status)
1622{
Glenn Kasten74935e42013-12-19 08:56:45 -08001623 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001624 sp<Track> track;
1625 status_t lStatus;
1626
1627 bool isTimed = (*flags & IAudioFlinger::TRACK_TIMED) != 0;
1628
1629 // client expresses a preference for FAST, but we get the final say
1630 if (*flags & IAudioFlinger::TRACK_FAST) {
1631 if (
1632 // not timed
1633 (!isTimed) &&
1634 // either of these use cases:
1635 (
1636 // use case 1: shared buffer with any frame count
1637 (
1638 (sharedBuffer != 0)
1639 ) ||
Glenn Kasten1dfe2f92015-03-09 12:03:14 -07001640 // use case 2: frame count is default or at least as large as HAL
Eric Laurent81784c32012-11-19 14:55:58 -08001641 (
Glenn Kasten1dfe2f92015-03-09 12:03:14 -07001642 // we formerly checked for a callback handler (non-0 tid),
1643 // but that is no longer required for TRANSFER_OBTAIN mode
Eric Laurent81784c32012-11-19 14:55:58 -08001644 ((frameCount == 0) ||
Glenn Kastenb5fed682013-12-03 09:06:43 -08001645 (frameCount >= mFrameCount))
Eric Laurent81784c32012-11-19 14:55:58 -08001646 )
1647 ) &&
1648 // PCM data
1649 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07001650 // TODO: extract as a data library function that checks that a computationally
1651 // expensive downmixer is not required: isFastOutputChannelConversion()
Andy Hung9a592762014-07-21 21:56:01 -07001652 (channelMask == mChannelMask ||
Andy Hung1f439e12015-05-19 12:57:41 -07001653 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
1654 (channelMask == AUDIO_CHANNEL_OUT_MONO
1655 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001656 // hardware sample rate
1657 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001658 // normal mixer has an associated fast mixer
1659 hasFastMixer() &&
1660 // there are sufficient fast track slots available
1661 (mFastTrackAvailMask != 0)
1662 // FIXME test that MixerThread for this fast track has a capable output HAL
1663 // FIXME add a permission test also?
1664 ) {
1665 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1666 if (frameCount == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001667 // read the fast track multiplier property the first time it is needed
1668 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1669 if (ok != 0) {
1670 ALOGE("%s pthread_once failed: %d", __func__, ok);
1671 }
1672 frameCount = mFrameCount * sFastTrackMultiplier;
Eric Laurent81784c32012-11-19 14:55:58 -08001673 }
1674 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
1675 frameCount, mFrameCount);
1676 } else {
1677 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
Andy Hung6146c082014-03-18 11:56:15 -07001678 "mFrameCount=%d format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
1679 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001680 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Andy Hung6146c082014-03-18 11:56:15 -07001681 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001682 audio_is_linear_pcm(format),
1683 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
1684 *flags &= ~IAudioFlinger::TRACK_FAST;
Andy Hung0e48d252015-01-26 11:43:15 -08001685 }
1686 }
1687 // For normal PCM streaming tracks, update minimum frame count.
1688 // For compatibility with AudioTrack calculation, buffer depth is forced
1689 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1690 // This is probably too conservative, but legacy application code may depend on it.
1691 // If you change this calculation, also review the start threshold which is related.
1692 if (!(*flags & IAudioFlinger::TRACK_FAST)
1693 && audio_is_linear_pcm(format) && sharedBuffer == 0) {
Andy Hung8edb8dc2015-03-26 19:13:55 -07001694 // this must match AudioTrack.cpp calculateMinFrameCount().
1695 // TODO: Move to a common library
Eric Laurent81784c32012-11-19 14:55:58 -08001696 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1697 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1698 if (minBufCount < 2) {
1699 minBufCount = 2;
1700 }
Andy Hung8edb8dc2015-03-26 19:13:55 -07001701 // For normal mixing tracks, if speed is > 1.0f (normal), AudioTrack
1702 // or the client should compute and pass in a larger buffer request.
Andy Hung0e48d252015-01-26 11:43:15 -08001703 size_t minFrameCount =
Andy Hung8edb8dc2015-03-26 19:13:55 -07001704 minBufCount * sourceFramesNeededWithTimestretch(
1705 sampleRate, mNormalFrameCount,
1706 mSampleRate, AUDIO_TIMESTRETCH_SPEED_NORMAL /*speed*/);
Andy Hung0e48d252015-01-26 11:43:15 -08001707 if (frameCount < minFrameCount) { // including frameCount == 0
Eric Laurent81784c32012-11-19 14:55:58 -08001708 frameCount = minFrameCount;
1709 }
Eric Laurent81784c32012-11-19 14:55:58 -08001710 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001711 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001712
Glenn Kastenc3df8382014-03-13 15:05:25 -07001713 switch (mType) {
1714
1715 case DIRECT:
Glenn Kasten993fa062014-05-02 11:14:34 -07001716 if (audio_is_linear_pcm(format)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001717 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001718 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1719 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001720 sampleRate, format, channelMask, mOutput, mFormat);
1721 lStatus = BAD_VALUE;
1722 goto Exit;
1723 }
1724 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001725 break;
1726
1727 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001728 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001729 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1730 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001731 sampleRate, format, channelMask, mOutput, mFormat);
1732 lStatus = BAD_VALUE;
1733 goto Exit;
1734 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001735 break;
1736
1737 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07001738 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001739 ALOGE("createTrack_l() Bad parameter: format %#x \""
1740 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001741 format, mOutput, mFormat);
1742 lStatus = BAD_VALUE;
1743 goto Exit;
1744 }
Andy Hungcd044842014-08-07 11:04:34 -07001745 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08001746 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1747 lStatus = BAD_VALUE;
1748 goto Exit;
1749 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001750 break;
1751
Eric Laurent81784c32012-11-19 14:55:58 -08001752 }
1753
1754 lStatus = initCheck();
1755 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07001756 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08001757 goto Exit;
1758 }
1759
1760 { // scope for mLock
1761 Mutex::Autolock _l(mLock);
1762
1763 // all tracks in same audio session must share the same routing strategy otherwise
1764 // conflicts will happen when tracks are moved from one output to another by audio policy
1765 // manager
1766 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1767 for (size_t i = 0; i < mTracks.size(); ++i) {
1768 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07001769 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001770 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1771 if (sessionId == t->sessionId() && strategy != actual) {
1772 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1773 strategy, actual);
1774 lStatus = BAD_VALUE;
1775 goto Exit;
1776 }
1777 }
1778 }
1779
1780 if (!isTimed) {
1781 track = new Track(this, client, streamType, sampleRate, format,
Eric Laurent83b88082014-06-20 18:31:16 -07001782 channelMask, frameCount, NULL, sharedBuffer,
1783 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08001784 } else {
1785 track = TimedTrack::create(this, client, streamType, sampleRate, format,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001786 channelMask, frameCount, sharedBuffer, sessionId, uid);
Eric Laurent81784c32012-11-19 14:55:58 -08001787 }
Glenn Kasten03003332013-08-06 15:40:54 -07001788
1789 // new Track always returns non-NULL,
1790 // but TimedTrack::create() is a factory that could fail by returning NULL
1791 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
1792 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08001793 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001794 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08001795 goto Exit;
1796 }
1797 mTracks.add(track);
1798
1799 sp<EffectChain> chain = getEffectChain_l(sessionId);
1800 if (chain != 0) {
1801 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1802 track->setMainBuffer(chain->inBuffer());
1803 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1804 chain->incTrackCnt();
1805 }
1806
1807 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1808 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1809 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1810 // so ask activity manager to do this on our behalf
1811 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1812 }
1813 }
1814
1815 lStatus = NO_ERROR;
1816
1817Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001818 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001819 return track;
1820}
1821
1822uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1823{
1824 return latency;
1825}
1826
1827uint32_t AudioFlinger::PlaybackThread::latency() const
1828{
1829 Mutex::Autolock _l(mLock);
1830 return latency_l();
1831}
1832uint32_t AudioFlinger::PlaybackThread::latency_l() const
1833{
1834 if (initCheck() == NO_ERROR) {
1835 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
1836 } else {
1837 return 0;
1838 }
1839}
1840
1841void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1842{
1843 Mutex::Autolock _l(mLock);
1844 // Don't apply master volume in SW if our HAL can do it for us.
1845 if (mOutput && mOutput->audioHwDev &&
1846 mOutput->audioHwDev->canSetMasterVolume()) {
1847 mMasterVolume = 1.0;
1848 } else {
1849 mMasterVolume = value;
1850 }
1851}
1852
1853void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1854{
1855 Mutex::Autolock _l(mLock);
1856 // Don't apply master mute in SW if our HAL can do it for us.
1857 if (mOutput && mOutput->audioHwDev &&
1858 mOutput->audioHwDev->canSetMasterMute()) {
1859 mMasterMute = false;
1860 } else {
1861 mMasterMute = muted;
1862 }
1863}
1864
1865void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
1866{
1867 Mutex::Autolock _l(mLock);
1868 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001869 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001870}
1871
1872void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
1873{
1874 Mutex::Autolock _l(mLock);
1875 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001876 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001877}
1878
1879float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
1880{
1881 Mutex::Autolock _l(mLock);
1882 return mStreamTypes[stream].volume;
1883}
1884
1885// addTrack_l() must be called with ThreadBase::mLock held
1886status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1887{
1888 status_t status = ALREADY_EXISTS;
1889
1890 // set retry count for buffer fill
1891 track->mRetryCount = kMaxTrackStartupRetries;
1892 if (mActiveTracks.indexOf(track) < 0) {
1893 // the track is newly added, make sure it fills up all its
1894 // buffers before playing. This is to ensure the client will
1895 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07001896 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001897 TrackBase::track_state state = track->mState;
1898 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08001899 status = AudioSystem::startOutput(mId, track->streamType(),
1900 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001901 mLock.lock();
1902 // abort track was stopped/paused while we released the lock
1903 if (state != track->mState) {
1904 if (status == NO_ERROR) {
1905 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08001906 AudioSystem::stopOutput(mId, track->streamType(),
1907 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001908 mLock.lock();
1909 }
1910 return INVALID_OPERATION;
1911 }
1912 // abort if start is rejected by audio policy manager
1913 if (status != NO_ERROR) {
1914 return PERMISSION_DENIED;
1915 }
1916#ifdef ADD_BATTERY_DATA
1917 // to track the speaker usage
1918 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
1919#endif
1920 }
1921
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001922 track->mFillingUpStatus = track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent81784c32012-11-19 14:55:58 -08001923 track->mResetDone = false;
1924 track->mPresentationCompleteFrames = 0;
1925 mActiveTracks.add(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001926 mWakeLockUids.add(track->uid());
1927 mActiveTracksGeneration++;
Eric Laurentfd477972013-10-25 18:10:40 -07001928 mLatestActiveTrack = track;
Eric Laurentd0107bc2013-06-11 14:38:48 -07001929 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1930 if (chain != 0) {
1931 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
1932 track->sessionId());
1933 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08001934 }
1935
1936 status = NO_ERROR;
1937 }
1938
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08001939 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001940 return status;
1941}
1942
Eric Laurentbfb1b832013-01-07 09:53:42 -08001943bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08001944{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001945 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08001946 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001947 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
1948 track->mState = TrackBase::STOPPED;
1949 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08001950 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07001951 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001952 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08001953 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001954
1955 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08001956}
1957
1958void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1959{
1960 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
1961 mTracks.remove(track);
1962 deleteTrackName_l(track->name());
1963 // redundant as track is about to be destroyed, for dumpsys only
1964 track->mName = -1;
1965 if (track->isFastTrack()) {
1966 int index = track->mFastIndex;
1967 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
1968 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1969 mFastTrackAvailMask |= 1 << index;
1970 // redundant as track is about to be destroyed, for dumpsys only
1971 track->mFastIndex = -1;
1972 }
1973 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1974 if (chain != 0) {
1975 chain->decTrackCnt();
1976 }
1977}
1978
Eric Laurentede6c3b2013-09-19 14:37:46 -07001979void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001980{
1981 // Thread could be blocked waiting for async
1982 // so signal it to handle state changes immediately
1983 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1984 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1985 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001986 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001987}
1988
Eric Laurent81784c32012-11-19 14:55:58 -08001989String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1990{
Eric Laurent81784c32012-11-19 14:55:58 -08001991 Mutex::Autolock _l(mLock);
1992 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07001993 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08001994 }
1995
Glenn Kastend8ea6992013-07-16 14:17:15 -07001996 char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
1997 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08001998 free(s);
1999 return out_s8;
2000}
2001
Eric Laurent73e26b62015-04-27 16:55:58 -07002002void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event) {
2003 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2004 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002005
Eric Laurent73e26b62015-04-27 16:55:58 -07002006 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002007
2008 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002009 case AUDIO_OUTPUT_OPENED:
2010 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002011 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002012 desc->mChannelMask = mChannelMask;
2013 desc->mSamplingRate = mSampleRate;
2014 desc->mFormat = mFormat;
2015 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002016 // AudioFlinger::frameCount(audio_io_handle_t)
Eric Laurent73e26b62015-04-27 16:55:58 -07002017 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002018 break;
2019
Eric Laurent73e26b62015-04-27 16:55:58 -07002020 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002021 default:
2022 break;
2023 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002024 mAudioFlinger->ioConfigChanged(event, desc);
Eric Laurent81784c32012-11-19 14:55:58 -08002025}
2026
Eric Laurentbfb1b832013-01-07 09:53:42 -08002027void AudioFlinger::PlaybackThread::writeCallback()
2028{
2029 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002030 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002031}
2032
2033void AudioFlinger::PlaybackThread::drainCallback()
2034{
2035 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002036 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002037}
2038
Eric Laurent3b4529e2013-09-05 18:09:19 -07002039void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002040{
2041 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002042 // reject out of sequence requests
2043 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2044 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002045 mWaitWorkCV.signal();
2046 }
2047}
2048
Eric Laurent3b4529e2013-09-05 18:09:19 -07002049void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002050{
2051 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002052 // reject out of sequence requests
2053 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
2054 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002055 mWaitWorkCV.signal();
2056 }
2057}
2058
2059// static
2060int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
Glenn Kasten0f11b512014-01-31 16:18:54 -08002061 void *param __unused,
Eric Laurentbfb1b832013-01-07 09:53:42 -08002062 void *cookie)
2063{
2064 AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
2065 ALOGV("asyncCallback() event %d", event);
2066 switch (event) {
2067 case STREAM_CBK_EVENT_WRITE_READY:
2068 me->writeCallback();
2069 break;
2070 case STREAM_CBK_EVENT_DRAIN_READY:
2071 me->drainCallback();
2072 break;
2073 default:
2074 ALOGW("asyncCallback() unknown event %d", event);
2075 break;
2076 }
2077 return 0;
2078}
2079
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002080void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002081{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002082 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Eric Laurent81784c32012-11-19 14:55:58 -08002083 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
2084 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002085 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002086 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002087 }
Andy Hung9a592762014-07-21 21:56:01 -07002088 if ((mType == MIXER || mType == DUPLICATING)
2089 && !isValidPcmSinkChannelMask(mChannelMask)) {
2090 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2091 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002092 }
Andy Hunge5412692014-05-16 11:25:07 -07002093 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Andy Hung463be252014-07-10 16:56:07 -07002094 mHALFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
2095 mFormat = mHALFormat;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002096 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002097 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002098 }
Andy Hung6146c082014-03-18 11:56:15 -07002099 if ((mType == MIXER || mType == DUPLICATING)
2100 && !isValidPcmSinkFormat(mFormat)) {
2101 LOG_FATAL("HAL format %#x not supported for mixed output",
2102 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002103 }
Phil Burk062e67a2015-02-11 13:40:50 -08002104 mFrameSize = mOutput->getFrameSize();
Glenn Kasten70949c42013-08-06 07:40:12 -07002105 mBufferSize = mOutput->stream->common.get_buffer_size(&mOutput->stream->common);
2106 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002107 if (mFrameCount & 15) {
2108 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
2109 mFrameCount);
2110 }
2111
Eric Laurentbfb1b832013-01-07 09:53:42 -08002112 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
2113 (mOutput->stream->set_callback != NULL)) {
2114 if (mOutput->stream->set_callback(mOutput->stream,
2115 AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
2116 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002117 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002118 }
2119 }
2120
Eric Laurentd1f69b02014-12-15 14:33:13 -08002121 mHwSupportsPause = false;
2122 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
2123 if (mOutput->stream->pause != NULL) {
2124 if (mOutput->stream->resume != NULL) {
2125 mHwSupportsPause = true;
2126 } else {
2127 ALOGW("direct output implements pause but not resume");
2128 }
2129 } else if (mOutput->stream->resume != NULL) {
2130 ALOGW("direct output implements resume but not pause");
2131 }
2132 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002133 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2134 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2135 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002136
Andy Hungfbfc3952015-01-15 13:33:51 -08002137 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2138 // For best precision, we use float instead of the associated output
2139 // device format (typically PCM 16 bit).
2140
2141 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2142 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2143 mBufferSize = mFrameSize * mFrameCount;
2144
2145 // TODO: We currently use the associated output device channel mask and sample rate.
2146 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2147 // (if a valid mask) to avoid premature downmix.
2148 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2149 // instead of the output device sample rate to avoid loss of high frequency information.
2150 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2151 }
2152
Andy Hung09a50072014-02-27 14:30:47 -08002153 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002154 double multiplier = 1.0;
2155 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2156 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002157 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2158 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Eric Laurent81784c32012-11-19 14:55:58 -08002159 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2160 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2161 maxNormalFrameCount = maxNormalFrameCount & ~15;
2162 if (maxNormalFrameCount < minNormalFrameCount) {
2163 maxNormalFrameCount = minNormalFrameCount;
2164 }
2165 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2166 if (multiplier <= 1.0) {
2167 multiplier = 1.0;
2168 } else if (multiplier <= 2.0) {
2169 if (2 * mFrameCount <= maxNormalFrameCount) {
2170 multiplier = 2.0;
2171 } else {
2172 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2173 }
2174 } else {
2175 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
Andy Hung09a50072014-02-27 14:30:47 -08002176 // 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 -08002177 // track, but we sometimes have to do this to satisfy the maximum frame count
2178 // constraint)
2179 // FIXME this rounding up should not be done if no HAL SRC
2180 uint32_t truncMult = (uint32_t) multiplier;
2181 if ((truncMult & 1)) {
2182 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
2183 ++truncMult;
2184 }
2185 }
2186 multiplier = (double) truncMult;
2187 }
2188 }
2189 mNormalFrameCount = multiplier * mFrameCount;
2190 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002191 if (mType == MIXER || mType == DUPLICATING) {
2192 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2193 }
Andy Hung09a50072014-02-27 14:30:47 -08002194 ALOGI("HAL output buffer size %u frames, normal sink buffer size %u frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002195 mNormalFrameCount);
2196
Andy Hung08fb1742015-05-31 23:22:10 -07002197 // Check if we want to throttle the processing to no more than 2x normal rate
2198 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002199 mThreadThrottleTimeMs = 0;
2200 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002201 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2202
Andy Hung010a1a12014-03-13 13:57:33 -07002203 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2204 // Originally this was int16_t[] array, need to remove legacy implications.
2205 free(mSinkBuffer);
2206 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002207 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2208 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2209 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002210 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002211
Andy Hung69aed5f2014-02-25 17:24:40 -08002212 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2213 // drives the output.
2214 free(mMixerBuffer);
2215 mMixerBuffer = NULL;
2216 if (mMixerBufferEnabled) {
2217 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2218 mMixerBufferSize = mNormalFrameCount * mChannelCount
2219 * audio_bytes_per_sample(mMixerBufferFormat);
2220 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2221 }
Andy Hung98ef9782014-03-04 14:46:50 -08002222 free(mEffectBuffer);
2223 mEffectBuffer = NULL;
2224 if (mEffectBufferEnabled) {
2225 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
2226 mEffectBufferSize = mNormalFrameCount * mChannelCount
2227 * audio_bytes_per_sample(mEffectBufferFormat);
2228 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2229 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002230
Eric Laurent81784c32012-11-19 14:55:58 -08002231 // force reconfiguration of effect chains and engines to take new buffer size and audio
2232 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002233 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002234 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2235 // matter.
2236 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2237 Vector< sp<EffectChain> > effectChains = mEffectChains;
2238 for (size_t i = 0; i < effectChains.size(); i ++) {
2239 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2240 }
2241}
2242
2243
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002244status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002245{
2246 if (halFrames == NULL || dspFrames == NULL) {
2247 return BAD_VALUE;
2248 }
2249 Mutex::Autolock _l(mLock);
2250 if (initCheck() != NO_ERROR) {
2251 return INVALID_OPERATION;
2252 }
2253 size_t framesWritten = mBytesWritten / mFrameSize;
2254 *halFrames = framesWritten;
2255
2256 if (isSuspended()) {
2257 // return an estimation of rendered frames when the output is suspended
2258 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
2259 *dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0;
2260 return NO_ERROR;
2261 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002262 status_t status;
2263 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002264 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002265 *dspFrames = (size_t)frames;
2266 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002267 }
2268}
2269
2270uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
2271{
2272 Mutex::Autolock _l(mLock);
2273 uint32_t result = 0;
2274 if (getEffectChain_l(sessionId) != 0) {
2275 result = EFFECT_SESSION;
2276 }
2277
2278 for (size_t i = 0; i < mTracks.size(); ++i) {
2279 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002280 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002281 result |= TRACK_SESSION;
2282 break;
2283 }
2284 }
2285
2286 return result;
2287}
2288
2289uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
2290{
2291 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2292 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2293 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2294 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2295 }
2296 for (size_t i = 0; i < mTracks.size(); i++) {
2297 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002298 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002299 return AudioSystem::getStrategyForStream(track->streamType());
2300 }
2301 }
2302 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2303}
2304
2305
Phil Burk062e67a2015-02-11 13:40:50 -08002306AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002307{
2308 Mutex::Autolock _l(mLock);
2309 return mOutput;
2310}
2311
Phil Burk062e67a2015-02-11 13:40:50 -08002312AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002313{
2314 Mutex::Autolock _l(mLock);
2315 AudioStreamOut *output = mOutput;
2316 mOutput = NULL;
2317 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2318 // must push a NULL and wait for ack
2319 mOutputSink.clear();
2320 mPipeSink.clear();
2321 mNormalSink.clear();
2322 return output;
2323}
2324
2325// this method must always be called either with ThreadBase mLock held or inside the thread loop
2326audio_stream_t* AudioFlinger::PlaybackThread::stream() const
2327{
2328 if (mOutput == NULL) {
2329 return NULL;
2330 }
2331 return &mOutput->stream->common;
2332}
2333
2334uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2335{
2336 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2337}
2338
2339status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2340{
2341 if (!isValidSyncEvent(event)) {
2342 return BAD_VALUE;
2343 }
2344
2345 Mutex::Autolock _l(mLock);
2346
2347 for (size_t i = 0; i < mTracks.size(); ++i) {
2348 sp<Track> track = mTracks[i];
2349 if (event->triggerSession() == track->sessionId()) {
2350 (void) track->setSyncEvent(event);
2351 return NO_ERROR;
2352 }
2353 }
2354
2355 return NAME_NOT_FOUND;
2356}
2357
2358bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2359{
2360 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2361}
2362
2363void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2364 const Vector< sp<Track> >& tracksToRemove)
2365{
2366 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002367 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002368 for (size_t i = 0 ; i < count ; i++) {
2369 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002370 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002371 AudioSystem::stopOutput(mId, track->streamType(),
2372 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002373#ifdef ADD_BATTERY_DATA
2374 // to track the speaker usage
2375 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2376#endif
2377 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002378 AudioSystem::releaseOutput(mId, track->streamType(),
2379 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002380 }
Eric Laurent81784c32012-11-19 14:55:58 -08002381 }
2382 }
2383 }
Eric Laurent81784c32012-11-19 14:55:58 -08002384}
2385
2386void AudioFlinger::PlaybackThread::checkSilentMode_l()
2387{
2388 if (!mMasterMute) {
2389 char value[PROPERTY_VALUE_MAX];
2390 if (property_get("ro.audio.silent", value, "0") > 0) {
2391 char *endptr;
2392 unsigned long ul = strtoul(value, &endptr, 0);
2393 if (*endptr == '\0' && ul != 0) {
2394 ALOGD("Silence is golden");
2395 // The setprop command will not allow a property to be changed after
2396 // the first time it is set, so we don't have to worry about un-muting.
2397 setMasterMute_l(true);
2398 }
2399 }
2400 }
2401}
2402
2403// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002404ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002405{
2406 // FIXME rewrite to reduce number of system calls
2407 mLastWriteTime = systemTime();
2408 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002409 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002410 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002411
2412 // If an NBAIO sink is present, use it to write the normal mixer's submix
2413 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002414
Andy Hung010a1a12014-03-13 13:57:33 -07002415 const size_t count = mBytesRemaining / mFrameSize;
2416
Simon Wilson2d590962012-11-29 15:18:50 -08002417 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002418 // update the setpoint when AudioFlinger::mScreenState changes
2419 uint32_t screenState = AudioFlinger::mScreenState;
2420 if (screenState != mScreenState) {
2421 mScreenState = screenState;
2422 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2423 if (pipe != NULL) {
2424 pipe->setAvgFrames((mScreenState & 1) ?
2425 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2426 }
2427 }
Andy Hung010a1a12014-03-13 13:57:33 -07002428 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002429 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002430 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002431 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002432 } else {
2433 bytesWritten = framesWritten;
2434 }
Glenn Kastenefaa7ab2014-08-20 08:48:54 -07002435 mLatchDValid = false;
Glenn Kasten767094d2013-08-23 13:51:43 -07002436 status_t status = mNormalSink->getTimestamp(mLatchD.mTimestamp);
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002437 if (status == NO_ERROR) {
2438 size_t totalFramesWritten = mNormalSink->framesWritten();
2439 if (totalFramesWritten >= mLatchD.mTimestamp.mPosition) {
2440 mLatchD.mUnpresentedFrames = totalFramesWritten - mLatchD.mTimestamp.mPosition;
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002441 // mLatchD.mFramesReleased is set immediately before D is clocked into Q
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002442 mLatchDValid = true;
2443 }
2444 }
Eric Laurent81784c32012-11-19 14:55:58 -08002445 // otherwise use the HAL / AudioStreamOut directly
2446 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002447 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002448
Eric Laurentbfb1b832013-01-07 09:53:42 -08002449 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002450 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2451 mWriteAckSequence += 2;
2452 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002453 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002454 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002455 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002456 // FIXME We should have an implementation of timestamps for direct output threads.
2457 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002458 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002459 if (mUseAsyncWrite &&
2460 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2461 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002462 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002463 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002464 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002465 }
Eric Laurent81784c32012-11-19 14:55:58 -08002466 }
2467
Eric Laurent81784c32012-11-19 14:55:58 -08002468 mNumWrites++;
2469 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002470 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002471 return bytesWritten;
2472}
2473
2474void AudioFlinger::PlaybackThread::threadLoop_drain()
2475{
2476 if (mOutput->stream->drain) {
2477 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2478 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002479 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2480 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002481 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002482 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002483 }
2484 mOutput->stream->drain(mOutput->stream,
2485 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
2486 : AUDIO_DRAIN_ALL);
2487 }
2488}
2489
2490void AudioFlinger::PlaybackThread::threadLoop_exit()
2491{
Eric Laurent275e8e92014-11-30 15:14:47 -08002492 {
2493 Mutex::Autolock _l(mLock);
2494 for (size_t i = 0; i < mTracks.size(); i++) {
2495 sp<Track> track = mTracks[i];
2496 track->invalidate();
2497 }
2498 }
Eric Laurent81784c32012-11-19 14:55:58 -08002499}
2500
2501/*
2502The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002503 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002504 - mActiveSleepTimeUs from activeSleepTimeUs()
2505 - mIdleSleepTimeUs from idleSleepTimeUs()
2506 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only)
Eric Laurent81784c32012-11-19 14:55:58 -08002507 - maxPeriod from frame count and sample rate (MIXER only)
2508
2509The parameters that affect these derived values are:
2510 - frame count
2511 - frame size
2512 - sample rate
2513 - device type: A2DP or not
2514 - device latency
2515 - format: PCM or not
2516 - active sleep time
2517 - idle sleep time
2518*/
2519
2520void AudioFlinger::PlaybackThread::cacheParameters_l()
2521{
Andy Hung25c2dac2014-02-27 14:56:00 -08002522 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002523 mActiveSleepTimeUs = activeSleepTimeUs();
2524 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent81784c32012-11-19 14:55:58 -08002525}
2526
2527void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2528{
Glenn Kasten7c027242012-12-26 14:43:16 -08002529 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurent81784c32012-11-19 14:55:58 -08002530 this, streamType, mTracks.size());
2531 Mutex::Autolock _l(mLock);
2532
2533 size_t size = mTracks.size();
2534 for (size_t i = 0; i < size; i++) {
2535 sp<Track> t = mTracks[i];
2536 if (t->streamType() == streamType) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002537 t->invalidate();
Eric Laurent81784c32012-11-19 14:55:58 -08002538 }
2539 }
2540}
2541
2542status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2543{
2544 int session = chain->sessionId();
Andy Hung010a1a12014-03-13 13:57:33 -07002545 int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled
2546 ? mEffectBuffer : mSinkBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002547 bool ownsBuffer = false;
2548
2549 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
2550 if (session > 0) {
2551 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002552 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002553 if (mType != DIRECT) {
2554 size_t numSamples = mNormalFrameCount * mChannelCount;
2555 buffer = new int16_t[numSamples];
2556 memset(buffer, 0, numSamples * sizeof(int16_t));
2557 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2558 ownsBuffer = true;
2559 }
2560
2561 // Attach all tracks with same session ID to this chain.
2562 for (size_t i = 0; i < mTracks.size(); ++i) {
2563 sp<Track> track = mTracks[i];
2564 if (session == track->sessionId()) {
2565 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2566 buffer);
2567 track->setMainBuffer(buffer);
2568 chain->incTrackCnt();
2569 }
2570 }
2571
2572 // indicate all active tracks in the chain
2573 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2574 sp<Track> track = mActiveTracks[i].promote();
2575 if (track == 0) {
2576 continue;
2577 }
2578 if (session == track->sessionId()) {
2579 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2580 chain->incActiveTrackCnt();
2581 }
2582 }
2583 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002584 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08002585 chain->setInBuffer(buffer, ownsBuffer);
Andy Hung010a1a12014-03-13 13:57:33 -07002586 chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled
2587 ? mEffectBuffer : mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002588 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
2589 // chains list in order to be processed last as it contains output stage effects
2590 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2591 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
2592 // after track specific effects and before output stage
2593 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
2594 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
2595 // Effect chain for other sessions are inserted at beginning of effect
2596 // chains list to be processed before output mix effects. Relative order between other
2597 // sessions is not important
2598 size_t size = mEffectChains.size();
2599 size_t i = 0;
2600 for (i = 0; i < size; i++) {
2601 if (mEffectChains[i]->sessionId() < session) {
2602 break;
2603 }
2604 }
2605 mEffectChains.insertAt(chain, i);
2606 checkSuspendOnAddEffectChain_l(chain);
2607
2608 return NO_ERROR;
2609}
2610
2611size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2612{
2613 int session = chain->sessionId();
2614
2615 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2616
2617 for (size_t i = 0; i < mEffectChains.size(); i++) {
2618 if (chain == mEffectChains[i]) {
2619 mEffectChains.removeAt(i);
2620 // detach all active tracks from the chain
2621 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2622 sp<Track> track = mActiveTracks[i].promote();
2623 if (track == 0) {
2624 continue;
2625 }
2626 if (session == track->sessionId()) {
2627 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2628 chain.get(), session);
2629 chain->decActiveTrackCnt();
2630 }
2631 }
2632
2633 // detach all tracks with same session ID from this chain
2634 for (size_t i = 0; i < mTracks.size(); ++i) {
2635 sp<Track> track = mTracks[i];
2636 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002637 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002638 chain->decTrackCnt();
2639 }
2640 }
2641 break;
2642 }
2643 }
2644 return mEffectChains.size();
2645}
2646
2647status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2648 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2649{
2650 Mutex::Autolock _l(mLock);
2651 return attachAuxEffect_l(track, EffectId);
2652}
2653
2654status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2655 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2656{
2657 status_t status = NO_ERROR;
2658
2659 if (EffectId == 0) {
2660 track->setAuxBuffer(0, NULL);
2661 } else {
2662 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2663 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2664 if (effect != 0) {
2665 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2666 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2667 } else {
2668 status = INVALID_OPERATION;
2669 }
2670 } else {
2671 status = BAD_VALUE;
2672 }
2673 }
2674 return status;
2675}
2676
2677void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2678{
2679 for (size_t i = 0; i < mTracks.size(); ++i) {
2680 sp<Track> track = mTracks[i];
2681 if (track->auxEffectId() == effectId) {
2682 attachAuxEffect_l(track, 0);
2683 }
2684 }
2685}
2686
2687bool AudioFlinger::PlaybackThread::threadLoop()
2688{
2689 Vector< sp<Track> > tracksToRemove;
2690
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002691 mStandbyTimeNs = systemTime();
Eric Laurent81784c32012-11-19 14:55:58 -08002692
2693 // MIXER
2694 nsecs_t lastWarning = 0;
2695
2696 // DUPLICATING
2697 // FIXME could this be made local to while loop?
2698 writeFrames = 0;
2699
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002700 int lastGeneration = 0;
2701
Eric Laurent81784c32012-11-19 14:55:58 -08002702 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002703 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08002704
2705 if (mType == MIXER) {
2706 sleepTimeShift = 0;
2707 }
2708
2709 CpuStats cpuStats;
2710 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2711
2712 acquireWakeLock();
2713
Glenn Kasten9e58b552013-01-18 15:09:48 -08002714 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2715 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2716 // and then that string will be logged at the next convenient opportunity.
2717 const char *logString = NULL;
2718
Eric Laurent664539d2013-09-23 18:24:31 -07002719 checkSilentMode_l();
2720
Eric Laurent81784c32012-11-19 14:55:58 -08002721 while (!exitPending())
2722 {
2723 cpuStats.sample(myName);
2724
2725 Vector< sp<EffectChain> > effectChains;
2726
Eric Laurent81784c32012-11-19 14:55:58 -08002727 { // scope for mLock
2728
2729 Mutex::Autolock _l(mLock);
2730
Eric Laurent021cf962014-05-13 10:18:14 -07002731 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07002732
Glenn Kasten9e58b552013-01-18 15:09:48 -08002733 if (logString != NULL) {
2734 mNBLogWriter->logTimestamp();
2735 mNBLogWriter->log(logString);
2736 logString = NULL;
2737 }
2738
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002739 // Gather the framesReleased counters for all active tracks,
2740 // and latch them atomically with the timestamp.
2741 // FIXME We're using raw pointers as indices. A unique track ID would be a better index.
2742 mLatchD.mFramesReleased.clear();
2743 size_t size = mActiveTracks.size();
2744 for (size_t i = 0; i < size; i++) {
2745 sp<Track> t = mActiveTracks[i].promote();
2746 if (t != 0) {
2747 mLatchD.mFramesReleased.add(t.get(),
2748 t->mAudioTrackServerProxy->framesReleased());
2749 }
2750 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002751 if (mLatchDValid) {
2752 mLatchQ = mLatchD;
2753 mLatchDValid = false;
2754 mLatchQValid = true;
2755 }
2756
Eric Laurent81784c32012-11-19 14:55:58 -08002757 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002758 if (mSignalPending) {
2759 // A signal was raised while we were unlocked
2760 mSignalPending = false;
2761 } else if (waitingAsyncCallback_l()) {
2762 if (exitPending()) {
2763 break;
2764 }
Marco Nelissen078538c2015-05-12 09:17:57 -07002765 bool released = false;
2766 // The following works around a bug in the offload driver. Ideally we would release
2767 // the wake lock every time, but that causes the last offload buffer(s) to be
2768 // dropped while the device is on battery, so we need to hold a wake lock during
2769 // the drain phase.
2770 if (mBytesRemaining && !(mDrainSequence & 1)) {
2771 releaseWakeLock_l();
2772 released = true;
2773 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002774 mWakeLockUids.clear();
2775 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002776 ALOGV("wait async completion");
2777 mWaitWorkCV.wait(mLock);
2778 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07002779 if (released) {
2780 acquireWakeLock_l();
2781 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002782 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
2783 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002784
2785 continue;
2786 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002787 if ((!mActiveTracks.size() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08002788 isSuspended()) {
2789 // put audio hardware into standby after short delay
2790 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002791
2792 threadLoop_standby();
2793
2794 mStandby = true;
2795 }
2796
2797 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2798 // we're about to wait, flush the binder command buffer
2799 IPCThreadState::self()->flushCommands();
2800
2801 clearOutputTracks();
2802
2803 if (exitPending()) {
2804 break;
2805 }
2806
2807 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002808 mWakeLockUids.clear();
2809 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002810 // wait until we have something to do...
2811 ALOGV("%s going to sleep", myName.string());
2812 mWaitWorkCV.wait(mLock);
2813 ALOGV("%s waking up", myName.string());
2814 acquireWakeLock_l();
2815
2816 mMixerStatus = MIXER_IDLE;
2817 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2818 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002819 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002820 checkSilentMode_l();
2821
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002822 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
2823 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08002824 if (mType == MIXER) {
2825 sleepTimeShift = 0;
2826 }
2827
2828 continue;
2829 }
2830 }
Eric Laurent81784c32012-11-19 14:55:58 -08002831 // mMixerStatusIgnoringFastTracks is also updated internally
2832 mMixerStatus = prepareTracks_l(&tracksToRemove);
2833
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002834 // compare with previously applied list
2835 if (lastGeneration != mActiveTracksGeneration) {
2836 // update wakelock
2837 updateWakeLockUids_l(mWakeLockUids);
2838 lastGeneration = mActiveTracksGeneration;
2839 }
2840
Eric Laurent81784c32012-11-19 14:55:58 -08002841 // prevent any changes in effect chain list and in each effect chain
2842 // during mixing and effect process as the audio buffers could be deleted
2843 // or modified if an effect is created or deleted
2844 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002845 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08002846
Eric Laurentbfb1b832013-01-07 09:53:42 -08002847 if (mBytesRemaining == 0) {
2848 mCurrentWriteLength = 0;
2849 if (mMixerStatus == MIXER_TRACKS_READY) {
2850 // threadLoop_mix() sets mCurrentWriteLength
2851 threadLoop_mix();
2852 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
2853 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002854 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08002855 // must be written to HAL
2856 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002857 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08002858 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002859 }
2860 }
Andy Hung98ef9782014-03-04 14:46:50 -08002861 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002862 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08002863 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
2864 // or mSinkBuffer (if there are no effects).
2865 //
2866 // This is done pre-effects computation; if effects change to
2867 // support higher precision, this needs to move.
2868 //
2869 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002870 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08002871 if (mMixerBufferValid) {
2872 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
2873 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
2874
2875 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
2876 mNormalFrameCount * mChannelCount);
2877 }
2878
Eric Laurentbfb1b832013-01-07 09:53:42 -08002879 mBytesRemaining = mCurrentWriteLength;
2880 if (isSuspended()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002881 mSleepTimeUs = suspendSleepTimeUs();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002882 // simulate write to HAL when suspended
Andy Hung25c2dac2014-02-27 14:56:00 -08002883 mBytesWritten += mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002884 mBytesRemaining = 0;
2885 }
Eric Laurent81784c32012-11-19 14:55:58 -08002886
Eric Laurentbfb1b832013-01-07 09:53:42 -08002887 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002888 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002889 for (size_t i = 0; i < effectChains.size(); i ++) {
2890 effectChains[i]->process_l();
2891 }
Eric Laurent81784c32012-11-19 14:55:58 -08002892 }
2893 }
Eric Laurent59fe0102013-09-27 18:48:26 -07002894 // Process effect chains for offloaded thread even if no audio
2895 // was read from audio track: process only updates effect state
2896 // and thus does have to be synchronized with audio writes but may have
2897 // to be called while waiting for async write callback
2898 if (mType == OFFLOAD) {
2899 for (size_t i = 0; i < effectChains.size(); i ++) {
2900 effectChains[i]->process_l();
2901 }
2902 }
Eric Laurent81784c32012-11-19 14:55:58 -08002903
Andy Hung98ef9782014-03-04 14:46:50 -08002904 // Only if the Effects buffer is enabled and there is data in the
2905 // Effects buffer (buffer valid), we need to
2906 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002907 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08002908 if (mEffectBufferValid) {
2909 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
2910 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
2911 mNormalFrameCount * mChannelCount);
2912 }
2913
Eric Laurent81784c32012-11-19 14:55:58 -08002914 // enable changes in effect chain
2915 unlockEffectChains(effectChains);
2916
Eric Laurentbfb1b832013-01-07 09:53:42 -08002917 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002918 // mSleepTimeUs == 0 means we must write to audio hardware
2919 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07002920 ssize_t ret = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002921 if (mBytesRemaining) {
Andy Hung08fb1742015-05-31 23:22:10 -07002922 ret = threadLoop_write();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002923 if (ret < 0) {
2924 mBytesRemaining = 0;
2925 } else {
2926 mBytesWritten += ret;
2927 mBytesRemaining -= ret;
2928 }
2929 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
2930 (mMixerStatus == MIXER_DRAIN_ALL)) {
2931 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08002932 }
Andy Hung08fb1742015-05-31 23:22:10 -07002933 if (mType == MIXER && !mStandby) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07002934 // write blocked detection
2935 nsecs_t now = systemTime();
2936 nsecs_t delta = now - mLastWriteTime;
Andy Hung08fb1742015-05-31 23:22:10 -07002937 if (delta > maxPeriod) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07002938 mNumDelayedWrites++;
2939 if ((now - lastWarning) > kWarningThrottleNs) {
2940 ATRACE_NAME("underrun");
2941 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2942 ns2ms(delta), mNumDelayedWrites, this);
2943 lastWarning = now;
2944 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002945 }
Andy Hung08fb1742015-05-31 23:22:10 -07002946
2947 if (mThreadThrottle
2948 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
2949 && ret > 0) { // we wrote something
2950 // Limit MixerThread data processing to no more than twice the
2951 // expected processing rate.
2952 //
2953 // This helps prevent underruns with NuPlayer and other applications
2954 // which may set up buffers that are close to the minimum size, or use
2955 // deep buffers, and rely on a double-buffering sleep strategy to fill.
2956 //
2957 // The throttle smooths out sudden large data drains from the device,
2958 // e.g. when it comes out of standby, which often causes problems with
2959 // (1) mixer threads without a fast mixer (which has its own warm-up)
2960 // (2) minimum buffer sized tracks (even if the track is full,
2961 // the app won't fill fast enough to handle the sudden draw).
2962
2963 const int32_t deltaMs = delta / 1000000;
2964 const int32_t throttleMs = mHalfBufferMs - deltaMs;
2965 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
2966 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07002967 // notify of throttle start on verbose log
2968 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
2969 "mixer(%p) throttle begin:"
2970 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07002971 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07002972 mThreadThrottleTimeMs += throttleMs;
2973 } else {
2974 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
2975 if (diff > 0) {
2976 // notify of throttle end on debug log
2977 ALOGD("mixer(%p) throttle end: throttle time(%u)", this, diff);
2978 mThreadThrottleEndMs = mThreadThrottleTimeMs;
2979 }
Andy Hung08fb1742015-05-31 23:22:10 -07002980 }
2981 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002982 }
Eric Laurent81784c32012-11-19 14:55:58 -08002983
Eric Laurentbfb1b832013-01-07 09:53:42 -08002984 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07002985 ATRACE_BEGIN("sleep");
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002986 usleep(mSleepTimeUs);
Glenn Kastene7754022014-10-31 12:11:26 -07002987 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002988 }
Eric Laurent81784c32012-11-19 14:55:58 -08002989 }
2990
2991 // Finally let go of removed track(s), without the lock held
2992 // since we can't guarantee the destructors won't acquire that
2993 // same lock. This will also mutate and push a new fast mixer state.
2994 threadLoop_removeTracks(tracksToRemove);
2995 tracksToRemove.clear();
2996
2997 // FIXME I don't understand the need for this here;
2998 // it was in the original code but maybe the
2999 // assignment in saveOutputTracks() makes this unnecessary?
3000 clearOutputTracks();
3001
3002 // Effect chains will be actually deleted here if they were removed from
3003 // mEffectChains list during mixing or effects processing
3004 effectChains.clear();
3005
3006 // FIXME Note that the above .clear() is no longer necessary since effectChains
3007 // is now local to this block, but will keep it for now (at least until merge done).
3008 }
3009
Eric Laurentbfb1b832013-01-07 09:53:42 -08003010 threadLoop_exit();
3011
Eric Laurentcf817a22014-08-04 20:36:31 -07003012 if (!mStandby) {
3013 threadLoop_standby();
3014 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003015 }
3016
3017 releaseWakeLock();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003018 mWakeLockUids.clear();
3019 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08003020
3021 ALOGV("Thread %p type %d exiting", this, mType);
3022 return false;
3023}
3024
Eric Laurentbfb1b832013-01-07 09:53:42 -08003025// removeTracks_l() must be called with ThreadBase::mLock held
3026void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3027{
3028 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07003029 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003030 for (size_t i=0 ; i<count ; i++) {
3031 const sp<Track>& track = tracksToRemove.itemAt(i);
3032 mActiveTracks.remove(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003033 mWakeLockUids.remove(track->uid());
3034 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003035 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
3036 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3037 if (chain != 0) {
3038 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
3039 track->sessionId());
3040 chain->decActiveTrackCnt();
3041 }
3042 if (track->isTerminated()) {
3043 removeTrack_l(track);
3044 }
3045 }
3046 }
3047
3048}
Eric Laurent81784c32012-11-19 14:55:58 -08003049
Eric Laurentaccc1472013-09-20 09:36:34 -07003050status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3051{
3052 if (mNormalSink != 0) {
3053 return mNormalSink->getTimestamp(timestamp);
3054 }
Andy Hung9a1c8892014-12-03 11:37:42 -08003055 if ((mType == OFFLOAD || mType == DIRECT)
3056 && mOutput != NULL && mOutput->stream->get_presentation_position) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003057 uint64_t position64;
Phil Burk062e67a2015-02-11 13:40:50 -08003058 int ret = mOutput->getPresentationPosition(&position64, &timestamp.mTime);
Eric Laurentaccc1472013-09-20 09:36:34 -07003059 if (ret == 0) {
3060 timestamp.mPosition = (uint32_t)position64;
3061 return NO_ERROR;
3062 }
3063 }
3064 return INVALID_OPERATION;
3065}
Eric Laurent1c333e22014-05-20 10:48:17 -07003066
Eric Laurent054d9d32015-04-24 08:48:48 -07003067status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
3068 audio_patch_handle_t *handle)
3069{
3070 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3071 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3072 if (mFastMixer != 0) {
3073 FastMixerStateQueue *sq = mFastMixer->sq();
3074 FastMixerState *state = sq->begin();
3075 if (!(state->mCommand & FastMixerState::IDLE)) {
3076 previousCommand = state->mCommand;
3077 state->mCommand = FastMixerState::HOT_IDLE;
3078 sq->end();
3079 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3080 } else {
3081 sq->end(false /*didModify*/);
3082 }
3083 }
3084 status_t status = PlaybackThread::createAudioPatch_l(patch, handle);
3085
3086 if (!(previousCommand & FastMixerState::IDLE)) {
3087 ALOG_ASSERT(mFastMixer != 0);
3088 FastMixerStateQueue *sq = mFastMixer->sq();
3089 FastMixerState *state = sq->begin();
3090 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3091 state->mCommand = previousCommand;
3092 sq->end();
3093 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3094 }
3095
3096 return status;
3097}
3098
Eric Laurent1c333e22014-05-20 10:48:17 -07003099status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3100 audio_patch_handle_t *handle)
3101{
3102 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003103
3104 // store new device and send to effects
3105 audio_devices_t type = AUDIO_DEVICE_NONE;
3106 for (unsigned int i = 0; i < patch->num_sinks; i++) {
3107 type |= patch->sinks[i].ext.device.type;
3108 }
3109
3110#ifdef ADD_BATTERY_DATA
3111 // when changing the audio output device, call addBatteryData to notify
3112 // the change
3113 if (mOutDevice != type) {
3114 uint32_t params = 0;
3115 // check whether speaker is on
3116 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3117 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003118 }
3119
Eric Laurent054d9d32015-04-24 08:48:48 -07003120 audio_devices_t deviceWithoutSpeaker
3121 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3122 // check if any other device (except speaker) is on
3123 if (type & deviceWithoutSpeaker) {
3124 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3125 }
3126
3127 if (params != 0) {
3128 addBatteryData(params);
3129 }
3130 }
3131#endif
3132
3133 for (size_t i = 0; i < mEffectChains.size(); i++) {
3134 mEffectChains[i]->setDevice_l(type);
3135 }
Eric Laurente8726fe2015-06-26 09:39:24 -07003136 bool configChanged = mOutDevice != type;
Eric Laurent054d9d32015-04-24 08:48:48 -07003137 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003138 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003139
3140 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003141 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
3142 status = hwDevice->create_audio_patch(hwDevice,
3143 patch->num_sources,
3144 patch->sources,
3145 patch->num_sinks,
3146 patch->sinks,
3147 handle);
3148 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003149 char *address;
3150 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3151 //FIXME: we only support address on first sink with HAL version < 3.0
3152 address = audio_device_address_to_parameter(
3153 patch->sinks[0].ext.device.type,
3154 patch->sinks[0].ext.device.address);
3155 } else {
3156 address = (char *)calloc(1, 1);
3157 }
3158 AudioParameter param = AudioParameter(String8(address));
3159 free(address);
3160 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), (int)type);
3161 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3162 param.toString().string());
3163 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003164 }
Eric Laurente8726fe2015-06-26 09:39:24 -07003165 if (configChanged) {
3166 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
3167 }
Eric Laurent1c333e22014-05-20 10:48:17 -07003168 return status;
3169}
3170
Eric Laurent054d9d32015-04-24 08:48:48 -07003171status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3172{
3173 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3174 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3175 if (mFastMixer != 0) {
3176 FastMixerStateQueue *sq = mFastMixer->sq();
3177 FastMixerState *state = sq->begin();
3178 if (!(state->mCommand & FastMixerState::IDLE)) {
3179 previousCommand = state->mCommand;
3180 state->mCommand = FastMixerState::HOT_IDLE;
3181 sq->end();
3182 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3183 } else {
3184 sq->end(false /*didModify*/);
3185 }
3186 }
3187
3188 status_t status = PlaybackThread::releaseAudioPatch_l(handle);
3189
3190 if (!(previousCommand & FastMixerState::IDLE)) {
3191 ALOG_ASSERT(mFastMixer != 0);
3192 FastMixerStateQueue *sq = mFastMixer->sq();
3193 FastMixerState *state = sq->begin();
3194 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3195 state->mCommand = previousCommand;
3196 sq->end();
3197 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3198 }
3199
3200 return status;
3201}
3202
Eric Laurent1c333e22014-05-20 10:48:17 -07003203status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3204{
3205 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003206
3207 mOutDevice = AUDIO_DEVICE_NONE;
3208
Eric Laurent1c333e22014-05-20 10:48:17 -07003209 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
3210 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
3211 status = hwDevice->release_audio_patch(hwDevice, handle);
3212 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003213 AudioParameter param;
3214 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
3215 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3216 param.toString().string());
Eric Laurent1c333e22014-05-20 10:48:17 -07003217 }
3218 return status;
3219}
3220
Eric Laurent83b88082014-06-20 18:31:16 -07003221void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3222{
3223 Mutex::Autolock _l(mLock);
3224 mTracks.add(track);
3225}
3226
3227void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3228{
3229 Mutex::Autolock _l(mLock);
3230 destroyTrack_l(track);
3231}
3232
3233void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
3234{
3235 ThreadBase::getAudioPortConfig(config);
3236 config->role = AUDIO_PORT_ROLE_SOURCE;
3237 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3238 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
3239}
3240
Eric Laurent81784c32012-11-19 14:55:58 -08003241// ----------------------------------------------------------------------------
3242
3243AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurent72e3f392015-05-20 14:43:50 -07003244 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
3245 : PlaybackThread(audioFlinger, output, id, device, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08003246 // mAudioMixer below
3247 // mFastMixer below
3248 mFastMixerFutex(0)
3249 // mOutputSink below
3250 // mPipeSink below
3251 // mNormalSink below
3252{
3253 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07003254 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, "
Eric Laurent81784c32012-11-19 14:55:58 -08003255 "mFrameCount=%d, mNormalFrameCount=%d",
3256 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3257 mNormalFrameCount);
3258 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3259
Andy Hungfbfc3952015-01-15 13:33:51 -08003260 if (type == DUPLICATING) {
3261 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3262 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3263 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3264 return;
3265 }
Eric Laurent81784c32012-11-19 14:55:58 -08003266 // create an NBAIO sink for the HAL output stream, and negotiate
3267 mOutputSink = new AudioStreamOutSink(output->stream);
3268 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003269 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Eric Laurent81784c32012-11-19 14:55:58 -08003270 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
3271 ALOG_ASSERT(index == 0);
3272
3273 // initialize fast mixer depending on configuration
3274 bool initFastMixer;
3275 switch (kUseFastMixer) {
3276 case FastMixer_Never:
3277 initFastMixer = false;
3278 break;
3279 case FastMixer_Always:
3280 initFastMixer = true;
3281 break;
3282 case FastMixer_Static:
3283 case FastMixer_Dynamic:
3284 initFastMixer = mFrameCount < mNormalFrameCount;
3285 break;
3286 }
3287 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003288 audio_format_t fastMixerFormat;
3289 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3290 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3291 } else {
3292 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3293 }
3294 if (mFormat != fastMixerFormat) {
3295 // change our Sink format to accept our intermediate precision
3296 mFormat = fastMixerFormat;
3297 free(mSinkBuffer);
3298 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3299 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3300 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3301 }
Eric Laurent81784c32012-11-19 14:55:58 -08003302
3303 // create a MonoPipe to connect our submix to FastMixer
3304 NBAIO_Format format = mOutputSink->format();
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003305 NBAIO_Format origformat = format;
Andy Hung1258c1a2014-05-23 21:22:17 -07003306 // adjust format to match that of the Fast Mixer
Glenn Kasten97b7b752014-09-28 13:04:24 -07003307 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003308 format.mFormat = fastMixerFormat;
3309 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3310
Eric Laurent81784c32012-11-19 14:55:58 -08003311 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3312 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3313 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3314 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3315 const NBAIO_Format offers[1] = {format};
3316 size_t numCounterOffers = 0;
3317 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
3318 ALOG_ASSERT(index == 0);
3319 monoPipe->setAvgFrames((mScreenState & 1) ?
3320 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3321 mPipeSink = monoPipe;
3322
Glenn Kasten46909e72013-02-26 09:20:22 -08003323#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08003324 if (mTeeSinkOutputEnabled) {
3325 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003326 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
3327 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08003328 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003329 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003330 ALOG_ASSERT(index == 0);
3331 mTeeSink = teeSink;
3332 PipeReader *teeSource = new PipeReader(*teeSink);
3333 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003334 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003335 ALOG_ASSERT(index == 0);
3336 mTeeSource = teeSource;
3337 }
Glenn Kasten46909e72013-02-26 09:20:22 -08003338#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003339
3340 // create fast mixer and configure it initially with just one fast track for our submix
3341 mFastMixer = new FastMixer();
3342 FastMixerStateQueue *sq = mFastMixer->sq();
3343#ifdef STATE_QUEUE_DUMP
3344 sq->setObserverDump(&mStateQueueObserverDump);
3345 sq->setMutatorDump(&mStateQueueMutatorDump);
3346#endif
3347 FastMixerState *state = sq->begin();
3348 FastTrack *fastTrack = &state->mFastTracks[0];
3349 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3350 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3351 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003352 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3353 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003354 fastTrack->mGeneration++;
3355 state->mFastTracksGen++;
3356 state->mTrackMask = 1;
3357 // fast mixer will use the HAL output sink
3358 state->mOutputSink = mOutputSink.get();
3359 state->mOutputSinkGen++;
3360 state->mFrameCount = mFrameCount;
3361 state->mCommand = FastMixerState::COLD_IDLE;
3362 // already done in constructor initialization list
3363 //mFastMixerFutex = 0;
3364 state->mColdFutexAddr = &mFastMixerFutex;
3365 state->mColdGen++;
3366 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08003367#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003368 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08003369#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08003370 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3371 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003372 sq->end();
3373 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3374
3375 // start the fast mixer
3376 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3377 pid_t tid = mFastMixer->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003378 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003379
3380#ifdef AUDIO_WATCHDOG
3381 // create and start the watchdog
3382 mAudioWatchdog = new AudioWatchdog();
3383 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3384 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3385 tid = mAudioWatchdog->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003386 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003387#endif
3388
Eric Laurent81784c32012-11-19 14:55:58 -08003389 }
3390
3391 switch (kUseFastMixer) {
3392 case FastMixer_Never:
3393 case FastMixer_Dynamic:
3394 mNormalSink = mOutputSink;
3395 break;
3396 case FastMixer_Always:
3397 mNormalSink = mPipeSink;
3398 break;
3399 case FastMixer_Static:
3400 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3401 break;
3402 }
3403}
3404
3405AudioFlinger::MixerThread::~MixerThread()
3406{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003407 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003408 FastMixerStateQueue *sq = mFastMixer->sq();
3409 FastMixerState *state = sq->begin();
3410 if (state->mCommand == FastMixerState::COLD_IDLE) {
3411 int32_t old = android_atomic_inc(&mFastMixerFutex);
3412 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003413 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003414 }
3415 }
3416 state->mCommand = FastMixerState::EXIT;
3417 sq->end();
3418 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3419 mFastMixer->join();
3420 // Though the fast mixer thread has exited, it's state queue is still valid.
3421 // We'll use that extract the final state which contains one remaining fast track
3422 // corresponding to our sub-mix.
3423 state = sq->begin();
3424 ALOG_ASSERT(state->mTrackMask == 1);
3425 FastTrack *fastTrack = &state->mFastTracks[0];
3426 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3427 delete fastTrack->mBufferProvider;
3428 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003429 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003430#ifdef AUDIO_WATCHDOG
3431 if (mAudioWatchdog != 0) {
3432 mAudioWatchdog->requestExit();
3433 mAudioWatchdog->requestExitAndWait();
3434 mAudioWatchdog.clear();
3435 }
3436#endif
3437 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003438 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003439 delete mAudioMixer;
3440}
3441
3442
3443uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3444{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003445 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003446 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3447 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3448 }
3449 return latency;
3450}
3451
3452
3453void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3454{
3455 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3456}
3457
Eric Laurentbfb1b832013-01-07 09:53:42 -08003458ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003459{
3460 // FIXME we should only do one push per cycle; confirm this is true
3461 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003462 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003463 FastMixerStateQueue *sq = mFastMixer->sq();
3464 FastMixerState *state = sq->begin();
3465 if (state->mCommand != FastMixerState::MIX_WRITE &&
3466 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3467 if (state->mCommand == FastMixerState::COLD_IDLE) {
3468 int32_t old = android_atomic_inc(&mFastMixerFutex);
3469 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003470 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003471 }
3472#ifdef AUDIO_WATCHDOG
3473 if (mAudioWatchdog != 0) {
3474 mAudioWatchdog->resume();
3475 }
3476#endif
3477 }
3478 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08003479#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003480 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08003481 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08003482#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003483 sq->end();
3484 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3485 if (kUseFastMixer == FastMixer_Dynamic) {
3486 mNormalSink = mPipeSink;
3487 }
3488 } else {
3489 sq->end(false /*didModify*/);
3490 }
3491 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003492 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003493}
3494
3495void AudioFlinger::MixerThread::threadLoop_standby()
3496{
3497 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003498 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003499 FastMixerStateQueue *sq = mFastMixer->sq();
3500 FastMixerState *state = sq->begin();
3501 if (!(state->mCommand & FastMixerState::IDLE)) {
3502 state->mCommand = FastMixerState::COLD_IDLE;
3503 state->mColdFutexAddr = &mFastMixerFutex;
3504 state->mColdGen++;
3505 mFastMixerFutex = 0;
3506 sq->end();
3507 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3508 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3509 if (kUseFastMixer == FastMixer_Dynamic) {
3510 mNormalSink = mOutputSink;
3511 }
3512#ifdef AUDIO_WATCHDOG
3513 if (mAudioWatchdog != 0) {
3514 mAudioWatchdog->pause();
3515 }
3516#endif
3517 } else {
3518 sq->end(false /*didModify*/);
3519 }
3520 }
3521 PlaybackThread::threadLoop_standby();
3522}
3523
Eric Laurentbfb1b832013-01-07 09:53:42 -08003524bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3525{
3526 return false;
3527}
3528
3529bool AudioFlinger::PlaybackThread::shouldStandby_l()
3530{
3531 return !mStandby;
3532}
3533
3534bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3535{
3536 Mutex::Autolock _l(mLock);
3537 return waitingAsyncCallback_l();
3538}
3539
Eric Laurent81784c32012-11-19 14:55:58 -08003540// shared by MIXER and DIRECT, overridden by DUPLICATING
3541void AudioFlinger::PlaybackThread::threadLoop_standby()
3542{
3543 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08003544 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003545 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003546 // discard any pending drain or write ack by incrementing sequence
3547 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3548 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003549 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003550 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3551 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003552 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003553 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003554}
3555
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003556void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3557{
3558 ALOGV("signal playback thread");
3559 broadcast_l();
3560}
3561
Eric Laurent81784c32012-11-19 14:55:58 -08003562void AudioFlinger::MixerThread::threadLoop_mix()
3563{
3564 // obtain the presentation timestamp of the next output buffer
3565 int64_t pts;
3566 status_t status = INVALID_OPERATION;
3567
3568 if (mNormalSink != 0) {
3569 status = mNormalSink->getNextWriteTimestamp(&pts);
3570 } else {
3571 status = mOutputSink->getNextWriteTimestamp(&pts);
3572 }
3573
3574 if (status != NO_ERROR) {
3575 pts = AudioBufferProvider::kInvalidPTS;
3576 }
3577
3578 // mix buffers...
3579 mAudioMixer->process(pts);
Andy Hung25c2dac2014-02-27 14:56:00 -08003580 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003581 // increase sleep time progressively when application underrun condition clears.
3582 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3583 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3584 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003585 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003586 sleepTimeShift--;
3587 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003588 mSleepTimeUs = 0;
3589 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08003590 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003591
Eric Laurent81784c32012-11-19 14:55:58 -08003592}
3593
3594void AudioFlinger::MixerThread::threadLoop_sleepTime()
3595{
3596 // If no tracks are ready, sleep once for the duration of an output
3597 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003598 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003599 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003600 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
3601 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
3602 mSleepTimeUs = kMinThreadSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003603 }
3604 // reduce sleep time in case of consecutive application underruns to avoid
3605 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3606 // duration we would end up writing less data than needed by the audio HAL if
3607 // the condition persists.
3608 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3609 sleepTimeShift++;
3610 }
3611 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003612 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003613 }
3614 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003615 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3616 // before effects processing or output.
3617 if (mMixerBufferValid) {
3618 memset(mMixerBuffer, 0, mMixerBufferSize);
3619 } else {
3620 memset(mSinkBuffer, 0, mSinkBufferSize);
3621 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003622 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003623 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3624 "anticipated start");
3625 }
3626 // TODO add standby time extension fct of effect tail
3627}
3628
3629// prepareTracks_l() must be called with ThreadBase::mLock held
3630AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3631 Vector< sp<Track> > *tracksToRemove)
3632{
3633
3634 mixer_state mixerStatus = MIXER_IDLE;
3635 // find out which tracks need to be processed
3636 size_t count = mActiveTracks.size();
3637 size_t mixedTracks = 0;
3638 size_t tracksWithEffect = 0;
3639 // counts only _active_ fast tracks
3640 size_t fastTracks = 0;
3641 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
3642
3643 float masterVolume = mMasterVolume;
3644 bool masterMute = mMasterMute;
3645
3646 if (masterMute) {
3647 masterVolume = 0;
3648 }
3649 // Delegate master volume control to effect in output mix effect chain if needed
3650 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3651 if (chain != 0) {
3652 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
3653 chain->setVolume_l(&v, &v);
3654 masterVolume = (float)((v + (1 << 23)) >> 24);
3655 chain.clear();
3656 }
3657
3658 // prepare a new state to push
3659 FastMixerStateQueue *sq = NULL;
3660 FastMixerState *state = NULL;
3661 bool didModify = false;
3662 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003663 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003664 sq = mFastMixer->sq();
3665 state = sq->begin();
3666 }
3667
Andy Hung69aed5f2014-02-25 17:24:40 -08003668 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08003669 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08003670
Eric Laurent81784c32012-11-19 14:55:58 -08003671 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003672 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003673 if (t == 0) {
3674 continue;
3675 }
3676
3677 // this const just means the local variable doesn't change
3678 Track* const track = t.get();
3679
3680 // process fast tracks
3681 if (track->isFastTrack()) {
3682
3683 // It's theoretically possible (though unlikely) for a fast track to be created
3684 // and then removed within the same normal mix cycle. This is not a problem, as
3685 // the track never becomes active so it's fast mixer slot is never touched.
3686 // The converse, of removing an (active) track and then creating a new track
3687 // at the identical fast mixer slot within the same normal mix cycle,
3688 // is impossible because the slot isn't marked available until the end of each cycle.
3689 int j = track->mFastIndex;
3690 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
3691 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
3692 FastTrack *fastTrack = &state->mFastTracks[j];
3693
3694 // Determine whether the track is currently in underrun condition,
3695 // and whether it had a recent underrun.
3696 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
3697 FastTrackUnderruns underruns = ftDump->mUnderruns;
3698 uint32_t recentFull = (underruns.mBitFields.mFull -
3699 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
3700 uint32_t recentPartial = (underruns.mBitFields.mPartial -
3701 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
3702 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
3703 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
3704 uint32_t recentUnderruns = recentPartial + recentEmpty;
3705 track->mObservedUnderruns = underruns;
3706 // don't count underruns that occur while stopping or pausing
3707 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07003708 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
3709 recentUnderruns > 0) {
3710 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
3711 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003712 }
3713
3714 // This is similar to the state machine for normal tracks,
3715 // with a few modifications for fast tracks.
3716 bool isActive = true;
3717 switch (track->mState) {
3718 case TrackBase::STOPPING_1:
3719 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08003720 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003721 track->mState = TrackBase::STOPPING_2;
3722 }
3723 break;
3724 case TrackBase::PAUSING:
3725 // ramp down is not yet implemented
3726 track->setPaused();
3727 break;
3728 case TrackBase::RESUMING:
3729 // ramp up is not yet implemented
3730 track->mState = TrackBase::ACTIVE;
3731 break;
3732 case TrackBase::ACTIVE:
3733 if (recentFull > 0 || recentPartial > 0) {
3734 // track has provided at least some frames recently: reset retry count
3735 track->mRetryCount = kMaxTrackRetries;
3736 }
3737 if (recentUnderruns == 0) {
3738 // no recent underruns: stay active
3739 break;
3740 }
3741 // there has recently been an underrun of some kind
3742 if (track->sharedBuffer() == 0) {
3743 // were any of the recent underruns "empty" (no frames available)?
3744 if (recentEmpty == 0) {
3745 // no, then ignore the partial underruns as they are allowed indefinitely
3746 break;
3747 }
3748 // there has recently been an "empty" underrun: decrement the retry counter
3749 if (--(track->mRetryCount) > 0) {
3750 break;
3751 }
3752 // indicate to client process that the track was disabled because of underrun;
3753 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003754 android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003755 // remove from active list, but state remains ACTIVE [confusing but true]
3756 isActive = false;
3757 break;
3758 }
3759 // fall through
3760 case TrackBase::STOPPING_2:
3761 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003762 case TrackBase::STOPPED:
3763 case TrackBase::FLUSHED: // flush() while active
3764 // Check for presentation complete if track is inactive
3765 // We have consumed all the buffers of this track.
3766 // This would be incomplete if we auto-paused on underrun
3767 {
3768 size_t audioHALFrames =
3769 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3770 size_t framesWritten = mBytesWritten / mFrameSize;
3771 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
3772 // track stays in active list until presentation is complete
3773 break;
3774 }
3775 }
3776 if (track->isStopping_2()) {
3777 track->mState = TrackBase::STOPPED;
3778 }
3779 if (track->isStopped()) {
3780 // Can't reset directly, as fast mixer is still polling this track
3781 // track->reset();
3782 // So instead mark this track as needing to be reset after push with ack
3783 resetMask |= 1 << i;
3784 }
3785 isActive = false;
3786 break;
3787 case TrackBase::IDLE:
3788 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08003789 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08003790 }
3791
3792 if (isActive) {
3793 // was it previously inactive?
3794 if (!(state->mTrackMask & (1 << j))) {
3795 ExtendedAudioBufferProvider *eabp = track;
3796 VolumeProvider *vp = track;
3797 fastTrack->mBufferProvider = eabp;
3798 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08003799 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003800 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08003801 fastTrack->mGeneration++;
3802 state->mTrackMask |= 1 << j;
3803 didModify = true;
3804 // no acknowledgement required for newly active tracks
3805 }
3806 // cache the combined master volume and stream type volume for fast mixer; this
3807 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08003808 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08003809 ++fastTracks;
3810 } else {
3811 // was it previously active?
3812 if (state->mTrackMask & (1 << j)) {
3813 fastTrack->mBufferProvider = NULL;
3814 fastTrack->mGeneration++;
3815 state->mTrackMask &= ~(1 << j);
3816 didModify = true;
3817 // If any fast tracks were removed, we must wait for acknowledgement
3818 // because we're about to decrement the last sp<> on those tracks.
3819 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3820 } else {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003821 LOG_ALWAYS_FATAL("fast track %d should have been active", j);
Eric Laurent81784c32012-11-19 14:55:58 -08003822 }
3823 tracksToRemove->add(track);
3824 // Avoids a misleading display in dumpsys
3825 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
3826 }
3827 continue;
3828 }
3829
3830 { // local variable scope to avoid goto warning
3831
3832 audio_track_cblk_t* cblk = track->cblk();
3833
3834 // The first time a track is added we wait
3835 // for all its buffers to be filled before processing it
3836 int name = track->name();
3837 // make sure that we have enough frames to mix one full buffer.
3838 // enforce this condition only once to enable draining the buffer in case the client
3839 // app does not call stop() and relies on underrun to stop:
3840 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
3841 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003842 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07003843 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07003844 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07003845
3846 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07003847 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07003848 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
3849 // add frames already consumed but not yet released by the resampler
3850 // because mAudioTrackServerProxy->framesReady() will include these frames
3851 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
3852
Eric Laurent81784c32012-11-19 14:55:58 -08003853 uint32_t minFrames = 1;
3854 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
3855 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003856 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08003857 }
Eric Laurent13e4c962013-12-20 17:36:01 -08003858
3859 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07003860 if (ATRACE_ENABLED()) {
3861 // I wish we had formatted trace names
3862 char traceName[16];
3863 strcpy(traceName, "nRdy");
3864 int name = track->name();
3865 if (AudioMixer::TRACK0 <= name &&
3866 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
3867 name -= AudioMixer::TRACK0;
3868 traceName[4] = (name / 10) + '0';
3869 traceName[5] = (name % 10) + '0';
3870 } else {
3871 traceName[4] = '?';
3872 traceName[5] = '?';
3873 }
3874 traceName[6] = '\0';
3875 ATRACE_INT(traceName, framesReady);
3876 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003877 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08003878 !track->isPaused() && !track->isTerminated())
3879 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003880 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003881
3882 mixedTracks++;
3883
Andy Hung69aed5f2014-02-25 17:24:40 -08003884 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
3885 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08003886 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08003887 if (track->mainBuffer() != mSinkBuffer &&
3888 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08003889 if (mEffectBufferEnabled) {
3890 mEffectBufferValid = true; // Later can set directly.
3891 }
Eric Laurent81784c32012-11-19 14:55:58 -08003892 chain = getEffectChain_l(track->sessionId());
3893 // Delegate volume control to effect in track effect chain if needed
3894 if (chain != 0) {
3895 tracksWithEffect++;
3896 } else {
3897 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
3898 "session %d",
3899 name, track->sessionId());
3900 }
3901 }
3902
3903
3904 int param = AudioMixer::VOLUME;
3905 if (track->mFillingUpStatus == Track::FS_FILLED) {
3906 // no ramp for the first volume setting
3907 track->mFillingUpStatus = Track::FS_ACTIVE;
3908 if (track->mState == TrackBase::RESUMING) {
3909 track->mState = TrackBase::ACTIVE;
3910 param = AudioMixer::RAMP_VOLUME;
3911 }
3912 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003913 // FIXME should not make a decision based on mServer
3914 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003915 // If the track is stopped before the first frame was mixed,
3916 // do not apply ramp
3917 param = AudioMixer::RAMP_VOLUME;
3918 }
3919
3920 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07003921 uint32_t vl, vr; // in U8.24 integer format
3922 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08003923 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07003924 vl = vr = 0;
3925 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08003926 if (track->isPausing()) {
3927 track->setPaused();
3928 }
3929 } else {
3930
3931 // read original volumes with volume control
3932 float typeVolume = mStreamTypes[track->streamType()].volume;
3933 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003934 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07003935 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07003936 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
3937 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08003938 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07003939 if (vlf > GAIN_FLOAT_UNITY) {
3940 ALOGV("Track left volume out of range: %.3g", vlf);
3941 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003942 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07003943 if (vrf > GAIN_FLOAT_UNITY) {
3944 ALOGV("Track right volume out of range: %.3g", vrf);
3945 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003946 }
3947 // now apply the master volume and stream type volume
Andy Hung6be49402014-05-30 10:42:03 -07003948 vlf *= v;
3949 vrf *= v;
Eric Laurent81784c32012-11-19 14:55:58 -08003950 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07003951 // then derive vl and vr as U8.24 versions for the effect chain
3952 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
3953 vl = (uint32_t) (scaleto8_24 * vlf);
3954 vr = (uint32_t) (scaleto8_24 * vrf);
3955 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08003956 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08003957 // send level comes from shared memory and so may be corrupt
3958 if (sendLevel > MAX_GAIN_INT) {
3959 ALOGV("Track send level out of range: %04X", sendLevel);
3960 sendLevel = MAX_GAIN_INT;
3961 }
Andy Hung6be49402014-05-30 10:42:03 -07003962 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
3963 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08003964 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003965
Eric Laurent81784c32012-11-19 14:55:58 -08003966 // Delegate volume control to effect in track effect chain if needed
3967 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3968 // Do not ramp volume if volume is controlled by effect
3969 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08003970 // Update remaining floating point volume levels
3971 vlf = (float)vl / (1 << 24);
3972 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08003973 track->mHasVolumeController = true;
3974 } else {
3975 // force no volume ramp when volume controller was just disabled or removed
3976 // from effect chain to avoid volume spike
3977 if (track->mHasVolumeController) {
3978 param = AudioMixer::VOLUME;
3979 }
3980 track->mHasVolumeController = false;
3981 }
3982
Eric Laurent81784c32012-11-19 14:55:58 -08003983 // XXX: these things DON'T need to be done each time
3984 mAudioMixer->setBufferProvider(name, track);
3985 mAudioMixer->enable(name);
3986
Andy Hung6be49402014-05-30 10:42:03 -07003987 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
3988 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
3989 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08003990 mAudioMixer->setParameter(
3991 name,
3992 AudioMixer::TRACK,
3993 AudioMixer::FORMAT, (void *)track->format());
3994 mAudioMixer->setParameter(
3995 name,
3996 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003997 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07003998 mAudioMixer->setParameter(
3999 name,
4000 AudioMixer::TRACK,
4001 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08004002 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07004003 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004004 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08004005 if (reqSampleRate == 0) {
4006 reqSampleRate = mSampleRate;
4007 } else if (reqSampleRate > maxSampleRate) {
4008 reqSampleRate = maxSampleRate;
4009 }
Eric Laurent81784c32012-11-19 14:55:58 -08004010 mAudioMixer->setParameter(
4011 name,
4012 AudioMixer::RESAMPLE,
4013 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004014 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004015
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004016 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004017 mAudioMixer->setParameter(
4018 name,
4019 AudioMixer::TIMESTRETCH,
4020 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004021 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004022
Andy Hung69aed5f2014-02-25 17:24:40 -08004023 /*
4024 * Select the appropriate output buffer for the track.
4025 *
Andy Hung98ef9782014-03-04 14:46:50 -08004026 * Tracks with effects go into their own effects chain buffer
4027 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08004028 *
4029 * Other tracks can use mMixerBuffer for higher precision
4030 * channel accumulation. If this buffer is enabled
4031 * (mMixerBufferEnabled true), then selected tracks will accumulate
4032 * into it.
4033 *
4034 */
4035 if (mMixerBufferEnabled
4036 && (track->mainBuffer() == mSinkBuffer
4037 || track->mainBuffer() == mMixerBuffer)) {
4038 mAudioMixer->setParameter(
4039 name,
4040 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004041 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08004042 mAudioMixer->setParameter(
4043 name,
4044 AudioMixer::TRACK,
4045 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
4046 // TODO: override track->mainBuffer()?
4047 mMixerBufferValid = true;
4048 } else {
4049 mAudioMixer->setParameter(
4050 name,
4051 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004052 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08004053 mAudioMixer->setParameter(
4054 name,
4055 AudioMixer::TRACK,
4056 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
4057 }
Eric Laurent81784c32012-11-19 14:55:58 -08004058 mAudioMixer->setParameter(
4059 name,
4060 AudioMixer::TRACK,
4061 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
4062
4063 // reset retry count
4064 track->mRetryCount = kMaxTrackRetries;
4065
4066 // If one track is ready, set the mixer ready if:
4067 // - the mixer was not ready during previous round OR
4068 // - no other track is not ready
4069 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
4070 mixerStatus != MIXER_TRACKS_ENABLED) {
4071 mixerStatus = MIXER_TRACKS_READY;
4072 }
4073 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004074 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hung08fb1742015-05-31 23:22:10 -07004075 ALOGV("track(%p) underrun, framesReady(%zu) < framesDesired(%zd)",
4076 track, framesReady, desiredFrames);
Glenn Kasten82aaf942013-07-17 16:05:07 -07004077 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004078 }
Eric Laurent81784c32012-11-19 14:55:58 -08004079 // clear effect chain input buffer if an active track underruns to avoid sending
4080 // previous audio buffer again to effects
4081 chain = getEffectChain_l(track->sessionId());
4082 if (chain != 0) {
4083 chain->clearInputBuffer();
4084 }
4085
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004086 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004087 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
4088 track->isStopped() || track->isPaused()) {
4089 // We have consumed all the buffers of this track.
4090 // Remove it from the list of active tracks.
4091 // TODO: use actual buffer filling status instead of latency when available from
4092 // audio HAL
4093 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
4094 size_t framesWritten = mBytesWritten / mFrameSize;
4095 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
4096 if (track->isStopped()) {
4097 track->reset();
4098 }
4099 tracksToRemove->add(track);
4100 }
4101 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08004102 // No buffers for this track. Give it a few chances to
4103 // fill a buffer, then remove it from active list.
4104 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004105 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004106 tracksToRemove->add(track);
4107 // indicate to client process that the track was disabled because of underrun;
4108 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07004109 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08004110 // If one track is not ready, mark the mixer also not ready if:
4111 // - the mixer was ready during previous round OR
4112 // - no other track is ready
4113 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
4114 mixerStatus != MIXER_TRACKS_READY) {
4115 mixerStatus = MIXER_TRACKS_ENABLED;
4116 }
4117 }
4118 mAudioMixer->disable(name);
4119 }
4120
4121 } // local variable scope to avoid goto warning
4122track_is_ready: ;
4123
4124 }
4125
4126 // Push the new FastMixer state if necessary
4127 bool pauseAudioWatchdog = false;
4128 if (didModify) {
4129 state->mFastTracksGen++;
4130 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4131 if (kUseFastMixer == FastMixer_Dynamic &&
4132 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4133 state->mCommand = FastMixerState::COLD_IDLE;
4134 state->mColdFutexAddr = &mFastMixerFutex;
4135 state->mColdGen++;
4136 mFastMixerFutex = 0;
4137 if (kUseFastMixer == FastMixer_Dynamic) {
4138 mNormalSink = mOutputSink;
4139 }
4140 // If we go into cold idle, need to wait for acknowledgement
4141 // so that fast mixer stops doing I/O.
4142 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4143 pauseAudioWatchdog = true;
4144 }
Eric Laurent81784c32012-11-19 14:55:58 -08004145 }
4146 if (sq != NULL) {
4147 sq->end(didModify);
4148 sq->push(block);
4149 }
4150#ifdef AUDIO_WATCHDOG
4151 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4152 mAudioWatchdog->pause();
4153 }
4154#endif
4155
4156 // Now perform the deferred reset on fast tracks that have stopped
4157 while (resetMask != 0) {
4158 size_t i = __builtin_ctz(resetMask);
4159 ALOG_ASSERT(i < count);
4160 resetMask &= ~(1 << i);
4161 sp<Track> t = mActiveTracks[i].promote();
4162 if (t == 0) {
4163 continue;
4164 }
4165 Track* track = t.get();
4166 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
4167 track->reset();
4168 }
4169
4170 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004171 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004172
Eric Laurent97d547d2014-09-02 14:45:53 -07004173 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
4174 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07004175 }
4176
4177 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07004178 // as long as there are effects we should clear the effects buffer, to avoid
4179 // passing a non-clean buffer to the effect chain
4180 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07004181 }
Andy Hung69aed5f2014-02-25 17:24:40 -08004182 // sink or mix buffer must be cleared if all tracks are connected to an
4183 // effect chain as in this case the mixer will not write to the sink or mix buffer
4184 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08004185 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4186 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08004187 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08004188 if (mMixerBufferValid) {
4189 memset(mMixerBuffer, 0, mMixerBufferSize);
4190 // TODO: In testing, mSinkBuffer below need not be cleared because
4191 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
4192 // after mixing.
4193 //
4194 // To enforce this guarantee:
4195 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4196 // (mixedTracks == 0 && fastTracks > 0))
4197 // must imply MIXER_TRACKS_READY.
4198 // Later, we may clear buffers regardless, and skip much of this logic.
4199 }
Andy Hung98ef9782014-03-04 14:46:50 -08004200 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07004201 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004202 }
4203
4204 // if any fast tracks, then status is ready
4205 mMixerStatusIgnoringFastTracks = mixerStatus;
4206 if (fastTracks > 0) {
4207 mixerStatus = MIXER_TRACKS_READY;
4208 }
4209 return mixerStatus;
4210}
4211
4212// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07004213int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
4214 audio_format_t format, int sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08004215{
Andy Hunge8a1ced2014-05-09 15:02:21 -07004216 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08004217}
4218
4219// deleteTrackName_l() must be called with ThreadBase::mLock held
4220void AudioFlinger::MixerThread::deleteTrackName_l(int name)
4221{
4222 ALOGV("remove track (%d) and delete from mixer", name);
4223 mAudioMixer->deleteTrackName(name);
4224}
4225
Eric Laurent10351942014-05-08 18:49:52 -07004226// checkForNewParameter_l() must be called with ThreadBase::mLock held
4227bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
4228 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004229{
Eric Laurent81784c32012-11-19 14:55:58 -08004230 bool reconfig = false;
4231
Eric Laurent10351942014-05-08 18:49:52 -07004232 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004233
Eric Laurent10351942014-05-08 18:49:52 -07004234 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
4235 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004236 if (mFastMixer != 0) {
Eric Laurent10351942014-05-08 18:49:52 -07004237 FastMixerStateQueue *sq = mFastMixer->sq();
4238 FastMixerState *state = sq->begin();
4239 if (!(state->mCommand & FastMixerState::IDLE)) {
4240 previousCommand = state->mCommand;
4241 state->mCommand = FastMixerState::HOT_IDLE;
4242 sq->end();
4243 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
4244 } else {
4245 sq->end(false /*didModify*/);
Eric Laurent81784c32012-11-19 14:55:58 -08004246 }
Eric Laurent10351942014-05-08 18:49:52 -07004247 }
Eric Laurent81784c32012-11-19 14:55:58 -08004248
Eric Laurent10351942014-05-08 18:49:52 -07004249 AudioParameter param = AudioParameter(keyValuePair);
4250 int value;
4251 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4252 reconfig = true;
4253 }
4254 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004255 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004256 status = BAD_VALUE;
4257 } else {
4258 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08004259 reconfig = true;
4260 }
Eric Laurent10351942014-05-08 18:49:52 -07004261 }
4262 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004263 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004264 status = BAD_VALUE;
4265 } else {
4266 // no need to save value, since it's constant
4267 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004268 }
Eric Laurent10351942014-05-08 18:49:52 -07004269 }
4270 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4271 // do not accept frame count changes if tracks are open as the track buffer
4272 // size depends on frame count and correct behavior would not be guaranteed
4273 // if frame count is changed after track creation
4274 if (!mTracks.isEmpty()) {
4275 status = INVALID_OPERATION;
4276 } else {
4277 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004278 }
Eric Laurent10351942014-05-08 18:49:52 -07004279 }
4280 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004281#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07004282 // when changing the audio output device, call addBatteryData to notify
4283 // the change
4284 if (mOutDevice != value) {
4285 uint32_t params = 0;
4286 // check whether speaker is on
4287 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
4288 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08004289 }
Eric Laurent10351942014-05-08 18:49:52 -07004290
4291 audio_devices_t deviceWithoutSpeaker
4292 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
4293 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07004294 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07004295 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4296 }
4297
4298 if (params != 0) {
4299 addBatteryData(params);
4300 }
4301 }
Eric Laurent81784c32012-11-19 14:55:58 -08004302#endif
4303
Eric Laurent10351942014-05-08 18:49:52 -07004304 // forward device change to effects that have requested to be
4305 // aware of attached audio device.
4306 if (value != AUDIO_DEVICE_NONE) {
4307 mOutDevice = value;
4308 for (size_t i = 0; i < mEffectChains.size(); i++) {
4309 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08004310 }
4311 }
Eric Laurent10351942014-05-08 18:49:52 -07004312 }
Eric Laurent81784c32012-11-19 14:55:58 -08004313
Eric Laurent10351942014-05-08 18:49:52 -07004314 if (status == NO_ERROR) {
4315 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4316 keyValuePair.string());
4317 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004318 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004319 mStandby = true;
4320 mBytesWritten = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004321 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Eric Laurent10351942014-05-08 18:49:52 -07004322 keyValuePair.string());
Eric Laurent81784c32012-11-19 14:55:58 -08004323 }
Eric Laurent10351942014-05-08 18:49:52 -07004324 if (status == NO_ERROR && reconfig) {
4325 readOutputParameters_l();
4326 delete mAudioMixer;
4327 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4328 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07004329 int name = getTrackName_l(mTracks[i]->mChannelMask,
4330 mTracks[i]->mFormat, mTracks[i]->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07004331 if (name < 0) {
4332 break;
4333 }
4334 mTracks[i]->mName = name;
4335 }
Eric Laurent73e26b62015-04-27 16:55:58 -07004336 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004337 }
Eric Laurent81784c32012-11-19 14:55:58 -08004338 }
4339
4340 if (!(previousCommand & FastMixerState::IDLE)) {
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004341 ALOG_ASSERT(mFastMixer != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08004342 FastMixerStateQueue *sq = mFastMixer->sq();
4343 FastMixerState *state = sq->begin();
4344 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
4345 state->mCommand = previousCommand;
4346 sq->end();
4347 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4348 }
4349
4350 return reconfig;
4351}
4352
4353
4354void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
4355{
4356 const size_t SIZE = 256;
4357 char buffer[SIZE];
4358 String8 result;
4359
4360 PlaybackThread::dumpInternals(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07004361 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Elliott Hughes87cebad2014-05-22 10:14:43 -07004362 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Eric Laurent81784c32012-11-19 14:55:58 -08004363
4364 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten4182c4e2013-07-15 14:45:07 -07004365 const FastMixerDumpState copy(mFastMixerDumpState);
Eric Laurent81784c32012-11-19 14:55:58 -08004366 copy.dump(fd);
4367
4368#ifdef STATE_QUEUE_DUMP
4369 // Similar for state queue
4370 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4371 observerCopy.dump(fd);
4372 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4373 mutatorCopy.dump(fd);
4374#endif
4375
Glenn Kasten46909e72013-02-26 09:20:22 -08004376#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08004377 // Write the tee output to a .wav file
4378 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08004379#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004380
4381#ifdef AUDIO_WATCHDOG
4382 if (mAudioWatchdog != 0) {
4383 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4384 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4385 wdCopy.dump(fd);
4386 }
4387#endif
4388}
4389
4390uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4391{
4392 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4393}
4394
4395uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4396{
4397 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4398}
4399
4400void AudioFlinger::MixerThread::cacheParameters_l()
4401{
4402 PlaybackThread::cacheParameters_l();
4403
4404 // FIXME: Relaxed timing because of a certain device that can't meet latency
4405 // Should be reduced to 2x after the vendor fixes the driver issue
4406 // increase threshold again due to low power audio mode. The way this warning
4407 // threshold is calculated and its usefulness should be reconsidered anyway.
4408 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4409}
4410
4411// ----------------------------------------------------------------------------
4412
4413AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07004414 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device, bool systemReady)
4415 : PlaybackThread(audioFlinger, output, id, device, DIRECT, systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08004416 // mLeftVolFloat, mRightVolFloat
4417{
4418}
4419
Eric Laurentbfb1b832013-01-07 09:53:42 -08004420AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4421 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07004422 ThreadBase::type_t type, bool systemReady)
4423 : PlaybackThread(audioFlinger, output, id, device, type, systemReady)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004424 // mLeftVolFloat, mRightVolFloat
4425{
4426}
4427
Eric Laurent81784c32012-11-19 14:55:58 -08004428AudioFlinger::DirectOutputThread::~DirectOutputThread()
4429{
4430}
4431
Eric Laurentbfb1b832013-01-07 09:53:42 -08004432void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
4433{
4434 audio_track_cblk_t* cblk = track->cblk();
4435 float left, right;
4436
4437 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4438 left = right = 0;
4439 } else {
4440 float typeVolume = mStreamTypes[track->streamType()].volume;
4441 float v = mMasterVolume * typeVolume;
4442 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004443 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4444 left = float_from_gain(gain_minifloat_unpack_left(vlr));
4445 if (left > GAIN_FLOAT_UNITY) {
4446 left = GAIN_FLOAT_UNITY;
4447 }
4448 left *= v;
4449 right = float_from_gain(gain_minifloat_unpack_right(vlr));
4450 if (right > GAIN_FLOAT_UNITY) {
4451 right = GAIN_FLOAT_UNITY;
4452 }
4453 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004454 }
4455
4456 if (lastTrack) {
4457 if (left != mLeftVolFloat || right != mRightVolFloat) {
4458 mLeftVolFloat = left;
4459 mRightVolFloat = right;
4460
4461 // Convert volumes from float to 8.24
4462 uint32_t vl = (uint32_t)(left * (1 << 24));
4463 uint32_t vr = (uint32_t)(right * (1 << 24));
4464
4465 // Delegate volume control to effect in track effect chain if needed
4466 // only one effect chain can be present on DirectOutputThread, so if
4467 // there is one, the track is connected to it
4468 if (!mEffectChains.isEmpty()) {
4469 mEffectChains[0]->setVolume_l(&vl, &vr);
4470 left = (float)vl / (1 << 24);
4471 right = (float)vr / (1 << 24);
4472 }
4473 if (mOutput->stream->set_volume) {
4474 mOutput->stream->set_volume(mOutput->stream, left, right);
4475 }
4476 }
4477 }
4478}
4479
Phil Burk43b4dcc2015-06-09 16:53:44 -07004480void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
4481{
4482 sp<Track> previousTrack = mPreviousTrack.promote();
4483 sp<Track> latestTrack = mLatestActiveTrack.promote();
4484
4485 if (previousTrack != 0 && latestTrack != 0 &&
4486 (previousTrack->sessionId() != latestTrack->sessionId())) {
4487 mFlushPending = true;
4488 }
4489 PlaybackThread::onAddNewTrack_l();
4490}
Eric Laurentbfb1b832013-01-07 09:53:42 -08004491
Eric Laurent81784c32012-11-19 14:55:58 -08004492AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4493 Vector< sp<Track> > *tracksToRemove
4494)
4495{
Eric Laurentd595b7c2013-04-03 17:27:56 -07004496 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08004497 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004498 bool doHwPause = false;
4499 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004500
4501 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07004502 for (size_t i = 0; i < count; i++) {
4503 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08004504 // The track died recently
4505 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004506 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08004507 }
4508
Phil Burk43b4dcc2015-06-09 16:53:44 -07004509 if (t->isInvalid()) {
4510 ALOGW("An invalidated track shouldn't be in active list");
4511 tracksToRemove->add(t);
4512 continue;
4513 }
4514
Eric Laurent81784c32012-11-19 14:55:58 -08004515 Track* const track = t.get();
4516 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07004517 // Only consider last track started for volume and mixer state control.
4518 // In theory an older track could underrun and restart after the new one starts
4519 // but as we only care about the transition phase between two tracks on a
4520 // direct output, it is not a problem to ignore the underrun case.
4521 sp<Track> l = mLatestActiveTrack.promote();
4522 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08004523
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004524 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004525 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004526 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004527 doHwPause = true;
4528 mHwPaused = true;
4529 }
4530 tracksToRemove->add(track);
4531 } else if (track->isFlushPending()) {
4532 track->flushAck();
4533 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004534 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004535 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004536 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004537 track->resumeAck();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004538 if (last && mHwPaused) {
4539 doHwResume = true;
4540 mHwPaused = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004541 }
4542 }
4543
Eric Laurent81784c32012-11-19 14:55:58 -08004544 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08004545 // for all its buffers to be filled before processing it.
4546 // Allow draining the buffer in case the client
4547 // app does not call stop() and relies on underrun to stop:
4548 // hence the test on (track->mRetryCount > 1).
4549 // If retryCount<=1 then track is about to underrun and be removed.
Eric Laurent81784c32012-11-19 14:55:58 -08004550 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08004551 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
4552 && (track->mRetryCount > 1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004553 minFrames = mNormalFrameCount;
4554 } else {
4555 minFrames = 1;
4556 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004557
Eric Laurentab5cdba2014-06-09 17:22:27 -07004558 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4559 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08004560 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004561 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08004562
4563 if (track->mFillingUpStatus == Track::FS_FILLED) {
4564 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004565 // make sure processVolume_l() will apply new volume even if 0
4566 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004567 if (!mHwSupportsPause) {
4568 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08004569 }
4570 }
4571
4572 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004573 processVolume_l(track, last);
4574 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004575 sp<Track> previousTrack = mPreviousTrack.promote();
4576 if (previousTrack != 0) {
4577 if (track != previousTrack.get()) {
4578 // Flush any data still being written from last track
4579 mBytesRemaining = 0;
4580 // flush data already sent if changing audio session as audio
4581 // comes from a different source. Also invalidate previous track to force a
4582 // seek when resuming.
4583 if (previousTrack->sessionId() != track->sessionId()) {
4584 previousTrack->invalidate();
4585 }
4586 }
4587 }
4588 mPreviousTrack = track;
4589
Eric Laurentd595b7c2013-04-03 17:27:56 -07004590 // reset retry count
4591 track->mRetryCount = kMaxTrackRetriesDirect;
4592 mActiveTrack = t;
4593 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07004594 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004595 doHwResume = true;
4596 mHwPaused = false;
4597 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004598 }
Eric Laurent81784c32012-11-19 14:55:58 -08004599 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004600 // clear effect chain input buffer if the last active track started underruns
4601 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07004602 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004603 mEffectChains[0]->clearInputBuffer();
4604 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004605 if (track->isStopping_1()) {
4606 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07004607 if (last && mHwPaused) {
4608 doHwResume = true;
4609 mHwPaused = false;
4610 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004611 }
4612 if ((track->sharedBuffer() != 0) || track->isStopped() ||
4613 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004614 // We have consumed all the buffers of this track.
4615 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07004616 size_t audioHALFrames;
4617 if (audio_is_linear_pcm(mFormat)) {
4618 audioHALFrames = (latency_l() * mSampleRate) / 1000;
4619 } else {
4620 audioHALFrames = 0;
4621 }
4622
Eric Laurent81784c32012-11-19 14:55:58 -08004623 size_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07004624 if (mStandby || !last ||
4625 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004626 if (track->isStopping_2()) {
4627 track->mState = TrackBase::STOPPED;
4628 }
Eric Laurent81784c32012-11-19 14:55:58 -08004629 if (track->isStopped()) {
4630 track->reset();
4631 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004632 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08004633 }
4634 } else {
4635 // No buffers for this track. Give it a few chances to
4636 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07004637 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08004638 if (--(track->mRetryCount) <= 0) {
4639 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07004640 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004641 // indicate to client process that the track was disabled because of underrun;
4642 // it will then automatically call start() when data is available
4643 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004644 } else if (last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004645 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07004646 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004647 doHwPause = true;
4648 mHwPaused = true;
4649 }
Eric Laurent81784c32012-11-19 14:55:58 -08004650 }
4651 }
4652 }
4653 }
4654
Eric Laurentd1f69b02014-12-15 14:33:13 -08004655 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07004656 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004657 for (size_t i = 0; i < mTracks.size(); i++) {
4658 if (mTracks[i]->isFlushPending()) {
4659 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004660 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004661 }
4662 }
4663 }
4664
4665 // make sure the pause/flush/resume sequence is executed in the right order.
4666 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4667 // before flush and then resume HW. This can happen in case of pause/flush/resume
4668 // if resume is received before pause is executed.
4669 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07004670 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004671 mOutput->stream->pause(mOutput->stream);
4672 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004673 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004674 flushHw_l();
4675 }
4676 if (mHwSupportsPause && !mStandby && doHwResume) {
4677 mOutput->stream->resume(mOutput->stream);
4678 }
Eric Laurent81784c32012-11-19 14:55:58 -08004679 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004680 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004681
4682 return mixerStatus;
4683}
4684
4685void AudioFlinger::DirectOutputThread::threadLoop_mix()
4686{
Eric Laurent81784c32012-11-19 14:55:58 -08004687 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08004688 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004689 // output audio to hardware
4690 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07004691 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004692 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08004693 status_t status = mActiveTrack->getNextBuffer(&buffer);
4694 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08004695 memset(curBuf, 0, frameCount * mFrameSize);
4696 break;
4697 }
4698 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
4699 frameCount -= buffer.frameCount;
4700 curBuf += buffer.frameCount * mFrameSize;
4701 mActiveTrack->releaseBuffer(&buffer);
4702 }
Andy Hung2098f272014-02-27 14:00:06 -08004703 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004704 mSleepTimeUs = 0;
4705 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08004706 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004707}
4708
4709void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
4710{
Eric Laurentd1f69b02014-12-15 14:33:13 -08004711 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004712 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004713 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004714 return;
4715 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004716 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004717 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004718 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004719 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004720 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004721 }
4722 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08004723 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004724 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004725 }
4726}
4727
Eric Laurentd1f69b02014-12-15 14:33:13 -08004728void AudioFlinger::DirectOutputThread::threadLoop_exit()
4729{
4730 {
4731 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08004732 for (size_t i = 0; i < mTracks.size(); i++) {
4733 if (mTracks[i]->isFlushPending()) {
4734 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004735 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004736 }
4737 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004738 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004739 flushHw_l();
4740 }
4741 }
4742 PlaybackThread::threadLoop_exit();
4743}
4744
4745// must be called with thread mutex locked
4746bool AudioFlinger::DirectOutputThread::shouldStandby_l()
4747{
4748 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07004749 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004750
4751 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4752 // after a timeout and we will enter standby then.
4753 if (mTracks.size() > 0) {
4754 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07004755 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
4756 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004757 }
4758
Eric Laurent5cff4032015-05-26 13:49:58 -07004759 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08004760}
4761
Eric Laurent81784c32012-11-19 14:55:58 -08004762// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004763int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Andy Hunge8a1ced2014-05-09 15:02:21 -07004764 audio_format_t format __unused, int sessionId __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004765{
4766 return 0;
4767}
4768
4769// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004770void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004771{
4772}
4773
Eric Laurent10351942014-05-08 18:49:52 -07004774// checkForNewParameter_l() must be called with ThreadBase::mLock held
4775bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
4776 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004777{
4778 bool reconfig = false;
4779
Eric Laurent10351942014-05-08 18:49:52 -07004780 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004781
Eric Laurent10351942014-05-08 18:49:52 -07004782 AudioParameter param = AudioParameter(keyValuePair);
4783 int value;
4784 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4785 // forward device change to effects that have requested to be
4786 // aware of attached audio device.
4787 if (value != AUDIO_DEVICE_NONE) {
4788 mOutDevice = value;
4789 for (size_t i = 0; i < mEffectChains.size(); i++) {
4790 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07004791 }
4792 }
Eric Laurent81784c32012-11-19 14:55:58 -08004793 }
Eric Laurent10351942014-05-08 18:49:52 -07004794 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4795 // do not accept frame count changes if tracks are open as the track buffer
4796 // size depends on frame count and correct behavior would not be garantied
4797 // if frame count is changed after track creation
4798 if (!mTracks.isEmpty()) {
4799 status = INVALID_OPERATION;
4800 } else {
4801 reconfig = true;
4802 }
4803 }
4804 if (status == NO_ERROR) {
4805 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4806 keyValuePair.string());
4807 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004808 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004809 mStandby = true;
4810 mBytesWritten = 0;
4811 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4812 keyValuePair.string());
4813 }
4814 if (status == NO_ERROR && reconfig) {
4815 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07004816 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004817 }
4818 }
4819
Eric Laurent81784c32012-11-19 14:55:58 -08004820 return reconfig;
4821}
4822
4823uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
4824{
4825 uint32_t time;
4826 if (audio_is_linear_pcm(mFormat)) {
4827 time = PlaybackThread::activeSleepTimeUs();
4828 } else {
4829 time = 10000;
4830 }
4831 return time;
4832}
4833
4834uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
4835{
4836 uint32_t time;
4837 if (audio_is_linear_pcm(mFormat)) {
4838 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
4839 } else {
4840 time = 10000;
4841 }
4842 return time;
4843}
4844
4845uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
4846{
4847 uint32_t time;
4848 if (audio_is_linear_pcm(mFormat)) {
4849 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
4850 } else {
4851 time = 10000;
4852 }
4853 return time;
4854}
4855
4856void AudioFlinger::DirectOutputThread::cacheParameters_l()
4857{
4858 PlaybackThread::cacheParameters_l();
4859
4860 // use shorter standby delay as on normal output to release
4861 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07004862 // no delay on outputs with HW A/V sync
4863 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004864 mStandbyDelayNs = 0;
Eric Laurent5cff4032015-05-26 13:49:58 -07004865 } else if ((mType == OFFLOAD) && !audio_is_linear_pcm(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004866 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07004867 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004868 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07004869 }
Eric Laurent81784c32012-11-19 14:55:58 -08004870}
4871
Eric Laurente659ef42014-09-29 13:06:46 -07004872void AudioFlinger::DirectOutputThread::flushHw_l()
4873{
Phil Burk062e67a2015-02-11 13:40:50 -08004874 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08004875 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07004876 mFlushPending = false;
Eric Laurente659ef42014-09-29 13:06:46 -07004877}
4878
Eric Laurent81784c32012-11-19 14:55:58 -08004879// ----------------------------------------------------------------------------
4880
Eric Laurentbfb1b832013-01-07 09:53:42 -08004881AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07004882 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004883 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07004884 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07004885 mWriteAckSequence(0),
4886 mDrainSequence(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004887{
4888}
4889
4890AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
4891{
4892}
4893
4894void AudioFlinger::AsyncCallbackThread::onFirstRef()
4895{
4896 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
4897}
4898
4899bool AudioFlinger::AsyncCallbackThread::threadLoop()
4900{
4901 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004902 uint32_t writeAckSequence;
4903 uint32_t drainSequence;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004904
4905 {
4906 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08004907 while (!((mWriteAckSequence & 1) ||
4908 (mDrainSequence & 1) ||
4909 exitPending())) {
4910 mWaitWorkCV.wait(mLock);
4911 }
4912
Eric Laurentbfb1b832013-01-07 09:53:42 -08004913 if (exitPending()) {
4914 break;
4915 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004916 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
4917 mWriteAckSequence, mDrainSequence);
4918 writeAckSequence = mWriteAckSequence;
4919 mWriteAckSequence &= ~1;
4920 drainSequence = mDrainSequence;
4921 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004922 }
4923 {
Eric Laurent4de95592013-09-26 15:28:21 -07004924 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
4925 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004926 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004927 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004928 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004929 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004930 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004931 }
4932 }
4933 }
4934 }
4935 return false;
4936}
4937
4938void AudioFlinger::AsyncCallbackThread::exit()
4939{
4940 ALOGV("AsyncCallbackThread::exit");
4941 Mutex::Autolock _l(mLock);
4942 requestExit();
4943 mWaitWorkCV.broadcast();
4944}
4945
Eric Laurent3b4529e2013-09-05 18:09:19 -07004946void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004947{
4948 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004949 // bit 0 is cleared
4950 mWriteAckSequence = sequence << 1;
4951}
4952
4953void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
4954{
4955 Mutex::Autolock _l(mLock);
4956 // ignore unexpected callbacks
4957 if (mWriteAckSequence & 2) {
4958 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004959 mWaitWorkCV.signal();
4960 }
4961}
4962
Eric Laurent3b4529e2013-09-05 18:09:19 -07004963void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004964{
4965 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004966 // bit 0 is cleared
4967 mDrainSequence = sequence << 1;
4968}
4969
4970void AudioFlinger::AsyncCallbackThread::resetDraining()
4971{
4972 Mutex::Autolock _l(mLock);
4973 // ignore unexpected callbacks
4974 if (mDrainSequence & 2) {
4975 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004976 mWaitWorkCV.signal();
4977 }
4978}
4979
4980
4981// ----------------------------------------------------------------------------
4982AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07004983 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady)
4984 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady),
Eric Laurentd7e59222013-11-15 12:02:28 -08004985 mPausedBytesRemaining(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004986{
Eric Laurentfd477972013-10-25 18:10:40 -07004987 //FIXME: mStandby should be set to true by ThreadBase constructor
4988 mStandby = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004989}
4990
Eric Laurentbfb1b832013-01-07 09:53:42 -08004991void AudioFlinger::OffloadThread::threadLoop_exit()
4992{
4993 if (mFlushPending || mHwPaused) {
4994 // If a flush is pending or track was paused, just discard buffered data
4995 flushHw_l();
4996 } else {
4997 mMixerStatus = MIXER_DRAIN_ALL;
4998 threadLoop_drain();
4999 }
Uday Gupta56604aa2014-05-13 11:19:17 -07005000 if (mUseAsyncWrite) {
5001 ALOG_ASSERT(mCallbackThread != 0);
5002 mCallbackThread->exit();
5003 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005004 PlaybackThread::threadLoop_exit();
5005}
5006
5007AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
5008 Vector< sp<Track> > *tracksToRemove
5009)
5010{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005011 size_t count = mActiveTracks.size();
5012
5013 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07005014 bool doHwPause = false;
5015 bool doHwResume = false;
5016
Eric Laurentede6c3b2013-09-19 14:37:46 -07005017 ALOGV("OffloadThread::prepareTracks_l active tracks %d", count);
5018
Eric Laurentbfb1b832013-01-07 09:53:42 -08005019 // find out which tracks need to be processed
5020 for (size_t i = 0; i < count; i++) {
5021 sp<Track> t = mActiveTracks[i].promote();
5022 // The track died recently
5023 if (t == 0) {
5024 continue;
5025 }
5026 Track* const track = t.get();
5027 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07005028 // Only consider last track started for volume and mixer state control.
5029 // In theory an older track could underrun and restart after the new one starts
5030 // but as we only care about the transition phase between two tracks on a
5031 // direct output, it is not a problem to ignore the underrun case.
5032 sp<Track> l = mLatestActiveTrack.promote();
5033 bool last = l.get() == track;
5034
Haynes Mathew George7844f672014-01-15 12:32:55 -08005035 if (track->isInvalid()) {
5036 ALOGW("An invalidated track shouldn't be in active list");
5037 tracksToRemove->add(track);
5038 continue;
5039 }
5040
5041 if (track->mState == TrackBase::IDLE) {
5042 ALOGW("An idle track shouldn't be in active list");
5043 continue;
5044 }
5045
Eric Laurentbfb1b832013-01-07 09:53:42 -08005046 if (track->isPausing()) {
5047 track->setPaused();
5048 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07005049 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07005050 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005051 mHwPaused = true;
5052 }
5053 // If we were part way through writing the mixbuffer to
5054 // the HAL we must save this until we resume
5055 // BUG - this will be wrong if a different track is made active,
5056 // in that case we want to discard the pending data in the
5057 // mixbuffer and tell the client to present it again when the
5058 // track is resumed
5059 mPausedWriteLength = mCurrentWriteLength;
5060 mPausedBytesRemaining = mBytesRemaining;
5061 mBytesRemaining = 0; // stop writing
5062 }
5063 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08005064 } else if (track->isFlushPending()) {
5065 track->flushAck();
5066 if (last) {
5067 mFlushPending = true;
5068 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005069 } else if (track->isResumePending()){
5070 track->resumeAck();
5071 if (last) {
5072 if (mPausedBytesRemaining) {
5073 // Need to continue write that was interrupted
5074 mCurrentWriteLength = mPausedWriteLength;
5075 mBytesRemaining = mPausedBytesRemaining;
5076 mPausedBytesRemaining = 0;
5077 }
5078 if (mHwPaused) {
5079 doHwResume = true;
5080 mHwPaused = false;
5081 // threadLoop_mix() will handle the case that we need to
5082 // resume an interrupted write
5083 }
5084 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005085 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005086
5087 // Do not handle new data in this iteration even if track->framesReady()
5088 mixerStatus = MIXER_TRACKS_ENABLED;
5089 }
5090 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07005091 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005092 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005093 if (track->mFillingUpStatus == Track::FS_FILLED) {
5094 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07005095 // make sure processVolume_l() will apply new volume even if 0
5096 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005097 }
5098
5099 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08005100 sp<Track> previousTrack = mPreviousTrack.promote();
5101 if (previousTrack != 0) {
5102 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08005103 // Flush any data still being written from last track
5104 mBytesRemaining = 0;
5105 if (mPausedBytesRemaining) {
5106 // Last track was paused so we also need to flush saved
5107 // mixbuffer state and invalidate track so that it will
5108 // re-submit that unwritten data when it is next resumed
5109 mPausedBytesRemaining = 0;
5110 // Invalidate is a bit drastic - would be more efficient
5111 // to have a flag to tell client that some of the
5112 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08005113 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005114 }
5115 // flush data already sent to the DSP if changing audio session as audio
5116 // comes from a different source. Also invalidate previous track to force a
5117 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08005118 if (previousTrack->sessionId() != track->sessionId()) {
5119 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005120 }
5121 }
5122 }
5123 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005124 // reset retry count
5125 track->mRetryCount = kMaxTrackRetriesOffload;
5126 mActiveTrack = t;
5127 mixerStatus = MIXER_TRACKS_READY;
5128 }
5129 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005130 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005131 if (track->isStopping_1()) {
5132 // Hardware buffer can hold a large amount of audio so we must
5133 // wait for all current track's data to drain before we say
5134 // that the track is stopped.
5135 if (mBytesRemaining == 0) {
5136 // Only start draining when all data in mixbuffer
5137 // has been written
5138 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
5139 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005140 // do not drain if no data was ever sent to HAL (mStandby == true)
5141 if (last && !mStandby) {
Eric Laurent1b9f9b12013-11-12 19:10:17 -08005142 // do not modify drain sequence if we are already draining. This happens
5143 // when resuming from pause after drain.
5144 if ((mDrainSequence & 1) == 0) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005145 mSleepTimeUs = 0;
5146 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent1b9f9b12013-11-12 19:10:17 -08005147 mixerStatus = MIXER_DRAIN_TRACK;
5148 mDrainSequence += 2;
5149 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005150 if (mHwPaused) {
5151 // It is possible to move from PAUSED to STOPPING_1 without
5152 // a resume so we must ensure hardware is running
Eric Laurent1b9f9b12013-11-12 19:10:17 -08005153 doHwResume = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005154 mHwPaused = false;
5155 }
5156 }
5157 }
5158 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005159 // Drain has completed or we are in standby, signal presentation complete
5160 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005161 track->mState = TrackBase::STOPPED;
5162 size_t audioHALFrames =
5163 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
5164 size_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08005165 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005166 track->presentationComplete(framesWritten, audioHALFrames);
5167 track->reset();
5168 tracksToRemove->add(track);
5169 }
5170 } else {
5171 // No buffers for this track. Give it a few chances to
5172 // fill a buffer, then remove it from active list.
5173 if (--(track->mRetryCount) <= 0) {
5174 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
5175 track->name());
5176 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08005177 // indicate to client process that the track was disabled because of underrun;
5178 // it will then automatically call start() when data is available
5179 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005180 } else if (last){
5181 mixerStatus = MIXER_TRACKS_ENABLED;
5182 }
5183 }
5184 }
5185 // compute volume for this track
5186 processVolume_l(track, last);
5187 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005188
Eric Laurentea0fade2013-10-04 16:23:48 -07005189 // make sure the pause/flush/resume sequence is executed in the right order.
5190 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5191 // before flush and then resume HW. This can happen in case of pause/flush/resume
5192 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07005193 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurent972a1732013-09-04 09:42:59 -07005194 mOutput->stream->pause(mOutput->stream);
5195 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005196 if (mFlushPending) {
5197 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005198 }
Eric Laurentfd477972013-10-25 18:10:40 -07005199 if (!mStandby && doHwResume) {
Eric Laurent972a1732013-09-04 09:42:59 -07005200 mOutput->stream->resume(mOutput->stream);
5201 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005202
Eric Laurentbfb1b832013-01-07 09:53:42 -08005203 // remove all the tracks that need to be...
5204 removeTracks_l(*tracksToRemove);
5205
5206 return mixerStatus;
5207}
5208
Eric Laurentbfb1b832013-01-07 09:53:42 -08005209// must be called with thread mutex locked
5210bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
5211{
Eric Laurent3b4529e2013-09-05 18:09:19 -07005212 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
5213 mWriteAckSequence, mDrainSequence);
5214 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005215 return true;
5216 }
5217 return false;
5218}
5219
Eric Laurentbfb1b832013-01-07 09:53:42 -08005220bool AudioFlinger::OffloadThread::waitingAsyncCallback()
5221{
5222 Mutex::Autolock _l(mLock);
5223 return waitingAsyncCallback_l();
5224}
5225
5226void AudioFlinger::OffloadThread::flushHw_l()
5227{
Eric Laurente659ef42014-09-29 13:06:46 -07005228 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005229 // Flush anything still waiting in the mixbuffer
5230 mCurrentWriteLength = 0;
5231 mBytesRemaining = 0;
5232 mPausedWriteLength = 0;
5233 mPausedBytesRemaining = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08005234
Eric Laurentbfb1b832013-01-07 09:53:42 -08005235 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005236 // discard any pending drain or write ack by incrementing sequence
5237 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5238 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005239 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005240 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5241 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005242 }
5243}
5244
5245// ----------------------------------------------------------------------------
5246
Eric Laurent81784c32012-11-19 14:55:58 -08005247AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07005248 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08005249 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
Eric Laurent72e3f392015-05-20 14:43:50 -07005250 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08005251 mWaitTimeMs(UINT_MAX)
5252{
5253 addOutputTrack(mainThread);
5254}
5255
5256AudioFlinger::DuplicatingThread::~DuplicatingThread()
5257{
5258 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5259 mOutputTracks[i]->destroy();
5260 }
5261}
5262
5263void AudioFlinger::DuplicatingThread::threadLoop_mix()
5264{
5265 // mix buffers...
5266 if (outputsReady(outputTracks)) {
5267 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
5268 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08005269 if (mMixerBufferValid) {
5270 memset(mMixerBuffer, 0, mMixerBufferSize);
5271 } else {
5272 memset(mSinkBuffer, 0, mSinkBufferSize);
5273 }
Eric Laurent81784c32012-11-19 14:55:58 -08005274 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005275 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005276 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005277 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005278 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005279}
5280
5281void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
5282{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005283 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005284 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005285 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005286 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005287 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005288 }
5289 } else if (mBytesWritten != 0) {
5290 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5291 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005292 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005293 } else {
5294 // flush remaining overflow buffers in output tracks
5295 writeFrames = 0;
5296 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005297 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005298 }
5299}
5300
Eric Laurentbfb1b832013-01-07 09:53:42 -08005301ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005302{
5303 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08005304 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005305 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07005306 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08005307 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005308}
5309
5310void AudioFlinger::DuplicatingThread::threadLoop_standby()
5311{
5312 // DuplicatingThread implements standby by stopping all tracks
5313 for (size_t i = 0; i < outputTracks.size(); i++) {
5314 outputTracks[i]->stop();
5315 }
5316}
5317
5318void AudioFlinger::DuplicatingThread::saveOutputTracks()
5319{
5320 outputTracks = mOutputTracks;
5321}
5322
5323void AudioFlinger::DuplicatingThread::clearOutputTracks()
5324{
5325 outputTracks.clear();
5326}
5327
5328void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
5329{
5330 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08005331 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
5332 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
5333 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
5334 const size_t frameCount =
5335 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
5336 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
5337 // from different OutputTracks and their associated MixerThreads (e.g. one may
5338 // nearly empty and the other may be dropping data).
5339
5340 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08005341 this,
5342 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08005343 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08005344 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005345 frameCount,
5346 IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08005347 if (outputTrack->cblk() != NULL) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005348 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
Eric Laurent81784c32012-11-19 14:55:58 -08005349 mOutputTracks.add(outputTrack);
Andy Hungc25b84a2015-01-14 19:04:10 -08005350 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005351 updateWaitTime_l();
5352 }
5353}
5354
5355void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
5356{
5357 Mutex::Autolock _l(mLock);
5358 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5359 if (mOutputTracks[i]->thread() == thread) {
5360 mOutputTracks[i]->destroy();
5361 mOutputTracks.removeAt(i);
5362 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07005363 if (thread->getOutput() == mOutput) {
5364 mOutput = NULL;
5365 }
Eric Laurent81784c32012-11-19 14:55:58 -08005366 return;
5367 }
5368 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07005369 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005370}
5371
5372// caller must hold mLock
5373void AudioFlinger::DuplicatingThread::updateWaitTime_l()
5374{
5375 mWaitTimeMs = UINT_MAX;
5376 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5377 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
5378 if (strong != 0) {
5379 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
5380 if (waitTimeMs < mWaitTimeMs) {
5381 mWaitTimeMs = waitTimeMs;
5382 }
5383 }
5384 }
5385}
5386
5387
5388bool AudioFlinger::DuplicatingThread::outputsReady(
5389 const SortedVector< sp<OutputTrack> > &outputTracks)
5390{
5391 for (size_t i = 0; i < outputTracks.size(); i++) {
5392 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
5393 if (thread == 0) {
5394 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
5395 outputTracks[i].get());
5396 return false;
5397 }
5398 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5399 // see note at standby() declaration
5400 if (playbackThread->standby() && !playbackThread->isSuspended()) {
5401 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
5402 thread.get());
5403 return false;
5404 }
5405 }
5406 return true;
5407}
5408
5409uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
5410{
5411 return (mWaitTimeMs * 1000) / 2;
5412}
5413
5414void AudioFlinger::DuplicatingThread::cacheParameters_l()
5415{
5416 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
5417 updateWaitTime_l();
5418
5419 MixerThread::cacheParameters_l();
5420}
5421
5422// ----------------------------------------------------------------------------
5423// Record
5424// ----------------------------------------------------------------------------
5425
5426AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5427 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08005428 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08005429 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07005430 audio_devices_t inDevice,
5431 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08005432#ifdef TEE_SINK
5433 , const sp<NBAIO_Sink>& teeSink
5434#endif
5435 ) :
Eric Laurent72e3f392015-05-20 14:43:50 -07005436 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005437 mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005438 // mRsmpInFrames and mRsmpInFramesP2 are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005439 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08005440#ifdef TEE_SINK
5441 , mTeeSink(teeSink)
5442#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07005443 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
5444 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005445 // mFastCapture below
5446 , mFastCaptureFutex(0)
5447 // mInputSource
5448 // mPipeSink
5449 // mPipeSource
5450 , mPipeFramesP2(0)
5451 // mPipeMemory
5452 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005453 , mFastTrackAvail(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005454{
Glenn Kastend7dca052015-03-05 16:05:54 -08005455 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
5456 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08005457
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005458 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005459
5460 // create an NBAIO source for the HAL input stream, and negotiate
5461 mInputSource = new AudioStreamInSource(input->stream);
5462 size_t numCounterOffers = 0;
5463 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
5464 ssize_t index = mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
5465 ALOG_ASSERT(index == 0);
5466
5467 // initialize fast capture depending on configuration
5468 bool initFastCapture;
5469 switch (kUseFastCapture) {
5470 case FastCapture_Never:
5471 initFastCapture = false;
5472 break;
5473 case FastCapture_Always:
5474 initFastCapture = true;
5475 break;
5476 case FastCapture_Static:
5477 uint32_t primaryOutputSampleRate;
5478 {
5479 AutoMutex _l(audioFlinger->mHardwareLock);
5480 primaryOutputSampleRate = audioFlinger->mPrimaryOutputSampleRate;
5481 }
5482 initFastCapture =
5483 // either capture sample rate is same as (a reasonable) primary output sample rate
Andy Hungdb4c0312015-05-06 08:46:52 -07005484 ((isMusicRate(primaryOutputSampleRate) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005485 (mSampleRate == primaryOutputSampleRate)) ||
5486 // or primary output sample rate is unknown, and capture sample rate is reasonable
5487 ((primaryOutputSampleRate == 0) &&
Andy Hungdb4c0312015-05-06 08:46:52 -07005488 isMusicRate(mSampleRate))) &&
Glenn Kasten9f81de32014-07-27 15:02:23 -07005489 // and the buffer size is < 12 ms
5490 (mFrameCount * 1000) / mSampleRate < 12;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005491 break;
5492 // case FastCapture_Dynamic:
5493 }
5494
5495 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07005496 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005497 NBAIO_Format format = mInputSource->format();
Glenn Kasten49d00ad2014-07-21 11:22:03 -07005498 size_t pipeFramesP2 = roundup(mSampleRate / 25); // double-buffering of 20 ms each
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005499 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
5500 void *pipeBuffer;
5501 const sp<MemoryDealer> roHeap(readOnlyHeap());
5502 sp<IMemory> pipeMemory;
5503 if ((roHeap == 0) ||
5504 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
5505 (pipeBuffer = pipeMemory->pointer()) == NULL) {
5506 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
5507 goto failed;
5508 }
5509 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
5510 memset(pipeBuffer, 0, pipeSize);
5511 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
5512 const NBAIO_Format offers[1] = {format};
5513 size_t numCounterOffers = 0;
5514 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
5515 ALOG_ASSERT(index == 0);
5516 mPipeSink = pipe;
5517 PipeReader *pipeReader = new PipeReader(*pipe);
5518 numCounterOffers = 0;
5519 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
5520 ALOG_ASSERT(index == 0);
5521 mPipeSource = pipeReader;
5522 mPipeFramesP2 = pipeFramesP2;
5523 mPipeMemory = pipeMemory;
5524
5525 // create fast capture
5526 mFastCapture = new FastCapture();
5527 FastCaptureStateQueue *sq = mFastCapture->sq();
5528#ifdef STATE_QUEUE_DUMP
5529 // FIXME
5530#endif
5531 FastCaptureState *state = sq->begin();
5532 state->mCblk = NULL;
5533 state->mInputSource = mInputSource.get();
5534 state->mInputSourceGen++;
5535 state->mPipeSink = pipe;
5536 state->mPipeSinkGen++;
5537 state->mFrameCount = mFrameCount;
5538 state->mCommand = FastCaptureState::COLD_IDLE;
5539 // already done in constructor initialization list
5540 //mFastCaptureFutex = 0;
5541 state->mColdFutexAddr = &mFastCaptureFutex;
5542 state->mColdGen++;
5543 state->mDumpState = &mFastCaptureDumpState;
5544#ifdef TEE_SINK
5545 // FIXME
5546#endif
5547 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
5548 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
5549 sq->end();
5550 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5551
5552 // start the fast capture
5553 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
5554 pid_t tid = mFastCapture->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07005555 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005556#ifdef AUDIO_WATCHDOG
5557 // FIXME
5558#endif
5559
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005560 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005561 }
5562failed: ;
5563
5564 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08005565}
5566
Eric Laurent81784c32012-11-19 14:55:58 -08005567AudioFlinger::RecordThread::~RecordThread()
5568{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005569 if (mFastCapture != 0) {
5570 FastCaptureStateQueue *sq = mFastCapture->sq();
5571 FastCaptureState *state = sq->begin();
5572 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5573 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5574 if (old == -1) {
5575 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5576 }
5577 }
5578 state->mCommand = FastCaptureState::EXIT;
5579 sq->end();
5580 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5581 mFastCapture->join();
5582 mFastCapture.clear();
5583 }
5584 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07005585 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07005586 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08005587}
5588
5589void AudioFlinger::RecordThread::onFirstRef()
5590{
Glenn Kastend7dca052015-03-05 16:05:54 -08005591 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08005592}
5593
Eric Laurent81784c32012-11-19 14:55:58 -08005594bool AudioFlinger::RecordThread::threadLoop()
5595{
Eric Laurent81784c32012-11-19 14:55:58 -08005596 nsecs_t lastWarning = 0;
5597
5598 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08005599
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005600reacquire_wakelock:
5601 sp<RecordTrack> activeTrack;
Glenn Kasten2b806402013-11-20 16:37:38 -08005602 int activeTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005603 {
5604 Mutex::Autolock _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005605 size_t size = mActiveTracks.size();
5606 activeTracksGen = mActiveTracksGen;
5607 if (size > 0) {
5608 // FIXME an arbitrary choice
5609 activeTrack = mActiveTracks[0];
5610 acquireWakeLock_l(activeTrack->uid());
5611 if (size > 1) {
5612 SortedVector<int> tmp;
5613 for (size_t i = 0; i < size; i++) {
5614 tmp.add(mActiveTracks[i]->uid());
5615 }
5616 updateWakeLockUids_l(tmp);
5617 }
5618 } else {
5619 acquireWakeLock_l(-1);
5620 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005621 }
5622
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005623 // used to request a deferred sleep, to be executed later while mutex is unlocked
5624 uint32_t sleepUs = 0;
5625
5626 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005627 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005628 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07005629
Glenn Kasten5edadd42013-08-14 16:30:49 -07005630 // sleep with mutex unlocked
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005631 if (sleepUs > 0) {
Glenn Kastene7754022014-10-31 12:11:26 -07005632 ATRACE_BEGIN("sleep");
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005633 usleep(sleepUs);
Glenn Kastene7754022014-10-31 12:11:26 -07005634 ATRACE_END();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005635 sleepUs = 0;
Glenn Kasten5edadd42013-08-14 16:30:49 -07005636 }
5637
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005638 // activeTracks accumulates a copy of a subset of mActiveTracks
5639 Vector< sp<RecordTrack> > activeTracks;
5640
Glenn Kasten735f45f2014-08-18 15:51:59 -07005641 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005642 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07005643
Glenn Kasten735f45f2014-08-18 15:51:59 -07005644 // reference to a fast track which is about to be removed
5645 sp<RecordTrack> fastTrackToRemove;
5646
Eric Laurent81784c32012-11-19 14:55:58 -08005647 { // scope for mLock
5648 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08005649
Eric Laurent021cf962014-05-13 10:18:14 -07005650 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005651
Eric Laurent000a4192014-01-29 15:17:32 -08005652 // check exitPending here because checkForNewParameters_l() and
5653 // checkForNewParameters_l() can temporarily release mLock
5654 if (exitPending()) {
5655 break;
5656 }
5657
Glenn Kasten2b806402013-11-20 16:37:38 -08005658 // if no active track(s), then standby and release wakelock
5659 size_t size = mActiveTracks.size();
5660 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07005661 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005662 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08005663 releaseWakeLock_l();
5664 ALOGV("RecordThread: loop stopping");
5665 // go to sleep
5666 mWaitWorkCV.wait(mLock);
5667 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005668 goto reacquire_wakelock;
5669 }
5670
Glenn Kasten2b806402013-11-20 16:37:38 -08005671 if (mActiveTracksGen != activeTracksGen) {
5672 activeTracksGen = mActiveTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005673 SortedVector<int> tmp;
Glenn Kasten2b806402013-11-20 16:37:38 -08005674 for (size_t i = 0; i < size; i++) {
5675 tmp.add(mActiveTracks[i]->uid());
5676 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005677 updateWakeLockUids_l(tmp);
Eric Laurent81784c32012-11-19 14:55:58 -08005678 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005679
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005680 bool doBroadcast = false;
5681 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07005682
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005683 activeTrack = mActiveTracks[i];
5684 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07005685 if (activeTrack->isFastTrack()) {
5686 ALOG_ASSERT(fastTrackToRemove == 0);
5687 fastTrackToRemove = activeTrack;
5688 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005689 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08005690 mActiveTracks.remove(activeTrack);
5691 mActiveTracksGen++;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005692 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07005693 continue;
5694 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005695
5696 TrackBase::track_state activeTrackState = activeTrack->mState;
5697 switch (activeTrackState) {
5698
5699 case TrackBase::PAUSING:
5700 mActiveTracks.remove(activeTrack);
5701 mActiveTracksGen++;
5702 doBroadcast = true;
5703 size--;
5704 continue;
5705
5706 case TrackBase::STARTING_1:
5707 sleepUs = 10000;
5708 i++;
5709 continue;
5710
5711 case TrackBase::STARTING_2:
5712 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005713 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07005714 activeTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005715 break;
5716
5717 case TrackBase::ACTIVE:
5718 break;
5719
5720 case TrackBase::IDLE:
5721 i++;
5722 continue;
5723
5724 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08005725 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07005726 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005727
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005728 activeTracks.add(activeTrack);
5729 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07005730
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005731 if (activeTrack->isFastTrack()) {
5732 ALOG_ASSERT(!mFastTrackAvail);
5733 ALOG_ASSERT(fastTrack == 0);
5734 fastTrack = activeTrack;
5735 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005736 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005737 if (doBroadcast) {
5738 mStartStopCond.broadcast();
5739 }
5740
5741 // sleep if there are no active tracks to process
5742 if (activeTracks.size() == 0) {
5743 if (sleepUs == 0) {
5744 sleepUs = kRecordThreadSleepUs;
5745 }
5746 continue;
5747 }
5748 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07005749
Eric Laurent81784c32012-11-19 14:55:58 -08005750 lockEffectChains_l(effectChains);
5751 }
5752
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005753 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07005754
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005755 size_t size = effectChains.size();
5756 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005757 // thread mutex is not locked, but effect chain is locked
5758 effectChains[i]->process_l();
5759 }
5760
Glenn Kasten735f45f2014-08-18 15:51:59 -07005761 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005762 if (mFastCapture != 0) {
5763 FastCaptureStateQueue *sq = mFastCapture->sq();
5764 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07005765 bool didModify = false;
5766 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005767 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
5768 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
5769 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5770 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5771 if (old == -1) {
5772 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5773 }
5774 }
5775 state->mCommand = FastCaptureState::READ_WRITE;
5776#if 0 // FIXME
5777 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08005778 FastThreadDumpState::kSamplingNforLowRamDevice :
5779 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005780#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07005781 didModify = true;
5782 }
5783 audio_track_cblk_t *cblkOld = state->mCblk;
5784 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
5785 if (cblkNew != cblkOld) {
5786 state->mCblk = cblkNew;
5787 // block until acked if removing a fast track
5788 if (cblkOld != NULL) {
5789 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
5790 }
5791 didModify = true;
5792 }
5793 sq->end(didModify);
5794 if (didModify) {
5795 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005796#if 0
5797 if (kUseFastCapture == FastCapture_Dynamic) {
5798 mNormalSource = mPipeSource;
5799 }
5800#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005801 }
5802 }
5803
Glenn Kasten735f45f2014-08-18 15:51:59 -07005804 // now run the fast track destructor with thread mutex unlocked
5805 fastTrackToRemove.clear();
5806
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005807 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
5808 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
5809 // slow, then this RecordThread will overrun by not calling HAL read often enough.
5810 // If destination is non-contiguous, first read past the nominal end of buffer, then
5811 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005812
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005813 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005814 ssize_t framesRead;
5815
5816 // If an NBAIO source is present, use it to read the normal capture's data
5817 if (mPipeSource != 0) {
5818 size_t framesToRead = mBufferSize / mFrameSize;
Andy Hung57446612015-04-19 23:56:46 -07005819 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005820 framesToRead, AudioBufferProvider::kInvalidPTS);
5821 if (framesRead == 0) {
5822 // since pipe is non-blocking, simulate blocking input
5823 sleepUs = (framesToRead * 1000000LL) / mSampleRate;
5824 }
5825 // otherwise use the HAL / AudioStreamIn directly
5826 } else {
5827 ssize_t bytesRead = mInput->stream->read(mInput->stream,
Andy Hung57446612015-04-19 23:56:46 -07005828 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005829 if (bytesRead < 0) {
5830 framesRead = bytesRead;
5831 } else {
5832 framesRead = bytesRead / mFrameSize;
5833 }
5834 }
5835
5836 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
5837 ALOGE("read failed: framesRead=%d", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005838 // Force input into standby so that it tries to recover at next read attempt
5839 inputStandBy();
5840 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005841 }
5842 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005843 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005844 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005845 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005846
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005847 if (mTeeSink != 0) {
Andy Hung57446612015-04-19 23:56:46 -07005848 (void) mTeeSink->write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005849 }
5850 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005851 {
5852 size_t part1 = mRsmpInFramesP2 - rear;
5853 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07005854 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005855 (framesRead - part1) * mFrameSize);
5856 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005857 }
5858 rear = mRsmpInRear += framesRead;
5859
5860 size = activeTracks.size();
5861 // loop over each active track
5862 for (size_t i = 0; i < size; i++) {
5863 activeTrack = activeTracks[i];
5864
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005865 // skip fast tracks, as those are handled directly by FastCapture
5866 if (activeTrack->isFastTrack()) {
5867 continue;
5868 }
5869
Andy Hung73c02e42015-03-29 01:13:58 -07005870 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07005871 // TODO: Update the activeTrack buffer converter in case of reconfigure.
5872
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005873 enum {
5874 OVERRUN_UNKNOWN,
5875 OVERRUN_TRUE,
5876 OVERRUN_FALSE
5877 } overrun = OVERRUN_UNKNOWN;
5878
5879 // loop over getNextBuffer to handle circular sink
5880 for (;;) {
5881
5882 activeTrack->mSink.frameCount = ~0;
5883 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
5884 size_t framesOut = activeTrack->mSink.frameCount;
5885 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
5886
Andy Hung73c02e42015-03-29 01:13:58 -07005887 // check available frames and handle overrun conditions
5888 // if the record track isn't draining fast enough.
5889 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005890 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07005891 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
5892 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005893 overrun = OVERRUN_TRUE;
5894 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005895 if (framesOut == 0 || framesIn == 0) {
5896 break;
5897 }
5898
Andy Hung6770c6f2015-04-07 13:43:36 -07005899 // Don't allow framesOut to be larger than what is possible with resampling
5900 // from framesIn.
5901 // This isn't strictly necessary but helps limit buffer resizing in
5902 // RecordBufferConverter. TODO: remove when no longer needed.
5903 framesOut = min(framesOut,
5904 destinationFramesPossible(
5905 framesIn, mSampleRate, activeTrack->mSampleRate));
Andy Hung97a893e2015-03-29 01:03:07 -07005906 // process frames from the RecordThread buffer provider to the RecordTrack buffer
5907 framesOut = activeTrack->mRecordBufferConverter->convert(
5908 activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005909
5910 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
5911 overrun = OVERRUN_FALSE;
5912 }
5913
5914 if (activeTrack->mFramesToDrop == 0) {
5915 if (framesOut > 0) {
5916 activeTrack->mSink.frameCount = framesOut;
5917 activeTrack->releaseBuffer(&activeTrack->mSink);
5918 }
5919 } else {
5920 // FIXME could do a partial drop of framesOut
5921 if (activeTrack->mFramesToDrop > 0) {
5922 activeTrack->mFramesToDrop -= framesOut;
5923 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005924 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005925 }
5926 } else {
5927 activeTrack->mFramesToDrop += framesOut;
5928 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
5929 activeTrack->mSyncStartEvent->isCancelled()) {
5930 ALOGW("Synced record %s, session %d, trigger session %d",
5931 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
5932 activeTrack->sessionId(),
5933 (activeTrack->mSyncStartEvent != 0) ?
5934 activeTrack->mSyncStartEvent->triggerSession() : 0);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005935 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005936 }
5937 }
5938 }
5939
5940 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005941 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005942 }
5943 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005944
5945 switch (overrun) {
5946 case OVERRUN_TRUE:
5947 // client isn't retrieving buffers fast enough
5948 if (!activeTrack->setOverflow()) {
5949 nsecs_t now = systemTime();
5950 // FIXME should lastWarning per track?
5951 if ((now - lastWarning) > kWarningThrottleNs) {
5952 ALOGW("RecordThread: buffer overflow");
5953 lastWarning = now;
5954 }
5955 }
5956 break;
5957 case OVERRUN_FALSE:
5958 activeTrack->clearOverflow();
5959 break;
5960 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005961 break;
5962 }
5963
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005964 }
5965
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005966unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08005967 // enable changes in effect chain
5968 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005969 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08005970 }
5971
Glenn Kasten93e471f2013-08-19 08:40:07 -07005972 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08005973
5974 {
5975 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07005976 for (size_t i = 0; i < mTracks.size(); i++) {
5977 sp<RecordTrack> track = mTracks[i];
5978 track->invalidate();
5979 }
Glenn Kasten2b806402013-11-20 16:37:38 -08005980 mActiveTracks.clear();
5981 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08005982 mStartStopCond.broadcast();
5983 }
5984
5985 releaseWakeLock();
5986
5987 ALOGV("RecordThread %p exiting", this);
5988 return false;
5989}
5990
Glenn Kasten93e471f2013-08-19 08:40:07 -07005991void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08005992{
5993 if (!mStandby) {
5994 inputStandBy();
5995 mStandby = true;
5996 }
5997}
5998
5999void AudioFlinger::RecordThread::inputStandBy()
6000{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006001 // Idle the fast capture if it's currently running
6002 if (mFastCapture != 0) {
6003 FastCaptureStateQueue *sq = mFastCapture->sq();
6004 FastCaptureState *state = sq->begin();
6005 if (!(state->mCommand & FastCaptureState::IDLE)) {
6006 state->mCommand = FastCaptureState::COLD_IDLE;
6007 state->mColdFutexAddr = &mFastCaptureFutex;
6008 state->mColdGen++;
6009 mFastCaptureFutex = 0;
6010 sq->end();
6011 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
6012 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
6013#if 0
6014 if (kUseFastCapture == FastCapture_Dynamic) {
6015 // FIXME
6016 }
6017#endif
6018#ifdef AUDIO_WATCHDOG
6019 // FIXME
6020#endif
6021 } else {
6022 sq->end(false /*didModify*/);
6023 }
6024 }
Eric Laurent81784c32012-11-19 14:55:58 -08006025 mInput->stream->common.standby(&mInput->stream->common);
6026}
6027
Glenn Kasten05997e22014-03-13 15:08:33 -07006028// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07006029sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08006030 const sp<AudioFlinger::Client>& client,
6031 uint32_t sampleRate,
6032 audio_format_t format,
6033 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08006034 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08006035 int sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07006036 size_t *notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08006037 int uid,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07006038 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08006039 pid_t tid,
6040 status_t *status)
6041{
Glenn Kasten74935e42013-12-19 08:56:45 -08006042 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08006043 sp<RecordTrack> track;
6044 status_t lStatus;
6045
Glenn Kasten90e58b12013-07-31 16:16:02 -07006046 // client expresses a preference for FAST, but we get the final say
6047 if (*flags & IAudioFlinger::TRACK_FAST) {
6048 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07006049 // we formerly checked for a callback handler (non-0 tid),
6050 // but that is no longer required for TRANSFER_OBTAIN mode
6051 //
Glenn Kasten74105912014-07-03 12:28:53 -07006052 // frame count is not specified, or is exactly the pipe depth
6053 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006054 // PCM data
6055 audio_is_linear_pcm(format) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006056 // native format
6057 (format == mFormat) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006058 // native channel mask
6059 (channelMask == mChannelMask) &&
6060 // native hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07006061 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006062 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006063 hasFastCapture() &&
6064 // there are sufficient fast track slots available
6065 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07006066 ) {
Glenn Kasten74105912014-07-03 12:28:53 -07006067 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%u mFrameCount=%u",
Glenn Kasten90e58b12013-07-31 16:16:02 -07006068 frameCount, mFrameCount);
6069 } else {
Glenn Kasten74105912014-07-03 12:28:53 -07006070 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%u mFrameCount=%u mPipeFramesP2=%u "
6071 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006072 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Glenn Kasten74105912014-07-03 12:28:53 -07006073 frameCount, mFrameCount, mPipeFramesP2,
6074 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
6075 hasFastCapture(), tid, mFastTrackAvail);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006076 *flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kasten74105912014-07-03 12:28:53 -07006077 }
6078 }
6079
6080 // compute track buffer size in frames, and suggest the notification frame count
6081 if (*flags & IAudioFlinger::TRACK_FAST) {
6082 // fast track: frame count is exactly the pipe depth
6083 frameCount = mPipeFramesP2;
6084 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
6085 *notificationFrames = mFrameCount;
6086 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006087 // not fast track: max notification period is resampled equivalent of one HAL buffer time
6088 // or 20 ms if there is a fast capture
6089 // TODO This could be a roundupRatio inline, and const
6090 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
6091 * sampleRate + mSampleRate - 1) / mSampleRate;
6092 // minimum number of notification periods is at least kMinNotifications,
6093 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
6094 static const size_t kMinNotifications = 3;
6095 static const uint32_t kMinMs = 30;
6096 // TODO This could be a roundupRatio inline
6097 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
6098 // TODO This could be a roundupRatio inline
6099 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
6100 maxNotificationFrames;
6101 const size_t minFrameCount = maxNotificationFrames *
6102 max(kMinNotifications, minNotificationsByMs);
6103 frameCount = max(frameCount, minFrameCount);
6104 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
6105 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07006106 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07006107 }
Glenn Kasten74935e42013-12-19 08:56:45 -08006108 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07006109
Glenn Kasten15e57982013-09-24 11:52:37 -07006110 lStatus = initCheck();
6111 if (lStatus != NO_ERROR) {
6112 ALOGE("createRecordTrack_l() audio driver not initialized");
6113 goto Exit;
6114 }
Eric Laurent81784c32012-11-19 14:55:58 -08006115
6116 { // scope for mLock
6117 Mutex::Autolock _l(mLock);
6118
6119 track = new RecordTrack(this, client, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07006120 format, channelMask, frameCount, NULL, sessionId, uid,
6121 *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08006122
Glenn Kasten03003332013-08-06 15:40:54 -07006123 lStatus = track->initCheck();
6124 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07006125 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08006126 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08006127 goto Exit;
6128 }
6129 mTracks.add(track);
6130
6131 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6132 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6133 mAudioFlinger->btNrecIsOff();
6134 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6135 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006136
6137 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
6138 pid_t callingPid = IPCThreadState::self()->getCallingPid();
6139 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
6140 // so ask activity manager to do this on our behalf
6141 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
6142 }
Eric Laurent81784c32012-11-19 14:55:58 -08006143 }
Glenn Kasten05997e22014-03-13 15:08:33 -07006144
Eric Laurent81784c32012-11-19 14:55:58 -08006145 lStatus = NO_ERROR;
6146
6147Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07006148 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08006149 return track;
6150}
6151
6152status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
6153 AudioSystem::sync_event_t event,
6154 int triggerSession)
6155{
6156 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
6157 sp<ThreadBase> strongMe = this;
6158 status_t status = NO_ERROR;
6159
6160 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006161 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006162 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006163 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08006164 triggerSession,
6165 recordTrack->sessionId(),
6166 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006167 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08006168 // Sync event can be cancelled by the trigger session if the track is not in a
6169 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006170 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006171 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006172 } else {
6173 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006174 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006175 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08006176 }
6177 }
6178
6179 {
Glenn Kasten47c20702013-08-13 15:37:35 -07006180 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08006181 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006182 if (mActiveTracks.indexOf(recordTrack) >= 0) {
6183 if (recordTrack->mState == TrackBase::PAUSING) {
6184 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006185 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006186 } else {
6187 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08006188 }
6189 return status;
6190 }
6191
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006192 // TODO consider other ways of handling this, such as changing the state to :STARTING and
6193 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
6194 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006195 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08006196 mActiveTracks.add(recordTrack);
6197 mActiveTracksGen++;
Eric Laurent83b88082014-06-20 18:31:16 -07006198 status_t status = NO_ERROR;
6199 if (recordTrack->isExternalTrack()) {
6200 mLock.unlock();
Eric Laurent4dc68062014-07-28 17:26:49 -07006201 status = AudioSystem::startInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006202 mLock.lock();
6203 // FIXME should verify that recordTrack is still in mActiveTracks
6204 if (status != NO_ERROR) {
6205 mActiveTracks.remove(recordTrack);
6206 mActiveTracksGen++;
6207 recordTrack->clearSyncStartEvent();
6208 ALOGV("RecordThread::start error %d", status);
6209 return status;
6210 }
Eric Laurent81784c32012-11-19 14:55:58 -08006211 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006212 // Catch up with current buffer indices if thread is already running.
6213 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
6214 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
6215 // see previously buffered data before it called start(), but with greater risk of overrun.
6216
Andy Hung73c02e42015-03-29 01:13:58 -07006217 recordTrack->mResamplerBufferProvider->reset();
Andy Hung97a893e2015-03-29 01:03:07 -07006218 // clear any converter state as new data will be discontinuous
6219 recordTrack->mRecordBufferConverter->reset();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006220 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08006221 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08006222 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08006223 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006224 ALOGV("Record failed to start");
6225 status = BAD_VALUE;
6226 goto startError;
6227 }
Eric Laurent81784c32012-11-19 14:55:58 -08006228 return status;
6229 }
Glenn Kasten7c027242012-12-26 14:43:16 -08006230
Eric Laurent81784c32012-11-19 14:55:58 -08006231startError:
Eric Laurent83b88082014-06-20 18:31:16 -07006232 if (recordTrack->isExternalTrack()) {
Eric Laurent4dc68062014-07-28 17:26:49 -07006233 AudioSystem::stopInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006234 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006235 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006236 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08006237 return status;
6238}
6239
Eric Laurent81784c32012-11-19 14:55:58 -08006240void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6241{
6242 sp<SyncEvent> strongEvent = event.promote();
6243
6244 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08006245 sp<RefBase> ptr = strongEvent->cookie().promote();
6246 if (ptr != 0) {
6247 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
6248 recordTrack->handleSyncStartEvent(strongEvent);
6249 }
Eric Laurent81784c32012-11-19 14:55:58 -08006250 }
6251}
6252
Glenn Kastena8356f62013-07-25 14:37:52 -07006253bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08006254 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07006255 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006256 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08006257 return false;
6258 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006259 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08006260 recordTrack->mState = TrackBase::PAUSING;
6261 // do not wait for mStartStopCond if exiting
6262 if (exitPending()) {
6263 return true;
6264 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006265 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08006266 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006267 // if we have been restarted, recordTrack is in mActiveTracks here
6268 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006269 ALOGV("Record stopped OK");
6270 return true;
6271 }
6272 return false;
6273}
6274
Glenn Kasten0f11b512014-01-31 16:18:54 -08006275bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08006276{
6277 return false;
6278}
6279
Glenn Kasten0f11b512014-01-31 16:18:54 -08006280status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006281{
6282#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
6283 if (!isValidSyncEvent(event)) {
6284 return BAD_VALUE;
6285 }
6286
6287 int eventSession = event->triggerSession();
6288 status_t ret = NAME_NOT_FOUND;
6289
6290 Mutex::Autolock _l(mLock);
6291
6292 for (size_t i = 0; i < mTracks.size(); i++) {
6293 sp<RecordTrack> track = mTracks[i];
6294 if (eventSession == track->sessionId()) {
6295 (void) track->setSyncEvent(event);
6296 ret = NO_ERROR;
6297 }
6298 }
6299 return ret;
6300#else
6301 return BAD_VALUE;
6302#endif
6303}
6304
6305// destroyTrack_l() must be called with ThreadBase::mLock held
6306void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6307{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006308 track->terminate();
6309 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08006310 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08006311 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006312 removeTrack_l(track);
6313 }
6314}
6315
6316void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6317{
6318 mTracks.remove(track);
6319 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006320 if (track->isFastTrack()) {
6321 ALOG_ASSERT(!mFastTrackAvail);
6322 mFastTrackAvail = true;
6323 }
Eric Laurent81784c32012-11-19 14:55:58 -08006324}
6325
6326void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6327{
6328 dumpInternals(fd, args);
6329 dumpTracks(fd, args);
6330 dumpEffectChains(fd, args);
6331}
6332
6333void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6334{
Elliott Hughes87cebad2014-05-22 10:14:43 -07006335 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08006336
Glenn Kasten44182c22015-03-05 17:12:23 -08006337 dumpBase(fd, args);
6338
6339 if (mActiveTracks.size() == 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006340 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006341 }
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006342 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006343 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08006344
6345 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
6346 const FastCaptureDumpState copy(mFastCaptureDumpState);
6347 copy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006348}
6349
Glenn Kasten0f11b512014-01-31 16:18:54 -08006350void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006351{
6352 const size_t SIZE = 256;
6353 char buffer[SIZE];
6354 String8 result;
6355
Marco Nelissenb2208842014-02-07 14:00:50 -08006356 size_t numtracks = mTracks.size();
6357 size_t numactive = mActiveTracks.size();
6358 size_t numactiveseen = 0;
Elliott Hughes87cebad2014-05-22 10:14:43 -07006359 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08006360 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006361 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08006362 RecordTrack::appendDumpHeader(result);
6363 for (size_t i = 0; i < numtracks ; ++i) {
6364 sp<RecordTrack> track = mTracks[i];
6365 if (track != 0) {
6366 bool active = mActiveTracks.indexOf(track) >= 0;
6367 if (active) {
6368 numactiveseen++;
6369 }
6370 track->dump(buffer, SIZE, active);
6371 result.append(buffer);
6372 }
Eric Laurent81784c32012-11-19 14:55:58 -08006373 }
Marco Nelissenb2208842014-02-07 14:00:50 -08006374 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006375 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006376 }
6377
Marco Nelissenb2208842014-02-07 14:00:50 -08006378 if (numactiveseen != numactive) {
6379 snprintf(buffer, SIZE, " The following tracks are in the active list but"
6380 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006381 result.append(buffer);
6382 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08006383 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08006384 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08006385 if (mTracks.indexOf(track) < 0) {
6386 track->dump(buffer, SIZE, true);
6387 result.append(buffer);
6388 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006389 }
Eric Laurent81784c32012-11-19 14:55:58 -08006390
6391 }
6392 write(fd, result.string(), result.size());
6393}
6394
Andy Hung73c02e42015-03-29 01:13:58 -07006395
6396void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
6397{
6398 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6399 RecordThread *recordThread = (RecordThread *) threadBase.get();
6400 mRsmpInFront = recordThread->mRsmpInRear;
6401 mRsmpInUnrel = 0;
6402}
6403
6404void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
6405 size_t *framesAvailable, bool *hasOverrun)
6406{
6407 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6408 RecordThread *recordThread = (RecordThread *) threadBase.get();
6409 const int32_t rear = recordThread->mRsmpInRear;
6410 const int32_t front = mRsmpInFront;
6411 const ssize_t filled = rear - front;
6412
6413 size_t framesIn;
6414 bool overrun = false;
6415 if (filled < 0) {
6416 // should not happen, but treat like a massive overrun and re-sync
6417 framesIn = 0;
6418 mRsmpInFront = rear;
6419 overrun = true;
6420 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
6421 framesIn = (size_t) filled;
6422 } else {
6423 // client is not keeping up with server, but give it latest data
6424 framesIn = recordThread->mRsmpInFrames;
6425 mRsmpInFront = /* front = */ rear - framesIn;
6426 overrun = true;
6427 }
6428 if (framesAvailable != NULL) {
6429 *framesAvailable = framesIn;
6430 }
6431 if (hasOverrun != NULL) {
6432 *hasOverrun = overrun;
6433 }
6434}
6435
Eric Laurent81784c32012-11-19 14:55:58 -08006436// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006437status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
6438 AudioBufferProvider::Buffer* buffer, int64_t pts __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006439{
Andy Hung73c02e42015-03-29 01:13:58 -07006440 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006441 if (threadBase == 0) {
6442 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006443 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006444 return NOT_ENOUGH_DATA;
6445 }
6446 RecordThread *recordThread = (RecordThread *) threadBase.get();
6447 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07006448 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07006449 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006450 // FIXME should not be P2 (don't want to increase latency)
6451 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006452 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07006453 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006454 front &= recordThread->mRsmpInFramesP2 - 1;
6455 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07006456 if (part1 > (size_t) filled) {
6457 part1 = filled;
6458 }
6459 size_t ask = buffer->frameCount;
6460 ALOG_ASSERT(ask > 0);
6461 if (part1 > ask) {
6462 part1 = ask;
6463 }
6464 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07006465 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07006466 buffer->raw = NULL;
6467 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07006468 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07006469 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08006470 }
6471
Andy Hung57446612015-04-19 23:56:46 -07006472 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07006473 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07006474 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08006475 return NO_ERROR;
6476}
6477
6478// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006479void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
6480 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006481{
Glenn Kasten85948432013-08-19 12:09:05 -07006482 size_t stepCount = buffer->frameCount;
6483 if (stepCount == 0) {
6484 return;
6485 }
Andy Hung73c02e42015-03-29 01:13:58 -07006486 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
6487 mRsmpInUnrel -= stepCount;
6488 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07006489 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006490 buffer->frameCount = 0;
6491}
6492
Andy Hung97a893e2015-03-29 01:03:07 -07006493AudioFlinger::RecordThread::RecordBufferConverter::RecordBufferConverter(
6494 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6495 uint32_t srcSampleRate,
6496 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6497 uint32_t dstSampleRate) :
6498 mSrcChannelMask(AUDIO_CHANNEL_INVALID), // updateParameters will set following vars
6499 // mSrcFormat
6500 // mSrcSampleRate
6501 // mDstChannelMask
6502 // mDstFormat
6503 // mDstSampleRate
6504 // mSrcChannelCount
6505 // mDstChannelCount
6506 // mDstFrameSize
6507 mBuf(NULL), mBufFrames(0), mBufFrameSize(0),
Andy Hungd330ee42015-04-20 13:23:41 -07006508 mResampler(NULL),
6509 mIsLegacyDownmix(false),
6510 mIsLegacyUpmix(false),
6511 mRequiresFloat(false),
6512 mInputConverterProvider(NULL)
Andy Hung97a893e2015-03-29 01:03:07 -07006513{
6514 (void)updateParameters(srcChannelMask, srcFormat, srcSampleRate,
6515 dstChannelMask, dstFormat, dstSampleRate);
6516}
6517
6518AudioFlinger::RecordThread::RecordBufferConverter::~RecordBufferConverter() {
6519 free(mBuf);
6520 delete mResampler;
Andy Hungd330ee42015-04-20 13:23:41 -07006521 delete mInputConverterProvider;
Andy Hung97a893e2015-03-29 01:03:07 -07006522}
6523
6524size_t AudioFlinger::RecordThread::RecordBufferConverter::convert(void *dst,
6525 AudioBufferProvider *provider, size_t frames)
6526{
Andy Hungd330ee42015-04-20 13:23:41 -07006527 if (mInputConverterProvider != NULL) {
6528 mInputConverterProvider->setBufferProvider(provider);
6529 provider = mInputConverterProvider;
6530 }
6531
6532 if (mResampler == NULL) {
Andy Hung97a893e2015-03-29 01:03:07 -07006533 ALOGVV("NO RESAMPLING sampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6534 mSrcSampleRate, mSrcFormat, mDstFormat);
6535
6536 AudioBufferProvider::Buffer buffer;
6537 for (size_t i = frames; i > 0; ) {
6538 buffer.frameCount = i;
6539 status_t status = provider->getNextBuffer(&buffer, 0);
6540 if (status != OK || buffer.frameCount == 0) {
6541 frames -= i; // cannot fill request.
6542 break;
6543 }
Andy Hungd330ee42015-04-20 13:23:41 -07006544 // format convert to destination buffer
6545 convertNoResampler(dst, buffer.raw, buffer.frameCount);
Andy Hung97a893e2015-03-29 01:03:07 -07006546
6547 dst = (int8_t*)dst + buffer.frameCount * mDstFrameSize;
6548 i -= buffer.frameCount;
6549 provider->releaseBuffer(&buffer);
6550 }
6551 } else {
6552 ALOGVV("RESAMPLING mSrcSampleRate:%u mDstSampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6553 mSrcSampleRate, mDstSampleRate, mSrcFormat, mDstFormat);
6554
Andy Hungd330ee42015-04-20 13:23:41 -07006555 // reallocate buffer if needed
6556 if (mBufFrameSize != 0 && mBufFrames < frames) {
6557 free(mBuf);
6558 mBufFrames = frames;
6559 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
6560 }
Andy Hung97a893e2015-03-29 01:03:07 -07006561 // resampler accumulates, but we only have one source track
Andy Hungd330ee42015-04-20 13:23:41 -07006562 memset(mBuf, 0, frames * mBufFrameSize);
6563 frames = mResampler->resample((int32_t*)mBuf, frames, provider);
6564 // format convert to destination buffer
6565 convertResampler(dst, mBuf, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006566 }
6567 return frames;
6568}
6569
6570status_t AudioFlinger::RecordThread::RecordBufferConverter::updateParameters(
6571 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6572 uint32_t srcSampleRate,
6573 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6574 uint32_t dstSampleRate)
6575{
6576 // quick evaluation if there is any change.
6577 if (mSrcFormat == srcFormat
6578 && mSrcChannelMask == srcChannelMask
6579 && mSrcSampleRate == srcSampleRate
6580 && mDstFormat == dstFormat
6581 && mDstChannelMask == dstChannelMask
6582 && mDstSampleRate == dstSampleRate) {
6583 return NO_ERROR;
6584 }
6585
Andy Hungdb4c0312015-05-06 08:46:52 -07006586 ALOGV("RecordBufferConverter updateParameters srcMask:%#x dstMask:%#x"
6587 " srcFormat:%#x dstFormat:%#x srcRate:%u dstRate:%u",
6588 srcChannelMask, dstChannelMask, srcFormat, dstFormat, srcSampleRate, dstSampleRate);
Andy Hung97a893e2015-03-29 01:03:07 -07006589 const bool valid =
6590 audio_is_input_channel(srcChannelMask)
6591 && audio_is_input_channel(dstChannelMask)
6592 && audio_is_valid_format(srcFormat) && audio_is_linear_pcm(srcFormat)
6593 && audio_is_valid_format(dstFormat) && audio_is_linear_pcm(dstFormat)
6594 && (srcSampleRate <= dstSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX)
6595 ; // no upsampling checks for now
6596 if (!valid) {
6597 return BAD_VALUE;
6598 }
6599
6600 mSrcFormat = srcFormat;
6601 mSrcChannelMask = srcChannelMask;
6602 mSrcSampleRate = srcSampleRate;
6603 mDstFormat = dstFormat;
6604 mDstChannelMask = dstChannelMask;
6605 mDstSampleRate = dstSampleRate;
6606
6607 // compute derived parameters
6608 mSrcChannelCount = audio_channel_count_from_in_mask(srcChannelMask);
6609 mDstChannelCount = audio_channel_count_from_in_mask(dstChannelMask);
6610 mDstFrameSize = mDstChannelCount * audio_bytes_per_sample(mDstFormat);
6611
Andy Hungd330ee42015-04-20 13:23:41 -07006612 // do we need to resample?
6613 delete mResampler;
6614 mResampler = NULL;
6615 if (mSrcSampleRate != mDstSampleRate) {
6616 mResampler = AudioResampler::create(AUDIO_FORMAT_PCM_FLOAT,
6617 mSrcChannelCount, mDstSampleRate);
6618 mResampler->setSampleRate(mSrcSampleRate);
6619 mResampler->setVolume(AudioMixer::UNITY_GAIN_FLOAT, AudioMixer::UNITY_GAIN_FLOAT);
6620 }
6621
6622 // are we running legacy channel conversion modes?
6623 mIsLegacyDownmix = (mSrcChannelMask == AUDIO_CHANNEL_IN_STEREO
6624 || mSrcChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK)
6625 && mDstChannelMask == AUDIO_CHANNEL_IN_MONO;
6626 mIsLegacyUpmix = mSrcChannelMask == AUDIO_CHANNEL_IN_MONO
6627 && (mDstChannelMask == AUDIO_CHANNEL_IN_STEREO
6628 || mDstChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK);
6629
6630 // do we need to process in float?
6631 mRequiresFloat = mResampler != NULL || mIsLegacyDownmix || mIsLegacyUpmix;
6632
6633 // do we need a staging buffer to convert for destination (we can still optimize this)?
6634 // we use mBufFrameSize > 0 to indicate both frame size as well as buffer necessity
6635 if (mResampler != NULL) {
6636 mBufFrameSize = max(mSrcChannelCount, FCC_2)
6637 * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
6638 } else if ((mIsLegacyUpmix || mIsLegacyDownmix) && mDstFormat != AUDIO_FORMAT_PCM_FLOAT) {
6639 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
6640 } else if (mSrcChannelMask != mDstChannelMask && mDstFormat != mSrcFormat) {
Andy Hung97a893e2015-03-29 01:03:07 -07006641 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(mSrcFormat);
6642 } else {
6643 mBufFrameSize = 0;
6644 }
6645 mBufFrames = 0; // force the buffer to be resized.
6646
Andy Hungd330ee42015-04-20 13:23:41 -07006647 // do we need an input converter buffer provider to give us float?
6648 delete mInputConverterProvider;
6649 mInputConverterProvider = NULL;
6650 if (mRequiresFloat && mSrcFormat != AUDIO_FORMAT_PCM_FLOAT) {
6651 mInputConverterProvider = new ReformatBufferProvider(
6652 audio_channel_count_from_in_mask(mSrcChannelMask),
6653 mSrcFormat,
6654 AUDIO_FORMAT_PCM_FLOAT,
6655 256 /* provider buffer frame count */);
6656 }
6657
6658 // do we need a remixer to do channel mask conversion
6659 if (!mIsLegacyDownmix && !mIsLegacyUpmix && mSrcChannelMask != mDstChannelMask) {
6660 (void) memcpy_by_index_array_initialization_from_channel_mask(
6661 mIdxAry, ARRAY_SIZE(mIdxAry), mDstChannelMask, mSrcChannelMask);
Andy Hung97a893e2015-03-29 01:03:07 -07006662 }
6663 return NO_ERROR;
6664}
6665
Andy Hungd330ee42015-04-20 13:23:41 -07006666void AudioFlinger::RecordThread::RecordBufferConverter::convertNoResampler(
6667 void *dst, const void *src, size_t frames)
Andy Hung97a893e2015-03-29 01:03:07 -07006668{
Andy Hungd330ee42015-04-20 13:23:41 -07006669 // src is native type unless there is legacy upmix or downmix, whereupon it is float.
Andy Hung97a893e2015-03-29 01:03:07 -07006670 if (mBufFrameSize != 0 && mBufFrames < frames) {
6671 free(mBuf);
6672 mBufFrames = frames;
6673 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
6674 }
Andy Hungd330ee42015-04-20 13:23:41 -07006675 // do we need to do legacy upmix and downmix?
6676 if (mIsLegacyUpmix || mIsLegacyDownmix) {
Andy Hung97a893e2015-03-29 01:03:07 -07006677 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07006678 if (mIsLegacyUpmix) {
6679 upmix_to_stereo_float_from_mono_float((float *)dstBuf,
6680 (const float *)src, frames);
6681 } else /*mIsLegacyDownmix */ {
6682 downmix_to_mono_float_from_stereo_float((float *)dstBuf,
6683 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006684 }
Andy Hungd330ee42015-04-20 13:23:41 -07006685 if (mBuf != NULL) {
6686 memcpy_by_audio_format(dst, mDstFormat, mBuf, AUDIO_FORMAT_PCM_FLOAT,
6687 frames * mDstChannelCount);
6688 }
6689 return;
6690 }
6691 // do we need to do channel mask conversion?
6692 if (mSrcChannelMask != mDstChannelMask) {
Andy Hung97a893e2015-03-29 01:03:07 -07006693 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07006694 memcpy_by_index_array(dstBuf, mDstChannelCount,
6695 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mSrcFormat), frames);
6696 if (dstBuf == dst) {
6697 return; // format is the same
6698 }
6699 }
6700 // convert to destination buffer
6701 const void *convertBuf = mBuf != NULL ? mBuf : src;
6702 memcpy_by_audio_format(dst, mDstFormat, convertBuf, mSrcFormat,
6703 frames * mDstChannelCount);
6704}
6705
6706void AudioFlinger::RecordThread::RecordBufferConverter::convertResampler(
6707 void *dst, /*not-a-const*/ void *src, size_t frames)
6708{
6709 // src buffer format is ALWAYS float when entering this routine
6710 if (mIsLegacyUpmix) {
6711 ; // mono to stereo already handled by resampler
6712 } else if (mIsLegacyDownmix
6713 || (mSrcChannelMask == mDstChannelMask && mSrcChannelCount == 1)) {
6714 // the resampler outputs stereo for mono input channel (a feature?)
6715 // must convert to mono
6716 downmix_to_mono_float_from_stereo_float((float *)src,
6717 (const float *)src, frames);
6718 } else if (mSrcChannelMask != mDstChannelMask) {
6719 // convert to mono channel again for channel mask conversion (could be skipped
6720 // with further optimization).
Andy Hung97a893e2015-03-29 01:03:07 -07006721 if (mSrcChannelCount == 1) {
Andy Hungd330ee42015-04-20 13:23:41 -07006722 downmix_to_mono_float_from_stereo_float((float *)src,
6723 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006724 }
Andy Hungd330ee42015-04-20 13:23:41 -07006725 // convert to destination format (in place, OK as float is larger than other types)
6726 if (mDstFormat != AUDIO_FORMAT_PCM_FLOAT) {
6727 memcpy_by_audio_format(src, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
6728 frames * mSrcChannelCount);
6729 }
6730 // channel convert and save to dst
6731 memcpy_by_index_array(dst, mDstChannelCount,
6732 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mDstFormat), frames);
6733 return;
Andy Hung97a893e2015-03-29 01:03:07 -07006734 }
Andy Hungd330ee42015-04-20 13:23:41 -07006735 // convert to destination format and save to dst
6736 memcpy_by_audio_format(dst, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
6737 frames * mDstChannelCount);
Andy Hung97a893e2015-03-29 01:03:07 -07006738}
6739
Eric Laurent10351942014-05-08 18:49:52 -07006740bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
6741 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006742{
6743 bool reconfig = false;
6744
Eric Laurent10351942014-05-08 18:49:52 -07006745 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006746
Eric Laurent10351942014-05-08 18:49:52 -07006747 audio_format_t reqFormat = mFormat;
6748 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07006749 // 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 -07006750 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
6751
6752 AudioParameter param = AudioParameter(keyValuePair);
6753 int value;
6754 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
6755 // channel count change can be requested. Do we mandate the first client defines the
6756 // HAL sampling rate and channel count or do we allow changes on the fly?
6757 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6758 samplingRate = value;
6759 reconfig = true;
6760 }
6761 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07006762 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07006763 status = BAD_VALUE;
6764 } else {
6765 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08006766 reconfig = true;
6767 }
Eric Laurent10351942014-05-08 18:49:52 -07006768 }
6769 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
6770 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07006771 if (!audio_is_input_channel(mask) ||
6772 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07006773 status = BAD_VALUE;
6774 } else {
6775 channelMask = mask;
6776 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006777 }
Eric Laurent10351942014-05-08 18:49:52 -07006778 }
6779 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6780 // do not accept frame count changes if tracks are open as the track buffer
6781 // size depends on frame count and correct behavior would not be guaranteed
6782 // if frame count is changed after track creation
6783 if (mActiveTracks.size() > 0) {
6784 status = INVALID_OPERATION;
6785 } else {
6786 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006787 }
Eric Laurent10351942014-05-08 18:49:52 -07006788 }
6789 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6790 // forward device change to effects that have requested to be
6791 // aware of attached audio device.
6792 for (size_t i = 0; i < mEffectChains.size(); i++) {
6793 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08006794 }
Eric Laurent81784c32012-11-19 14:55:58 -08006795
Eric Laurent10351942014-05-08 18:49:52 -07006796 // store input device and output device but do not forward output device to audio HAL.
6797 // Note that status is ignored by the caller for output device
6798 // (see AudioFlinger::setParameters()
6799 if (audio_is_output_devices(value)) {
6800 mOutDevice = value;
6801 status = BAD_VALUE;
6802 } else {
6803 mInDevice = value;
Eric Laurente8726fe2015-06-26 09:39:24 -07006804 if (value != AUDIO_DEVICE_NONE) {
6805 mPrevInDevice = value;
6806 }
Eric Laurent10351942014-05-08 18:49:52 -07006807 // disable AEC and NS if the device is a BT SCO headset supporting those
6808 // pre processings
6809 if (mTracks.size() > 0) {
6810 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6811 mAudioFlinger->btNrecIsOff();
6812 for (size_t i = 0; i < mTracks.size(); i++) {
6813 sp<RecordTrack> track = mTracks[i];
6814 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
6815 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08006816 }
6817 }
6818 }
Eric Laurent10351942014-05-08 18:49:52 -07006819 }
6820 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
6821 mAudioSource != (audio_source_t)value) {
6822 // forward device change to effects that have requested to be
6823 // aware of attached audio device.
6824 for (size_t i = 0; i < mEffectChains.size(); i++) {
6825 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08006826 }
Eric Laurent10351942014-05-08 18:49:52 -07006827 mAudioSource = (audio_source_t)value;
6828 }
Glenn Kastene198c362013-08-13 09:13:36 -07006829
Eric Laurent10351942014-05-08 18:49:52 -07006830 if (status == NO_ERROR) {
6831 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6832 keyValuePair.string());
6833 if (status == INVALID_OPERATION) {
6834 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006835 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6836 keyValuePair.string());
Eric Laurent10351942014-05-08 18:49:52 -07006837 }
6838 if (reconfig) {
6839 if (status == BAD_VALUE &&
Andy Hung97a893e2015-03-29 01:03:07 -07006840 audio_is_linear_pcm(mInput->stream->common.get_format(&mInput->stream->common)) &&
6841 audio_is_linear_pcm(reqFormat) &&
Eric Laurent10351942014-05-08 18:49:52 -07006842 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
Andy Hung97a893e2015-03-29 01:03:07 -07006843 <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate)) &&
Andy Hunge5412692014-05-16 11:25:07 -07006844 audio_channel_count_from_in_mask(
Andy Hungd1abb8f2015-05-05 23:42:34 -07006845 mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07006846 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006847 }
Eric Laurent10351942014-05-08 18:49:52 -07006848 if (status == NO_ERROR) {
6849 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07006850 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08006851 }
6852 }
Eric Laurent81784c32012-11-19 14:55:58 -08006853 }
Eric Laurent10351942014-05-08 18:49:52 -07006854
Eric Laurent81784c32012-11-19 14:55:58 -08006855 return reconfig;
6856}
6857
6858String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6859{
Eric Laurent81784c32012-11-19 14:55:58 -08006860 Mutex::Autolock _l(mLock);
6861 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07006862 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08006863 }
6864
Glenn Kastend8ea6992013-07-16 14:17:15 -07006865 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
6866 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08006867 free(s);
6868 return out_s8;
6869}
6870
Eric Laurent73e26b62015-04-27 16:55:58 -07006871void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event) {
6872 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
6873
6874 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08006875
6876 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07006877 case AUDIO_INPUT_OPENED:
6878 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07006879 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07006880 desc->mChannelMask = mChannelMask;
6881 desc->mSamplingRate = mSampleRate;
6882 desc->mFormat = mFormat;
6883 desc->mFrameCount = mFrameCount;
6884 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006885 break;
6886
Eric Laurent73e26b62015-04-27 16:55:58 -07006887 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08006888 default:
6889 break;
6890 }
Eric Laurent73e26b62015-04-27 16:55:58 -07006891 mAudioFlinger->ioConfigChanged(event, desc);
Eric Laurent81784c32012-11-19 14:55:58 -08006892}
6893
Glenn Kastendeca2ae2014-02-07 10:25:56 -08006894void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006895{
Eric Laurent81784c32012-11-19 14:55:58 -08006896 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
6897 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Andy Hunge5412692014-05-16 11:25:07 -07006898 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Andy Hungd330ee42015-04-20 13:23:41 -07006899 if (mChannelCount > FCC_8) {
6900 ALOGE("HAL channel count %d > %d", mChannelCount, FCC_8);
6901 }
Andy Hung463be252014-07-10 16:56:07 -07006902 mHALFormat = mInput->stream->common.get_format(&mInput->stream->common);
6903 mFormat = mHALFormat;
Andy Hungd330ee42015-04-20 13:23:41 -07006904 if (!audio_is_linear_pcm(mFormat)) {
6905 ALOGE("HAL format %#x is not linear pcm", mFormat);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07006906 }
Eric Laurent665470b2014-07-03 16:37:08 -07006907 mFrameSize = audio_stream_in_frame_size(mInput->stream);
Glenn Kasten548efc92012-11-29 08:48:51 -08006908 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
6909 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006910 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08006911 // 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 -07006912 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08006913 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006914 // A larger value should allow more old data to be read after a track calls start(),
6915 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07006916 //
6917 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08006918 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07006919 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07006920 free(mRsmpInBuffer);
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006921
6922 // TODO optimize audio capture buffer sizes ...
6923 // Here we calculate the size of the sliding buffer used as a source
6924 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
6925 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
6926 // be better to have it derived from the pipe depth in the long term.
6927 // The current value is higher than necessary. However it should not add to latency.
6928
Glenn Kasten85948432013-08-19 12:09:05 -07006929 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Andy Hung57446612015-04-19 23:56:46 -07006930 (void)posix_memalign(&mRsmpInBuffer, 32, (mRsmpInFramesP2 + mFrameCount - 1) * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006931
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006932 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
6933 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08006934}
6935
Glenn Kasten5f972c02014-01-13 09:59:31 -08006936uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08006937{
6938 Mutex::Autolock _l(mLock);
6939 if (initCheck() != NO_ERROR) {
6940 return 0;
6941 }
6942
6943 return mInput->stream->get_input_frames_lost(mInput->stream);
6944}
6945
6946uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
6947{
6948 Mutex::Autolock _l(mLock);
6949 uint32_t result = 0;
6950 if (getEffectChain_l(sessionId) != 0) {
6951 result = EFFECT_SESSION;
6952 }
6953
6954 for (size_t i = 0; i < mTracks.size(); ++i) {
6955 if (sessionId == mTracks[i]->sessionId()) {
6956 result |= TRACK_SESSION;
6957 break;
6958 }
6959 }
6960
6961 return result;
6962}
6963
6964KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
6965{
6966 KeyedVector<int, bool> ids;
6967 Mutex::Autolock _l(mLock);
6968 for (size_t j = 0; j < mTracks.size(); ++j) {
6969 sp<RecordThread::RecordTrack> track = mTracks[j];
6970 int sessionId = track->sessionId();
6971 if (ids.indexOfKey(sessionId) < 0) {
6972 ids.add(sessionId, true);
6973 }
6974 }
6975 return ids;
6976}
6977
6978AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
6979{
6980 Mutex::Autolock _l(mLock);
6981 AudioStreamIn *input = mInput;
6982 mInput = NULL;
6983 return input;
6984}
6985
6986// this method must always be called either with ThreadBase mLock held or inside the thread loop
6987audio_stream_t* AudioFlinger::RecordThread::stream() const
6988{
6989 if (mInput == NULL) {
6990 return NULL;
6991 }
6992 return &mInput->stream->common;
6993}
6994
6995status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6996{
6997 // only one chain per input thread
6998 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07006999 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08007000 return INVALID_OPERATION;
7001 }
7002 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07007003 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08007004 chain->setInBuffer(NULL);
7005 chain->setOutBuffer(NULL);
7006
7007 checkSuspendOnAddEffectChain_l(chain);
7008
Eric Laurent1b928682014-10-02 19:41:47 -07007009 // make sure enabled pre processing effects state is communicated to the HAL as we
7010 // just moved them to a new input stream.
7011 chain->syncHalEffectsState();
7012
Eric Laurent81784c32012-11-19 14:55:58 -08007013 mEffectChains.add(chain);
7014
7015 return NO_ERROR;
7016}
7017
7018size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7019{
7020 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
7021 ALOGW_IF(mEffectChains.size() != 1,
7022 "removeEffectChain_l() %p invalid chain size %d on thread %p",
7023 chain.get(), mEffectChains.size(), this);
7024 if (mEffectChains.size() == 1) {
7025 mEffectChains.removeAt(0);
7026 }
7027 return 0;
7028}
7029
Eric Laurent1c333e22014-05-20 10:48:17 -07007030status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
7031 audio_patch_handle_t *handle)
7032{
7033 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007034
7035 // store new device and send to effects
7036 mInDevice = patch->sources[0].ext.device.type;
Eric Laurent296fb132015-05-01 11:38:42 -07007037 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07007038 for (size_t i = 0; i < mEffectChains.size(); i++) {
7039 mEffectChains[i]->setDevice_l(mInDevice);
7040 }
7041
7042 // disable AEC and NS if the device is a BT SCO headset supporting those
7043 // pre processings
7044 if (mTracks.size() > 0) {
7045 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7046 mAudioFlinger->btNrecIsOff();
7047 for (size_t i = 0; i < mTracks.size(); i++) {
7048 sp<RecordTrack> track = mTracks[i];
7049 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7050 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
7051 }
7052 }
7053
7054 // store new source and send to effects
7055 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7056 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07007057 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07007058 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07007059 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007060 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007061
Eric Laurent054d9d32015-04-24 08:48:48 -07007062 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007063 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
7064 status = hwDevice->create_audio_patch(hwDevice,
7065 patch->num_sources,
7066 patch->sources,
7067 patch->num_sinks,
7068 patch->sinks,
7069 handle);
7070 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007071 char *address;
7072 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
7073 address = audio_device_address_to_parameter(
7074 patch->sources[0].ext.device.type,
7075 patch->sources[0].ext.device.address);
7076 } else {
7077 address = (char *)calloc(1, 1);
7078 }
7079 AudioParameter param = AudioParameter(String8(address));
7080 free(address);
7081 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING),
7082 (int)patch->sources[0].ext.device.type);
7083 param.addInt(String8(AUDIO_PARAMETER_STREAM_INPUT_SOURCE),
7084 (int)patch->sinks[0].ext.mix.usecase.source);
7085 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7086 param.toString().string());
7087 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07007088 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007089
Eric Laurente8726fe2015-06-26 09:39:24 -07007090 if (mInDevice != mPrevInDevice) {
7091 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
7092 mPrevInDevice = mInDevice;
7093 }
Eric Laurent296fb132015-05-01 11:38:42 -07007094
Eric Laurent1c333e22014-05-20 10:48:17 -07007095 return status;
7096}
7097
7098status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
7099{
7100 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007101
7102 mInDevice = AUDIO_DEVICE_NONE;
7103
Eric Laurent1c333e22014-05-20 10:48:17 -07007104 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
7105 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
7106 status = hwDevice->release_audio_patch(hwDevice, handle);
7107 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007108 AudioParameter param;
7109 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
7110 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7111 param.toString().string());
Eric Laurent1c333e22014-05-20 10:48:17 -07007112 }
7113 return status;
7114}
7115
Eric Laurent83b88082014-06-20 18:31:16 -07007116void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
7117{
7118 Mutex::Autolock _l(mLock);
7119 mTracks.add(record);
7120}
7121
7122void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
7123{
7124 Mutex::Autolock _l(mLock);
7125 destroyTrack_l(record);
7126}
7127
7128void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
7129{
7130 ThreadBase::getAudioPortConfig(config);
7131 config->role = AUDIO_PORT_ROLE_SINK;
7132 config->ext.mix.hw_module = mInput->audioHwDev->handle();
7133 config->ext.mix.usecase.source = mAudioSource;
7134}
Eric Laurent1c333e22014-05-20 10:48:17 -07007135
Glenn Kasten63238ef2015-03-02 15:50:29 -08007136} // namespace android