blob: e32c984ece3b9843dfd5a5bbe11db370cbf3b5bd [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
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700128// FIXME This should be based on experimentally observed scheduling jitter
Andy Hung09a50072014-02-27 14:30:47 -0800129static const uint32_t kMinNormalSinkBufferSizeMs = 20;
130// maximum normal sink buffer size
131static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800132
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700133// minimum capture buffer size in milliseconds to _not_ need a fast capture thread
134// FIXME This should be based on experimentally observed scheduling jitter
135static const uint32_t kMinNormalCaptureBufferSizeMs = 12;
136
Eric Laurent972a1732013-09-04 09:42:59 -0700137// Offloaded output thread standby delay: allows track transition without going to standby
138static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
139
Eric Laurent81784c32012-11-19 14:55:58 -0800140// Whether to use fast mixer
141static const enum {
142 FastMixer_Never, // never initialize or use: for debugging only
143 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
144 // normal mixer multiplier is 1
145 FastMixer_Static, // initialize if needed, then use all the time if initialized,
146 // multiplier is calculated based on min & max normal mixer buffer size
147 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
148 // multiplier is calculated based on min & max normal mixer buffer size
149 // FIXME for FastMixer_Dynamic:
150 // Supporting this option will require fixing HALs that can't handle large writes.
151 // For example, one HAL implementation returns an error from a large write,
152 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
153 // We could either fix the HAL implementations, or provide a wrapper that breaks
154 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
155} kUseFastMixer = FastMixer_Static;
156
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700157// Whether to use fast capture
158static const enum {
159 FastCapture_Never, // never initialize or use: for debugging only
160 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
161 FastCapture_Static, // initialize if needed, then use all the time if initialized
162} kUseFastCapture = FastCapture_Static;
163
Eric Laurent81784c32012-11-19 14:55:58 -0800164// Priorities for requestPriority
165static const int kPriorityAudioApp = 2;
166static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700167static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800168
169// IAudioFlinger::createTrack() reports back to client the total size of shared memory area
170// for the track. The client then sub-divides this into smaller buffers for its use.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800171// Currently the client uses N-buffering by default, but doesn't tell us about the value of N.
172// So for now we just assume that client is double-buffered for fast tracks.
173// FIXME It would be better for client to tell AudioFlinger the value of N,
174// so AudioFlinger could allocate the right amount of memory.
Eric Laurent81784c32012-11-19 14:55:58 -0800175// See the client's minBufCount and mNotificationFramesAct calculations for details.
Glenn Kasten03490092014-05-27 12:30:54 -0700176
177// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800178static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800179
Glenn Kasten03490092014-05-27 12:30:54 -0700180// The minimum and maximum allowed values
181static const int kFastTrackMultiplierMin = 1;
182static const int kFastTrackMultiplierMax = 2;
183
184// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
185static int sFastTrackMultiplier = kFastTrackMultiplier;
186
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700187// See Thread::readOnlyHeap().
188// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
189// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
190// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Glenn Kasten9f81de32014-07-27 15:02:23 -0700191static const size_t kRecordThreadReadOnlyHeapSize = 0x2000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700192
Eric Laurent81784c32012-11-19 14:55:58 -0800193// ----------------------------------------------------------------------------
194
Glenn Kasten03490092014-05-27 12:30:54 -0700195static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
196
197static void sFastTrackMultiplierInit()
198{
199 char value[PROPERTY_VALUE_MAX];
200 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
201 char *endptr;
202 unsigned long ul = strtoul(value, &endptr, 0);
203 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
204 sFastTrackMultiplier = (int) ul;
205 }
206 }
207}
208
209// ----------------------------------------------------------------------------
210
Eric Laurent81784c32012-11-19 14:55:58 -0800211#ifdef ADD_BATTERY_DATA
212// To collect the amplifier usage
213static void addBatteryData(uint32_t params) {
214 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
215 if (service == NULL) {
216 // it already logged
217 return;
218 }
219
220 service->addBatteryData(params);
221}
222#endif
223
224
225// ----------------------------------------------------------------------------
226// CPU Stats
227// ----------------------------------------------------------------------------
228
229class CpuStats {
230public:
231 CpuStats();
232 void sample(const String8 &title);
233#ifdef DEBUG_CPU_USAGE
234private:
235 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
236 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
237
238 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
239
240 int mCpuNum; // thread's current CPU number
241 int mCpukHz; // frequency of thread's current CPU in kHz
242#endif
243};
244
245CpuStats::CpuStats()
246#ifdef DEBUG_CPU_USAGE
247 : mCpuNum(-1), mCpukHz(-1)
248#endif
249{
250}
251
Glenn Kasten0f11b512014-01-31 16:18:54 -0800252void CpuStats::sample(const String8 &title
253#ifndef DEBUG_CPU_USAGE
254 __unused
255#endif
256 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800257#ifdef DEBUG_CPU_USAGE
258 // get current thread's delta CPU time in wall clock ns
259 double wcNs;
260 bool valid = mCpuUsage.sampleAndEnable(wcNs);
261
262 // record sample for wall clock statistics
263 if (valid) {
264 mWcStats.sample(wcNs);
265 }
266
267 // get the current CPU number
268 int cpuNum = sched_getcpu();
269
270 // get the current CPU frequency in kHz
271 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
272
273 // check if either CPU number or frequency changed
274 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
275 mCpuNum = cpuNum;
276 mCpukHz = cpukHz;
277 // ignore sample for purposes of cycles
278 valid = false;
279 }
280
281 // if no change in CPU number or frequency, then record sample for cycle statistics
282 if (valid && mCpukHz > 0) {
283 double cycles = wcNs * cpukHz * 0.000001;
284 mHzStats.sample(cycles);
285 }
286
287 unsigned n = mWcStats.n();
288 // mCpuUsage.elapsed() is expensive, so don't call it every loop
289 if ((n & 127) == 1) {
290 long long elapsed = mCpuUsage.elapsed();
291 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
292 double perLoop = elapsed / (double) n;
293 double perLoop100 = perLoop * 0.01;
294 double perLoop1k = perLoop * 0.001;
295 double mean = mWcStats.mean();
296 double stddev = mWcStats.stddev();
297 double minimum = mWcStats.minimum();
298 double maximum = mWcStats.maximum();
299 double meanCycles = mHzStats.mean();
300 double stddevCycles = mHzStats.stddev();
301 double minCycles = mHzStats.minimum();
302 double maxCycles = mHzStats.maximum();
303 mCpuUsage.resetElapsed();
304 mWcStats.reset();
305 mHzStats.reset();
306 ALOGD("CPU usage for %s over past %.1f secs\n"
307 " (%u mixer loops at %.1f mean ms per loop):\n"
308 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
309 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
310 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
311 title.string(),
312 elapsed * .000000001, n, perLoop * .000001,
313 mean * .001,
314 stddev * .001,
315 minimum * .001,
316 maximum * .001,
317 mean / perLoop100,
318 stddev / perLoop100,
319 minimum / perLoop100,
320 maximum / perLoop100,
321 meanCycles / perLoop1k,
322 stddevCycles / perLoop1k,
323 minCycles / perLoop1k,
324 maxCycles / perLoop1k);
325
326 }
327 }
328#endif
329};
330
331// ----------------------------------------------------------------------------
332// ThreadBase
333// ----------------------------------------------------------------------------
334
Glenn Kasten97b7b752014-09-28 13:04:24 -0700335// static
336const char *AudioFlinger::ThreadBase::threadTypeToString(AudioFlinger::ThreadBase::type_t type)
337{
338 switch (type) {
339 case MIXER:
340 return "MIXER";
341 case DIRECT:
342 return "DIRECT";
343 case DUPLICATING:
344 return "DUPLICATING";
345 case RECORD:
346 return "RECORD";
347 case OFFLOAD:
348 return "OFFLOAD";
349 default:
350 return "unknown";
351 }
352}
353
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800354String8 devicesToString(audio_devices_t devices)
355{
356 static const struct mapping {
357 audio_devices_t mDevices;
358 const char * mString;
359 } mappingsOut[] = {
360 AUDIO_DEVICE_OUT_EARPIECE, "EARPIECE",
361 AUDIO_DEVICE_OUT_SPEAKER, "SPEAKER",
362 AUDIO_DEVICE_OUT_WIRED_HEADSET, "WIRED_HEADSET",
363 AUDIO_DEVICE_OUT_WIRED_HEADPHONE, "WIRED_HEADPHONE",
Glenn Kasten84d61ca2015-05-06 18:32:13 -0700364 AUDIO_DEVICE_OUT_BLUETOOTH_SCO, "BLUETOOTH_SCO",
365 AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET, "BLUETOOTH_SCO_HEADSET",
366 AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT, "BLUETOOTH_SCO_CARKIT",
367 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, "BLUETOOTH_A2DP",
368 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES, "BLUETOOTH_A2DP_HEADPHONES",
369 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER, "BLUETOOTH_A2DP_SPEAKER",
370 AUDIO_DEVICE_OUT_AUX_DIGITAL, "AUX_DIGITAL",
371 AUDIO_DEVICE_OUT_HDMI, "HDMI",
372 AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET, "ANLG_DOCK_HEADSET",
373 AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET, "DGTL_DOCK_HEADSET",
374 AUDIO_DEVICE_OUT_USB_ACCESSORY, "USB_ACCESSORY",
375 AUDIO_DEVICE_OUT_USB_DEVICE, "USB_DEVICE",
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800376 AUDIO_DEVICE_OUT_TELEPHONY_TX, "TELEPHONY_TX",
Glenn Kasten84d61ca2015-05-06 18:32:13 -0700377 AUDIO_DEVICE_OUT_LINE, "LINE",
378 AUDIO_DEVICE_OUT_HDMI_ARC, "HDMI_ARC",
379 AUDIO_DEVICE_OUT_SPDIF, "SPDIF",
380 AUDIO_DEVICE_OUT_FM, "FM",
381 AUDIO_DEVICE_OUT_AUX_LINE, "AUX_LINE",
382 AUDIO_DEVICE_OUT_SPEAKER_SAFE, "SPEAKER_SAFE",
Eric Laurentb9d73332015-06-30 17:09:20 -0700383 AUDIO_DEVICE_OUT_IP, "IP",
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800384 AUDIO_DEVICE_NONE, "NONE", // must be last
385 }, mappingsIn[] = {
Glenn Kasten84d61ca2015-05-06 18:32:13 -0700386 AUDIO_DEVICE_IN_COMMUNICATION, "COMMUNICATION",
387 AUDIO_DEVICE_IN_AMBIENT, "AMBIENT",
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800388 AUDIO_DEVICE_IN_BUILTIN_MIC, "BUILTIN_MIC",
Glenn Kasten84d61ca2015-05-06 18:32:13 -0700389 AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET, "BLUETOOTH_SCO_HEADSET",
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800390 AUDIO_DEVICE_IN_WIRED_HEADSET, "WIRED_HEADSET",
Glenn Kasten84d61ca2015-05-06 18:32:13 -0700391 AUDIO_DEVICE_IN_AUX_DIGITAL, "AUX_DIGITAL",
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800392 AUDIO_DEVICE_IN_VOICE_CALL, "VOICE_CALL",
Glenn Kasten84d61ca2015-05-06 18:32:13 -0700393 AUDIO_DEVICE_IN_TELEPHONY_RX, "TELEPHONY_RX",
394 AUDIO_DEVICE_IN_BACK_MIC, "BACK_MIC",
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800395 AUDIO_DEVICE_IN_REMOTE_SUBMIX, "REMOTE_SUBMIX",
Glenn Kasten84d61ca2015-05-06 18:32:13 -0700396 AUDIO_DEVICE_IN_ANLG_DOCK_HEADSET, "ANLG_DOCK_HEADSET",
397 AUDIO_DEVICE_IN_DGTL_DOCK_HEADSET, "DGTL_DOCK_HEADSET",
398 AUDIO_DEVICE_IN_USB_ACCESSORY, "USB_ACCESSORY",
399 AUDIO_DEVICE_IN_USB_DEVICE, "USB_DEVICE",
400 AUDIO_DEVICE_IN_FM_TUNER, "FM_TUNER",
401 AUDIO_DEVICE_IN_TV_TUNER, "TV_TUNER",
402 AUDIO_DEVICE_IN_LINE, "LINE",
403 AUDIO_DEVICE_IN_SPDIF, "SPDIF",
404 AUDIO_DEVICE_IN_BLUETOOTH_A2DP, "BLUETOOTH_A2DP",
405 AUDIO_DEVICE_IN_LOOPBACK, "LOOPBACK",
Eric Laurentb9d73332015-06-30 17:09:20 -0700406 AUDIO_DEVICE_IN_IP, "IP",
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800407 AUDIO_DEVICE_NONE, "NONE", // must be last
408 };
409 String8 result;
410 audio_devices_t allDevices = AUDIO_DEVICE_NONE;
411 const mapping *entry;
412 if (devices & AUDIO_DEVICE_BIT_IN) {
413 devices &= ~AUDIO_DEVICE_BIT_IN;
414 entry = mappingsIn;
415 } else {
416 entry = mappingsOut;
417 }
418 for ( ; entry->mDevices != AUDIO_DEVICE_NONE; entry++) {
419 allDevices = (audio_devices_t) (allDevices | entry->mDevices);
420 if (devices & entry->mDevices) {
421 if (!result.isEmpty()) {
422 result.append("|");
423 }
424 result.append(entry->mString);
425 }
426 }
427 if (devices & ~allDevices) {
428 if (!result.isEmpty()) {
429 result.append("|");
430 }
431 result.appendFormat("0x%X", devices & ~allDevices);
432 }
433 if (result.isEmpty()) {
434 result.append(entry->mString);
435 }
436 return result;
437}
438
439String8 inputFlagsToString(audio_input_flags_t flags)
440{
441 static const struct mapping {
442 audio_input_flags_t mFlag;
443 const char * mString;
444 } mappings[] = {
445 AUDIO_INPUT_FLAG_FAST, "FAST",
446 AUDIO_INPUT_FLAG_HW_HOTWORD, "HW_HOTWORD",
Glenn Kasten937c3472015-09-28 10:21:06 -0700447 AUDIO_INPUT_FLAG_RAW, "RAW",
448 AUDIO_INPUT_FLAG_SYNC, "SYNC",
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800449 AUDIO_INPUT_FLAG_NONE, "NONE", // must be last
450 };
451 String8 result;
452 audio_input_flags_t allFlags = AUDIO_INPUT_FLAG_NONE;
453 const mapping *entry;
454 for (entry = mappings; entry->mFlag != AUDIO_INPUT_FLAG_NONE; entry++) {
455 allFlags = (audio_input_flags_t) (allFlags | entry->mFlag);
456 if (flags & entry->mFlag) {
457 if (!result.isEmpty()) {
458 result.append("|");
459 }
460 result.append(entry->mString);
461 }
462 }
463 if (flags & ~allFlags) {
464 if (!result.isEmpty()) {
465 result.append("|");
466 }
467 result.appendFormat("0x%X", flags & ~allFlags);
468 }
469 if (result.isEmpty()) {
470 result.append(entry->mString);
471 }
472 return result;
473}
474
475String8 outputFlagsToString(audio_output_flags_t flags)
Glenn Kasten97b7b752014-09-28 13:04:24 -0700476{
477 static const struct mapping {
478 audio_output_flags_t mFlag;
479 const char * mString;
480 } mappings[] = {
481 AUDIO_OUTPUT_FLAG_DIRECT, "DIRECT",
482 AUDIO_OUTPUT_FLAG_PRIMARY, "PRIMARY",
483 AUDIO_OUTPUT_FLAG_FAST, "FAST",
484 AUDIO_OUTPUT_FLAG_DEEP_BUFFER, "DEEP_BUFFER",
Glenn Kastendfb0e112015-02-18 14:33:39 -0800485 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD, "COMPRESS_OFFLOAD",
Glenn Kasten97b7b752014-09-28 13:04:24 -0700486 AUDIO_OUTPUT_FLAG_NON_BLOCKING, "NON_BLOCKING",
487 AUDIO_OUTPUT_FLAG_HW_AV_SYNC, "HW_AV_SYNC",
Glenn Kasten937c3472015-09-28 10:21:06 -0700488 AUDIO_OUTPUT_FLAG_RAW, "RAW",
489 AUDIO_OUTPUT_FLAG_SYNC, "SYNC",
490 AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO, "IEC958_NONAUDIO",
Glenn Kasten97b7b752014-09-28 13:04:24 -0700491 AUDIO_OUTPUT_FLAG_NONE, "NONE", // must be last
492 };
493 String8 result;
494 audio_output_flags_t allFlags = AUDIO_OUTPUT_FLAG_NONE;
495 const mapping *entry;
496 for (entry = mappings; entry->mFlag != AUDIO_OUTPUT_FLAG_NONE; entry++) {
497 allFlags = (audio_output_flags_t) (allFlags | entry->mFlag);
498 if (flags & entry->mFlag) {
499 if (!result.isEmpty()) {
500 result.append("|");
501 }
502 result.append(entry->mString);
503 }
504 }
505 if (flags & ~allFlags) {
506 if (!result.isEmpty()) {
507 result.append("|");
508 }
509 result.appendFormat("0x%X", flags & ~allFlags);
510 }
511 if (result.isEmpty()) {
512 result.append(entry->mString);
513 }
514 return result;
515}
516
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800517const char *sourceToString(audio_source_t source)
518{
519 switch (source) {
520 case AUDIO_SOURCE_DEFAULT: return "default";
521 case AUDIO_SOURCE_MIC: return "mic";
522 case AUDIO_SOURCE_VOICE_UPLINK: return "voice uplink";
523 case AUDIO_SOURCE_VOICE_DOWNLINK: return "voice downlink";
524 case AUDIO_SOURCE_VOICE_CALL: return "voice call";
525 case AUDIO_SOURCE_CAMCORDER: return "camcorder";
526 case AUDIO_SOURCE_VOICE_RECOGNITION: return "voice recognition";
527 case AUDIO_SOURCE_VOICE_COMMUNICATION: return "voice communication";
528 case AUDIO_SOURCE_REMOTE_SUBMIX: return "remote submix";
529 case AUDIO_SOURCE_FM_TUNER: return "FM tuner";
530 case AUDIO_SOURCE_HOTWORD: return "hotword";
531 default: return "unknown";
532 }
533}
534
Eric Laurent81784c32012-11-19 14:55:58 -0800535AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -0700536 audio_devices_t outDevice, audio_devices_t inDevice, type_t type, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -0800537 : Thread(false /*canCallJava*/),
538 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700539 mAudioFlinger(audioFlinger),
Glenn Kasten70949c42013-08-06 07:40:12 -0700540 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800541 // are set by PlaybackThread::readOutputParameters_l() or
542 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700543 //FIXME: mStandby should be true here. Is this some kind of hack?
Eric Laurent81784c32012-11-19 14:55:58 -0800544 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700545 mPrevOutDevice(AUDIO_DEVICE_NONE), mPrevInDevice(AUDIO_DEVICE_NONE),
546 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Eric Laurent81784c32012-11-19 14:55:58 -0800547 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700548 mDeathRecipient(new PMDeathRecipient(this)),
549 mSystemReady(systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -0800550{
Eric Laurent296fb132015-05-01 11:38:42 -0700551 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800552}
553
554AudioFlinger::ThreadBase::~ThreadBase()
555{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700556 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700557 mConfigEvents.clear();
558
Eric Laurent81784c32012-11-19 14:55:58 -0800559 // do not lock the mutex in destructor
560 releaseWakeLock_l();
561 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800562 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800563 binder->unlinkToDeath(mDeathRecipient);
564 }
565}
566
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700567status_t AudioFlinger::ThreadBase::readyToRun()
568{
569 status_t status = initCheck();
570 if (status == NO_ERROR) {
571 ALOGI("AudioFlinger's thread %p ready to run", this);
572 } else {
573 ALOGE("No working audio driver found.");
574 }
575 return status;
576}
577
Eric Laurent81784c32012-11-19 14:55:58 -0800578void AudioFlinger::ThreadBase::exit()
579{
580 ALOGV("ThreadBase::exit");
581 // do any cleanup required for exit to succeed
582 preExit();
583 {
584 // This lock prevents the following race in thread (uniprocessor for illustration):
585 // if (!exitPending()) {
586 // // context switch from here to exit()
587 // // exit() calls requestExit(), what exitPending() observes
588 // // exit() calls signal(), which is dropped since no waiters
589 // // context switch back from exit() to here
590 // mWaitWorkCV.wait(...);
591 // // now thread is hung
592 // }
593 AutoMutex lock(mLock);
594 requestExit();
595 mWaitWorkCV.broadcast();
596 }
597 // When Thread::requestExitAndWait is made virtual and this method is renamed to
598 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
599 requestExitAndWait();
600}
601
602status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
603{
604 status_t status;
605
606 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
607 Mutex::Autolock _l(mLock);
608
Eric Laurent10351942014-05-08 18:49:52 -0700609 return sendSetParameterConfigEvent_l(keyValuePairs);
610}
611
612// sendConfigEvent_l() must be called with ThreadBase::mLock held
613// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
614status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
615{
616 status_t status = NO_ERROR;
617
Eric Laurent72e3f392015-05-20 14:43:50 -0700618 if (event->mRequiresSystemReady && !mSystemReady) {
619 event->mWaitStatus = false;
620 mPendingConfigEvents.add(event);
621 return status;
622 }
Eric Laurent10351942014-05-08 18:49:52 -0700623 mConfigEvents.add(event);
624 ALOGV("sendConfigEvent_l() num events %d event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800625 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700626 mLock.unlock();
627 {
628 Mutex::Autolock _l(event->mLock);
629 while (event->mWaitStatus) {
630 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
631 event->mStatus = TIMED_OUT;
632 event->mWaitStatus = false;
633 }
634 }
635 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800636 }
Eric Laurent10351942014-05-08 18:49:52 -0700637 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800638 return status;
639}
640
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700641void AudioFlinger::ThreadBase::sendIoConfigEvent(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800642{
643 Mutex::Autolock _l(mLock);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700644 sendIoConfigEvent_l(event, pid);
Eric Laurent81784c32012-11-19 14:55:58 -0800645}
646
647// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700648void AudioFlinger::ThreadBase::sendIoConfigEvent_l(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800649{
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700650 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid);
Eric Laurent10351942014-05-08 18:49:52 -0700651 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800652}
653
Eric Laurent72e3f392015-05-20 14:43:50 -0700654void AudioFlinger::ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio)
655{
656 Mutex::Autolock _l(mLock);
657 sendPrioConfigEvent_l(pid, tid, prio);
658}
659
Eric Laurent81784c32012-11-19 14:55:58 -0800660// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
661void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
662{
Eric Laurent10351942014-05-08 18:49:52 -0700663 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio);
664 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800665}
666
Eric Laurent10351942014-05-08 18:49:52 -0700667// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
668status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800669{
Eric Laurent10351942014-05-08 18:49:52 -0700670 sp<ConfigEvent> configEvent = (ConfigEvent *)new SetParameterConfigEvent(keyValuePair);
671 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700672}
673
Eric Laurent1c333e22014-05-20 10:48:17 -0700674status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
675 const struct audio_patch *patch,
676 audio_patch_handle_t *handle)
677{
678 Mutex::Autolock _l(mLock);
679 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
680 status_t status = sendConfigEvent_l(configEvent);
681 if (status == NO_ERROR) {
682 CreateAudioPatchConfigEventData *data =
683 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
684 *handle = data->mHandle;
685 }
686 return status;
687}
688
689status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
690 const audio_patch_handle_t handle)
691{
692 Mutex::Autolock _l(mLock);
693 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
694 return sendConfigEvent_l(configEvent);
695}
696
697
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700698// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700699void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700700{
Eric Laurent10351942014-05-08 18:49:52 -0700701 bool configChanged = false;
702
Eric Laurent81784c32012-11-19 14:55:58 -0800703 while (!mConfigEvents.isEmpty()) {
Eric Laurent10351942014-05-08 18:49:52 -0700704 ALOGV("processConfigEvents_l() remaining events %d", mConfigEvents.size());
705 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800706 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700707 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700708 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700709 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
710 // FIXME Need to understand why this has to be done asynchronously
711 int err = requestPriority(data->mPid, data->mTid, data->mPrio,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700712 true /*asynchronous*/);
713 if (err != 0) {
714 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700715 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700716 }
717 } break;
718 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700719 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700720 ioConfigChanged(data->mEvent, data->mPid);
Eric Laurent10351942014-05-08 18:49:52 -0700721 } break;
722 case CFG_EVENT_SET_PARAMETER: {
723 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
724 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
725 configChanged = true;
Glenn Kastend5418eb2013-08-14 13:11:06 -0700726 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700727 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700728 case CFG_EVENT_CREATE_AUDIO_PATCH: {
729 CreateAudioPatchConfigEventData *data =
730 (CreateAudioPatchConfigEventData *)event->mData.get();
731 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
732 } break;
733 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
734 ReleaseAudioPatchConfigEventData *data =
735 (ReleaseAudioPatchConfigEventData *)event->mData.get();
736 event->mStatus = releaseAudioPatch_l(data->mHandle);
737 } break;
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700738 default:
Eric Laurent10351942014-05-08 18:49:52 -0700739 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700740 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800741 }
Eric Laurent10351942014-05-08 18:49:52 -0700742 {
743 Mutex::Autolock _l(event->mLock);
744 if (event->mWaitStatus) {
745 event->mWaitStatus = false;
746 event->mCond.signal();
747 }
748 }
749 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
750 }
751
752 if (configChanged) {
753 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800754 }
Eric Laurent81784c32012-11-19 14:55:58 -0800755}
756
Marco Nelissenb2208842014-02-07 14:00:50 -0800757String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
758 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700759 const audio_channel_representation_t representation =
760 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700761
762 switch (representation) {
763 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
764 if (output) {
765 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
766 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
767 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
768 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
769 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
770 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
771 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
772 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
773 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
774 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
775 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
776 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
777 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
778 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
779 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
780 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
781 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
782 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
783 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
784 } else {
785 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
786 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
787 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
788 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
789 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
790 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
791 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
792 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
793 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
794 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
795 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
796 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
797 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
798 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
799 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
800 }
801 const int len = s.length();
802 if (len > 2) {
803 char *str = s.lockBuffer(len); // needed?
804 s.unlockBuffer(len - 2); // remove trailing ", "
805 }
806 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800807 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700808 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
809 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
810 return s;
811 default:
812 s.appendFormat("unknown mask, representation:%d bits:%#x",
813 representation, audio_channel_mask_get_bits(mask));
814 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800815 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800816}
817
Glenn Kasten0f11b512014-01-31 16:18:54 -0800818void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800819{
820 const size_t SIZE = 256;
821 char buffer[SIZE];
822 String8 result;
823
824 bool locked = AudioFlinger::dumpTryLock(mLock);
825 if (!locked) {
Glenn Kasten97b7b752014-09-28 13:04:24 -0700826 dprintf(fd, "thread %p may be deadlocked\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -0800827 }
828
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800829 dprintf(fd, " Thread name: %s\n", mThreadName);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700830 dprintf(fd, " I/O handle: %d\n", mId);
831 dprintf(fd, " TID: %d\n", getTid());
832 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700833 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700834 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700835 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat));
Elliott Hughes87cebad2014-05-22 10:14:43 -0700836 dprintf(fd, " HAL buffer size: %u bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700837 dprintf(fd, " Channel count: %u\n", mChannelCount);
838 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800839 channelMaskToString(mChannelMask, mType != RECORD).string());
Glenn Kastenf87c2f52015-08-21 08:03:57 -0700840 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat, formatToString(mFormat));
841 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700842 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800843 size_t numConfig = mConfigEvents.size();
844 if (numConfig) {
845 for (size_t i = 0; i < numConfig; i++) {
846 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700847 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800848 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700849 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800850 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700851 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800852 }
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800853 dprintf(fd, " Output device: %#x (%s)\n", mOutDevice, devicesToString(mOutDevice).string());
854 dprintf(fd, " Input device: %#x (%s)\n", mInDevice, devicesToString(mInDevice).string());
855 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, sourceToString(mAudioSource));
Eric Laurent81784c32012-11-19 14:55:58 -0800856
857 if (locked) {
858 mLock.unlock();
859 }
860}
861
862void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
863{
864 const size_t SIZE = 256;
865 char buffer[SIZE];
866 String8 result;
867
Marco Nelissenb2208842014-02-07 14:00:50 -0800868 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000869 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800870 write(fd, buffer, strlen(buffer));
871
Marco Nelissenb2208842014-02-07 14:00:50 -0800872 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800873 sp<EffectChain> chain = mEffectChains[i];
874 if (chain != 0) {
875 chain->dump(fd, args);
876 }
877 }
878}
879
Marco Nelissene14a5d62013-10-03 08:51:24 -0700880void AudioFlinger::ThreadBase::acquireWakeLock(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800881{
882 Mutex::Autolock _l(mLock);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700883 acquireWakeLock_l(uid);
Eric Laurent81784c32012-11-19 14:55:58 -0800884}
885
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100886String16 AudioFlinger::ThreadBase::getWakeLockTag()
887{
888 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -0800889 case MIXER:
890 return String16("AudioMix");
891 case DIRECT:
892 return String16("AudioDirectOut");
893 case DUPLICATING:
894 return String16("AudioDup");
895 case RECORD:
896 return String16("AudioIn");
897 case OFFLOAD:
898 return String16("AudioOffload");
899 default:
900 ALOG_ASSERT(false);
901 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100902 }
903}
904
Marco Nelissene14a5d62013-10-03 08:51:24 -0700905void AudioFlinger::ThreadBase::acquireWakeLock_l(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800906{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800907 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800908 if (mPowerManager != 0) {
909 sp<IBinder> binder = new BBinder();
Marco Nelissene14a5d62013-10-03 08:51:24 -0700910 status_t status;
911 if (uid >= 0) {
Eric Laurent547789d2013-10-04 11:46:55 -0700912 status = mPowerManager->acquireWakeLockWithUid(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700913 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100914 getWakeLockTag(),
Marco Nelissene14a5d62013-10-03 08:51:24 -0700915 String16("media"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700916 uid,
917 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700918 } else {
Eric Laurent547789d2013-10-04 11:46:55 -0700919 status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700920 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100921 getWakeLockTag(),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700922 String16("media"),
923 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700924 }
Eric Laurent81784c32012-11-19 14:55:58 -0800925 if (status == NO_ERROR) {
926 mWakeLockToken = binder;
927 }
Glenn Kastend7dca052015-03-05 16:05:54 -0800928 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Eric Laurent81784c32012-11-19 14:55:58 -0800929 }
930}
931
932void AudioFlinger::ThreadBase::releaseWakeLock()
933{
934 Mutex::Autolock _l(mLock);
935 releaseWakeLock_l();
936}
937
938void AudioFlinger::ThreadBase::releaseWakeLock_l()
939{
940 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800941 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -0800942 if (mPowerManager != 0) {
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700943 mPowerManager->releaseWakeLock(mWakeLockToken, 0,
944 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800945 }
946 mWakeLockToken.clear();
947 }
948}
949
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800950void AudioFlinger::ThreadBase::updateWakeLockUids(const SortedVector<int> &uids) {
951 Mutex::Autolock _l(mLock);
952 updateWakeLockUids_l(uids);
953}
954
955void AudioFlinger::ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -0700956 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800957 // use checkService() to avoid blocking if power service is not up yet
958 sp<IBinder> binder =
959 defaultServiceManager()->checkService(String16("power"));
960 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800961 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800962 } else {
963 mPowerManager = interface_cast<IPowerManager>(binder);
964 binder->linkToDeath(mDeathRecipient);
965 }
966 }
967}
968
969void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<int> &uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800970 getPowerManager_l();
971 if (mWakeLockToken == NULL) {
972 ALOGE("no wake lock to update!");
973 return;
974 }
975 if (mPowerManager != 0) {
976 sp<IBinder> binder = new BBinder();
977 status_t status;
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700978 status = mPowerManager->updateWakeLockUids(mWakeLockToken, uids.size(), uids.array(),
979 true /* FIXME force oneway contrary to .aidl */);
Glenn Kastend7dca052015-03-05 16:05:54 -0800980 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800981 }
982}
983
Eric Laurent81784c32012-11-19 14:55:58 -0800984void AudioFlinger::ThreadBase::clearPowerManager()
985{
986 Mutex::Autolock _l(mLock);
987 releaseWakeLock_l();
988 mPowerManager.clear();
989}
990
Glenn Kasten0f11b512014-01-31 16:18:54 -0800991void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800992{
993 sp<ThreadBase> thread = mThread.promote();
994 if (thread != 0) {
995 thread->clearPowerManager();
996 }
997 ALOGW("power manager service died !!!");
998}
999
1000void AudioFlinger::ThreadBase::setEffectSuspended(
1001 const effect_uuid_t *type, bool suspend, int sessionId)
1002{
1003 Mutex::Autolock _l(mLock);
1004 setEffectSuspended_l(type, suspend, sessionId);
1005}
1006
1007void AudioFlinger::ThreadBase::setEffectSuspended_l(
1008 const effect_uuid_t *type, bool suspend, int sessionId)
1009{
1010 sp<EffectChain> chain = getEffectChain_l(sessionId);
1011 if (chain != 0) {
1012 if (type != NULL) {
1013 chain->setEffectSuspended_l(type, suspend);
1014 } else {
1015 chain->setEffectSuspendedAll_l(suspend);
1016 }
1017 }
1018
1019 updateSuspendedSessions_l(type, suspend, sessionId);
1020}
1021
1022void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1023{
1024 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1025 if (index < 0) {
1026 return;
1027 }
1028
1029 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1030 mSuspendedSessions.valueAt(index);
1031
1032 for (size_t i = 0; i < sessionEffects.size(); i++) {
1033 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
1034 for (int j = 0; j < desc->mRefCount; j++) {
1035 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1036 chain->setEffectSuspendedAll_l(true);
1037 } else {
1038 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1039 desc->mType.timeLow);
1040 chain->setEffectSuspended_l(&desc->mType, true);
1041 }
1042 }
1043 }
1044}
1045
1046void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1047 bool suspend,
1048 int sessionId)
1049{
1050 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1051
1052 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1053
1054 if (suspend) {
1055 if (index >= 0) {
1056 sessionEffects = mSuspendedSessions.valueAt(index);
1057 } else {
1058 mSuspendedSessions.add(sessionId, sessionEffects);
1059 }
1060 } else {
1061 if (index < 0) {
1062 return;
1063 }
1064 sessionEffects = mSuspendedSessions.valueAt(index);
1065 }
1066
1067
1068 int key = EffectChain::kKeyForSuspendAll;
1069 if (type != NULL) {
1070 key = type->timeLow;
1071 }
1072 index = sessionEffects.indexOfKey(key);
1073
1074 sp<SuspendedSessionDesc> desc;
1075 if (suspend) {
1076 if (index >= 0) {
1077 desc = sessionEffects.valueAt(index);
1078 } else {
1079 desc = new SuspendedSessionDesc();
1080 if (type != NULL) {
1081 desc->mType = *type;
1082 }
1083 sessionEffects.add(key, desc);
1084 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1085 }
1086 desc->mRefCount++;
1087 } else {
1088 if (index < 0) {
1089 return;
1090 }
1091 desc = sessionEffects.valueAt(index);
1092 if (--desc->mRefCount == 0) {
1093 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1094 sessionEffects.removeItemsAt(index);
1095 if (sessionEffects.isEmpty()) {
1096 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1097 sessionId);
1098 mSuspendedSessions.removeItem(sessionId);
1099 }
1100 }
1101 }
1102 if (!sessionEffects.isEmpty()) {
1103 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1104 }
1105}
1106
1107void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1108 bool enabled,
1109 int sessionId)
1110{
1111 Mutex::Autolock _l(mLock);
1112 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1113}
1114
1115void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1116 bool enabled,
1117 int sessionId)
1118{
1119 if (mType != RECORD) {
1120 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1121 // another session. This gives the priority to well behaved effect control panels
1122 // and applications not using global effects.
1123 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1124 // global effects
1125 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
1126 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1127 }
1128 }
1129
1130 sp<EffectChain> chain = getEffectChain_l(sessionId);
1131 if (chain != 0) {
1132 chain->checkSuspendOnEffectEnabled(effect, enabled);
1133 }
1134}
1135
1136// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1137sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1138 const sp<AudioFlinger::Client>& client,
1139 const sp<IEffectClient>& effectClient,
1140 int32_t priority,
1141 int sessionId,
1142 effect_descriptor_t *desc,
1143 int *enabled,
Glenn Kasten9156ef32013-08-06 15:39:08 -07001144 status_t *status)
Eric Laurent81784c32012-11-19 14:55:58 -08001145{
1146 sp<EffectModule> effect;
1147 sp<EffectHandle> handle;
1148 status_t lStatus;
1149 sp<EffectChain> chain;
1150 bool chainCreated = false;
1151 bool effectCreated = false;
1152 bool effectRegistered = false;
1153
1154 lStatus = initCheck();
1155 if (lStatus != NO_ERROR) {
1156 ALOGW("createEffect_l() Audio driver not initialized.");
1157 goto Exit;
1158 }
1159
Andy Hung98ef9782014-03-04 14:46:50 -08001160 // Reject any effect on Direct output threads for now, since the format of
1161 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1162 if (mType == DIRECT) {
1163 ALOGW("createEffect_l() Cannot add effect %s on Direct output type thread %s",
Glenn Kastend7dca052015-03-05 16:05:54 -08001164 desc->name, mThreadName);
Andy Hung98ef9782014-03-04 14:46:50 -08001165 lStatus = BAD_VALUE;
1166 goto Exit;
1167 }
1168
Andy Hung389cfdb2014-08-07 17:49:53 -07001169 // Reject any effect on mixer or duplicating multichannel sinks.
Andy Hung9a592762014-07-21 21:56:01 -07001170 // TODO: fix both format and multichannel issues with effects.
Andy Hung389cfdb2014-08-07 17:49:53 -07001171 if ((mType == MIXER || mType == DUPLICATING) && mChannelCount != FCC_2) {
1172 ALOGW("createEffect_l() Cannot add effect %s for multichannel(%d) %s threads",
1173 desc->name, mChannelCount, mType == MIXER ? "MIXER" : "DUPLICATING");
Andy Hung9a592762014-07-21 21:56:01 -07001174 lStatus = BAD_VALUE;
1175 goto Exit;
1176 }
1177
Eric Laurent5baf2af2013-09-12 17:37:00 -07001178 // Allow global effects only on offloaded and mixer threads
1179 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1180 switch (mType) {
1181 case MIXER:
1182 case OFFLOAD:
1183 break;
1184 case DIRECT:
1185 case DUPLICATING:
1186 case RECORD:
1187 default:
Glenn Kastend7dca052015-03-05 16:05:54 -08001188 ALOGW("createEffect_l() Cannot add global effect %s on thread %s",
1189 desc->name, mThreadName);
Eric Laurent5baf2af2013-09-12 17:37:00 -07001190 lStatus = BAD_VALUE;
1191 goto Exit;
1192 }
Eric Laurent81784c32012-11-19 14:55:58 -08001193 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07001194
Eric Laurent81784c32012-11-19 14:55:58 -08001195 // Only Pre processor effects are allowed on input threads and only on input threads
1196 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
1197 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
1198 desc->name, desc->flags, mType);
1199 lStatus = BAD_VALUE;
1200 goto Exit;
1201 }
1202
1203 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1204
1205 { // scope for mLock
1206 Mutex::Autolock _l(mLock);
1207
1208 // check for existing effect chain with the requested audio session
1209 chain = getEffectChain_l(sessionId);
1210 if (chain == 0) {
1211 // create a new chain for this session
1212 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1213 chain = new EffectChain(this, sessionId);
1214 addEffectChain_l(chain);
1215 chain->setStrategy(getStrategyForSession_l(sessionId));
1216 chainCreated = true;
1217 } else {
1218 effect = chain->getEffectFromDesc_l(desc);
1219 }
1220
1221 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1222
1223 if (effect == 0) {
1224 int id = mAudioFlinger->nextUniqueId();
1225 // Check CPU and memory usage
1226 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
1227 if (lStatus != NO_ERROR) {
1228 goto Exit;
1229 }
1230 effectRegistered = true;
1231 // create a new effect module if none present in the chain
1232 effect = new EffectModule(this, chain, desc, id, sessionId);
1233 lStatus = effect->status();
1234 if (lStatus != NO_ERROR) {
1235 goto Exit;
1236 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07001237 effect->setOffloaded(mType == OFFLOAD, mId);
1238
Eric Laurent81784c32012-11-19 14:55:58 -08001239 lStatus = chain->addEffect_l(effect);
1240 if (lStatus != NO_ERROR) {
1241 goto Exit;
1242 }
1243 effectCreated = true;
1244
1245 effect->setDevice(mOutDevice);
1246 effect->setDevice(mInDevice);
1247 effect->setMode(mAudioFlinger->getMode());
1248 effect->setAudioSource(mAudioSource);
1249 }
1250 // create effect handle and connect it to effect module
1251 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001252 lStatus = handle->initCheck();
1253 if (lStatus == OK) {
1254 lStatus = effect->addHandle(handle.get());
1255 }
Eric Laurent81784c32012-11-19 14:55:58 -08001256 if (enabled != NULL) {
1257 *enabled = (int)effect->isEnabled();
1258 }
1259 }
1260
1261Exit:
1262 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1263 Mutex::Autolock _l(mLock);
1264 if (effectCreated) {
1265 chain->removeEffect_l(effect);
1266 }
1267 if (effectRegistered) {
1268 AudioSystem::unregisterEffect(effect->id());
1269 }
1270 if (chainCreated) {
1271 removeEffectChain_l(chain);
1272 }
1273 handle.clear();
1274 }
1275
Glenn Kasten9156ef32013-08-06 15:39:08 -07001276 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001277 return handle;
1278}
1279
1280sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
1281{
1282 Mutex::Autolock _l(mLock);
1283 return getEffect_l(sessionId, effectId);
1284}
1285
1286sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
1287{
1288 sp<EffectChain> chain = getEffectChain_l(sessionId);
1289 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1290}
1291
1292// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1293// PlaybackThread::mLock held
1294status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1295{
1296 // check for existing effect chain with the requested audio session
1297 int sessionId = effect->sessionId();
1298 sp<EffectChain> chain = getEffectChain_l(sessionId);
1299 bool chainCreated = false;
1300
Eric Laurent5baf2af2013-09-12 17:37:00 -07001301 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
1302 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
1303 this, effect->desc().name, effect->desc().flags);
1304
Eric Laurent81784c32012-11-19 14:55:58 -08001305 if (chain == 0) {
1306 // create a new chain for this session
1307 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1308 chain = new EffectChain(this, sessionId);
1309 addEffectChain_l(chain);
1310 chain->setStrategy(getStrategyForSession_l(sessionId));
1311 chainCreated = true;
1312 }
1313 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1314
1315 if (chain->getEffectFromId_l(effect->id()) != 0) {
1316 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1317 this, effect->desc().name, chain.get());
1318 return BAD_VALUE;
1319 }
1320
Eric Laurent5baf2af2013-09-12 17:37:00 -07001321 effect->setOffloaded(mType == OFFLOAD, mId);
1322
Eric Laurent81784c32012-11-19 14:55:58 -08001323 status_t status = chain->addEffect_l(effect);
1324 if (status != NO_ERROR) {
1325 if (chainCreated) {
1326 removeEffectChain_l(chain);
1327 }
1328 return status;
1329 }
1330
1331 effect->setDevice(mOutDevice);
1332 effect->setDevice(mInDevice);
1333 effect->setMode(mAudioFlinger->getMode());
1334 effect->setAudioSource(mAudioSource);
1335 return NO_ERROR;
1336}
1337
1338void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
1339
1340 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
1341 effect_descriptor_t desc = effect->desc();
1342 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1343 detachAuxEffect_l(effect->id());
1344 }
1345
1346 sp<EffectChain> chain = effect->chain().promote();
1347 if (chain != 0) {
1348 // remove effect chain if removing last effect
1349 if (chain->removeEffect_l(effect) == 0) {
1350 removeEffectChain_l(chain);
1351 }
1352 } else {
1353 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1354 }
1355}
1356
1357void AudioFlinger::ThreadBase::lockEffectChains_l(
1358 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1359{
1360 effectChains = mEffectChains;
1361 for (size_t i = 0; i < mEffectChains.size(); i++) {
1362 mEffectChains[i]->lock();
1363 }
1364}
1365
1366void AudioFlinger::ThreadBase::unlockEffectChains(
1367 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1368{
1369 for (size_t i = 0; i < effectChains.size(); i++) {
1370 effectChains[i]->unlock();
1371 }
1372}
1373
1374sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
1375{
1376 Mutex::Autolock _l(mLock);
1377 return getEffectChain_l(sessionId);
1378}
1379
1380sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const
1381{
1382 size_t size = mEffectChains.size();
1383 for (size_t i = 0; i < size; i++) {
1384 if (mEffectChains[i]->sessionId() == sessionId) {
1385 return mEffectChains[i];
1386 }
1387 }
1388 return 0;
1389}
1390
1391void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1392{
1393 Mutex::Autolock _l(mLock);
1394 size_t size = mEffectChains.size();
1395 for (size_t i = 0; i < size; i++) {
1396 mEffectChains[i]->setMode_l(mode);
1397 }
1398}
1399
Eric Laurent83b88082014-06-20 18:31:16 -07001400void AudioFlinger::ThreadBase::getAudioPortConfig(struct audio_port_config *config)
1401{
1402 config->type = AUDIO_PORT_TYPE_MIX;
1403 config->ext.mix.handle = mId;
1404 config->sample_rate = mSampleRate;
1405 config->format = mFormat;
1406 config->channel_mask = mChannelMask;
1407 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1408 AUDIO_PORT_CONFIG_FORMAT;
1409}
1410
Eric Laurent72e3f392015-05-20 14:43:50 -07001411void AudioFlinger::ThreadBase::systemReady()
1412{
1413 Mutex::Autolock _l(mLock);
1414 if (mSystemReady) {
1415 return;
1416 }
1417 mSystemReady = true;
1418
1419 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1420 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1421 }
1422 mPendingConfigEvents.clear();
1423}
1424
Eric Laurent83b88082014-06-20 18:31:16 -07001425
Eric Laurent81784c32012-11-19 14:55:58 -08001426// ----------------------------------------------------------------------------
1427// Playback
1428// ----------------------------------------------------------------------------
1429
1430AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1431 AudioStreamOut* output,
1432 audio_io_handle_t id,
1433 audio_devices_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07001434 type_t type,
1435 bool systemReady)
1436 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type, systemReady),
Andy Hung2098f272014-02-27 14:00:06 -08001437 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001438 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001439 mMixerBuffer(NULL),
1440 mMixerBufferSize(0),
1441 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1442 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001443 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001444 mEffectBuffer(NULL),
1445 mEffectBufferSize(0),
1446 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1447 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001448 mSuspended(0), mBytesWritten(0),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001449 mActiveTracksGeneration(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001450 // mStreamTypes[] initialized in constructor body
1451 mOutput(output),
1452 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
1453 mMixerStatus(MIXER_IDLE),
1454 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001455 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001456 mBytesRemaining(0),
1457 mCurrentWriteLength(0),
1458 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001459 mWriteAckSequence(0),
1460 mDrainSequence(0),
Eric Laurentede6c3b2013-09-19 14:37:46 -07001461 mSignalPending(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001462 mScreenState(AudioFlinger::mScreenState),
1463 // index 0 is reserved for normal mixer's submix
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001464 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1),
Eric Laurentd1f69b02014-12-15 14:33:13 -08001465 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001466 // mLatchD, mLatchQ,
1467 mLatchDValid(false), mLatchQValid(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001468{
Glenn Kastend7dca052015-03-05 16:05:54 -08001469 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1470 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001471
1472 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1473 // it would be safer to explicitly pass initial masterVolume/masterMute as
1474 // parameter.
1475 //
1476 // If the HAL we are using has support for master volume or master mute,
1477 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1478 // and the mute set to false).
1479 mMasterVolume = audioFlinger->masterVolume_l();
1480 mMasterMute = audioFlinger->masterMute_l();
1481 if (mOutput && mOutput->audioHwDev) {
1482 if (mOutput->audioHwDev->canSetMasterVolume()) {
1483 mMasterVolume = 1.0;
1484 }
1485
1486 if (mOutput->audioHwDev->canSetMasterMute()) {
1487 mMasterMute = false;
1488 }
1489 }
1490
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001491 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001492
Eric Laurent223fd5c2014-11-11 13:43:36 -08001493 // ++ operator does not compile
Glenn Kasten66e46352014-01-16 17:44:23 -08001494 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001495 stream = (audio_stream_type_t) (stream + 1)) {
1496 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1497 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1498 }
Eric Laurent81784c32012-11-19 14:55:58 -08001499}
1500
1501AudioFlinger::PlaybackThread::~PlaybackThread()
1502{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001503 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001504 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001505 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001506 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001507}
1508
1509void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1510{
1511 dumpInternals(fd, args);
1512 dumpTracks(fd, args);
1513 dumpEffectChains(fd, args);
1514}
1515
Glenn Kasten0f11b512014-01-31 16:18:54 -08001516void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001517{
1518 const size_t SIZE = 256;
1519 char buffer[SIZE];
1520 String8 result;
1521
Marco Nelissenb2208842014-02-07 14:00:50 -08001522 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001523 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1524 const stream_type_t *st = &mStreamTypes[i];
1525 if (i > 0) {
1526 result.appendFormat(", ");
1527 }
1528 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1529 if (st->mute) {
1530 result.append("M");
1531 }
1532 }
1533 result.append("\n");
1534 write(fd, result.string(), result.length());
1535 result.clear();
1536
Eric Laurent81784c32012-11-19 14:55:58 -08001537 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1538 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001539 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001540 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001541
1542 size_t numtracks = mTracks.size();
1543 size_t numactive = mActiveTracks.size();
Elliott Hughes87cebad2014-05-22 10:14:43 -07001544 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001545 size_t numactiveseen = 0;
1546 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07001547 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08001548 Track::appendDumpHeader(result);
1549 for (size_t i = 0; i < numtracks; ++i) {
1550 sp<Track> track = mTracks[i];
1551 if (track != 0) {
1552 bool active = mActiveTracks.indexOf(track) >= 0;
1553 if (active) {
1554 numactiveseen++;
1555 }
1556 track->dump(buffer, SIZE, active);
1557 result.append(buffer);
1558 }
1559 }
1560 } else {
1561 result.append("\n");
1562 }
1563 if (numactiveseen != numactive) {
1564 // some tracks in the active list were not in the tracks list
1565 snprintf(buffer, SIZE, " The following tracks are in the active list but"
1566 " not in the track list\n");
1567 result.append(buffer);
1568 Track::appendDumpHeader(result);
1569 for (size_t i = 0; i < numactive; ++i) {
1570 sp<Track> track = mActiveTracks[i].promote();
1571 if (track != 0 && mTracks.indexOf(track) < 0) {
1572 track->dump(buffer, SIZE, true);
1573 result.append(buffer);
1574 }
1575 }
1576 }
1577
1578 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001579}
1580
1581void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1582{
Glenn Kasten97b7b752014-09-28 13:04:24 -07001583 dprintf(fd, "\nOutput thread %p type %d (%s):\n", this, type(), threadTypeToString(type()));
Glenn Kasten44182c22015-03-05 17:12:23 -08001584
1585 dumpBase(fd, args);
1586
Elliott Hughes87cebad2014-05-22 10:14:43 -07001587 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
1588 dprintf(fd, " Last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1589 dprintf(fd, " Total writes: %d\n", mNumWrites);
1590 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1591 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1592 dprintf(fd, " Suspend count: %d\n", mSuspended);
1593 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1594 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1595 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1596 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001597 AudioStreamOut *output = mOutput;
1598 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
1599 String8 flagsAsString = outputFlagsToString(flags);
1600 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n", output, flags, flagsAsString.string());
Eric Laurent81784c32012-11-19 14:55:58 -08001601}
1602
1603// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001604
1605void AudioFlinger::PlaybackThread::onFirstRef()
1606{
Glenn Kastend7dca052015-03-05 16:05:54 -08001607 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001608}
1609
1610// ThreadBase virtuals
1611void AudioFlinger::PlaybackThread::preExit()
1612{
1613 ALOGV(" preExit()");
1614 // FIXME this is using hard-coded strings but in the future, this functionality will be
1615 // converted to use audio HAL extensions required to support tunneling
1616 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1617}
1618
1619// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1620sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1621 const sp<AudioFlinger::Client>& client,
1622 audio_stream_type_t streamType,
1623 uint32_t sampleRate,
1624 audio_format_t format,
1625 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001626 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001627 const sp<IMemory>& sharedBuffer,
1628 int sessionId,
1629 IAudioFlinger::track_flags_t *flags,
1630 pid_t tid,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001631 int uid,
Eric Laurent81784c32012-11-19 14:55:58 -08001632 status_t *status)
1633{
Glenn Kasten74935e42013-12-19 08:56:45 -08001634 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001635 sp<Track> track;
1636 status_t lStatus;
1637
1638 bool isTimed = (*flags & IAudioFlinger::TRACK_TIMED) != 0;
1639
1640 // client expresses a preference for FAST, but we get the final say
1641 if (*flags & IAudioFlinger::TRACK_FAST) {
1642 if (
1643 // not timed
1644 (!isTimed) &&
1645 // either of these use cases:
1646 (
1647 // use case 1: shared buffer with any frame count
1648 (
1649 (sharedBuffer != 0)
1650 ) ||
Glenn Kasten1dfe2f92015-03-09 12:03:14 -07001651 // use case 2: frame count is default or at least as large as HAL
Eric Laurent81784c32012-11-19 14:55:58 -08001652 (
Glenn Kasten1dfe2f92015-03-09 12:03:14 -07001653 // we formerly checked for a callback handler (non-0 tid),
1654 // but that is no longer required for TRANSFER_OBTAIN mode
Eric Laurent81784c32012-11-19 14:55:58 -08001655 ((frameCount == 0) ||
Glenn Kastenb5fed682013-12-03 09:06:43 -08001656 (frameCount >= mFrameCount))
Eric Laurent81784c32012-11-19 14:55:58 -08001657 )
1658 ) &&
1659 // PCM data
1660 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07001661 // TODO: extract as a data library function that checks that a computationally
1662 // expensive downmixer is not required: isFastOutputChannelConversion()
Andy Hung9a592762014-07-21 21:56:01 -07001663 (channelMask == mChannelMask ||
Andy Hung1f439e12015-05-19 12:57:41 -07001664 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
1665 (channelMask == AUDIO_CHANNEL_OUT_MONO
1666 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001667 // hardware sample rate
1668 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001669 // normal mixer has an associated fast mixer
1670 hasFastMixer() &&
1671 // there are sufficient fast track slots available
1672 (mFastTrackAvailMask != 0)
1673 // FIXME test that MixerThread for this fast track has a capable output HAL
1674 // FIXME add a permission test also?
1675 ) {
1676 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1677 if (frameCount == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001678 // read the fast track multiplier property the first time it is needed
1679 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1680 if (ok != 0) {
1681 ALOGE("%s pthread_once failed: %d", __func__, ok);
1682 }
1683 frameCount = mFrameCount * sFastTrackMultiplier;
Eric Laurent81784c32012-11-19 14:55:58 -08001684 }
1685 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
1686 frameCount, mFrameCount);
1687 } else {
1688 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
Andy Hung6146c082014-03-18 11:56:15 -07001689 "mFrameCount=%d format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
1690 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001691 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Andy Hung6146c082014-03-18 11:56:15 -07001692 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001693 audio_is_linear_pcm(format),
1694 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
1695 *flags &= ~IAudioFlinger::TRACK_FAST;
Andy Hung0e48d252015-01-26 11:43:15 -08001696 }
1697 }
1698 // For normal PCM streaming tracks, update minimum frame count.
1699 // For compatibility with AudioTrack calculation, buffer depth is forced
1700 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1701 // This is probably too conservative, but legacy application code may depend on it.
1702 // If you change this calculation, also review the start threshold which is related.
1703 if (!(*flags & IAudioFlinger::TRACK_FAST)
1704 && audio_is_linear_pcm(format) && sharedBuffer == 0) {
Andy Hung8edb8dc2015-03-26 19:13:55 -07001705 // this must match AudioTrack.cpp calculateMinFrameCount().
1706 // TODO: Move to a common library
Eric Laurent81784c32012-11-19 14:55:58 -08001707 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1708 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1709 if (minBufCount < 2) {
1710 minBufCount = 2;
1711 }
Andy Hung8edb8dc2015-03-26 19:13:55 -07001712 // For normal mixing tracks, if speed is > 1.0f (normal), AudioTrack
1713 // or the client should compute and pass in a larger buffer request.
Andy Hung0e48d252015-01-26 11:43:15 -08001714 size_t minFrameCount =
Andy Hung8edb8dc2015-03-26 19:13:55 -07001715 minBufCount * sourceFramesNeededWithTimestretch(
1716 sampleRate, mNormalFrameCount,
1717 mSampleRate, AUDIO_TIMESTRETCH_SPEED_NORMAL /*speed*/);
Andy Hung0e48d252015-01-26 11:43:15 -08001718 if (frameCount < minFrameCount) { // including frameCount == 0
Eric Laurent81784c32012-11-19 14:55:58 -08001719 frameCount = minFrameCount;
1720 }
Eric Laurent81784c32012-11-19 14:55:58 -08001721 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001722 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001723
Glenn Kastenc3df8382014-03-13 15:05:25 -07001724 switch (mType) {
1725
1726 case DIRECT:
Glenn Kasten993fa062014-05-02 11:14:34 -07001727 if (audio_is_linear_pcm(format)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001728 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001729 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1730 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001731 sampleRate, format, channelMask, mOutput, mFormat);
1732 lStatus = BAD_VALUE;
1733 goto Exit;
1734 }
1735 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001736 break;
1737
1738 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001739 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001740 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1741 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001742 sampleRate, format, channelMask, mOutput, mFormat);
1743 lStatus = BAD_VALUE;
1744 goto Exit;
1745 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001746 break;
1747
1748 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07001749 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001750 ALOGE("createTrack_l() Bad parameter: format %#x \""
1751 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001752 format, mOutput, mFormat);
1753 lStatus = BAD_VALUE;
1754 goto Exit;
1755 }
Andy Hungcd044842014-08-07 11:04:34 -07001756 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08001757 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1758 lStatus = BAD_VALUE;
1759 goto Exit;
1760 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001761 break;
1762
Eric Laurent81784c32012-11-19 14:55:58 -08001763 }
1764
1765 lStatus = initCheck();
1766 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07001767 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08001768 goto Exit;
1769 }
1770
1771 { // scope for mLock
1772 Mutex::Autolock _l(mLock);
1773
1774 // all tracks in same audio session must share the same routing strategy otherwise
1775 // conflicts will happen when tracks are moved from one output to another by audio policy
1776 // manager
1777 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1778 for (size_t i = 0; i < mTracks.size(); ++i) {
1779 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07001780 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001781 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1782 if (sessionId == t->sessionId() && strategy != actual) {
1783 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1784 strategy, actual);
1785 lStatus = BAD_VALUE;
1786 goto Exit;
1787 }
1788 }
1789 }
1790
1791 if (!isTimed) {
1792 track = new Track(this, client, streamType, sampleRate, format,
Eric Laurent83b88082014-06-20 18:31:16 -07001793 channelMask, frameCount, NULL, sharedBuffer,
1794 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08001795 } else {
1796 track = TimedTrack::create(this, client, streamType, sampleRate, format,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001797 channelMask, frameCount, sharedBuffer, sessionId, uid);
Eric Laurent81784c32012-11-19 14:55:58 -08001798 }
Glenn Kasten03003332013-08-06 15:40:54 -07001799
1800 // new Track always returns non-NULL,
1801 // but TimedTrack::create() is a factory that could fail by returning NULL
1802 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
1803 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08001804 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001805 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08001806 goto Exit;
1807 }
1808 mTracks.add(track);
1809
1810 sp<EffectChain> chain = getEffectChain_l(sessionId);
1811 if (chain != 0) {
1812 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1813 track->setMainBuffer(chain->inBuffer());
1814 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1815 chain->incTrackCnt();
1816 }
1817
1818 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1819 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1820 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1821 // so ask activity manager to do this on our behalf
1822 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1823 }
1824 }
1825
1826 lStatus = NO_ERROR;
1827
1828Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001829 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001830 return track;
1831}
1832
1833uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1834{
1835 return latency;
1836}
1837
1838uint32_t AudioFlinger::PlaybackThread::latency() const
1839{
1840 Mutex::Autolock _l(mLock);
1841 return latency_l();
1842}
1843uint32_t AudioFlinger::PlaybackThread::latency_l() const
1844{
1845 if (initCheck() == NO_ERROR) {
1846 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
1847 } else {
1848 return 0;
1849 }
1850}
1851
1852void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1853{
1854 Mutex::Autolock _l(mLock);
1855 // Don't apply master volume in SW if our HAL can do it for us.
1856 if (mOutput && mOutput->audioHwDev &&
1857 mOutput->audioHwDev->canSetMasterVolume()) {
1858 mMasterVolume = 1.0;
1859 } else {
1860 mMasterVolume = value;
1861 }
1862}
1863
1864void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1865{
1866 Mutex::Autolock _l(mLock);
1867 // Don't apply master mute in SW if our HAL can do it for us.
1868 if (mOutput && mOutput->audioHwDev &&
1869 mOutput->audioHwDev->canSetMasterMute()) {
1870 mMasterMute = false;
1871 } else {
1872 mMasterMute = muted;
1873 }
1874}
1875
1876void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
1877{
1878 Mutex::Autolock _l(mLock);
1879 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001880 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001881}
1882
1883void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
1884{
1885 Mutex::Autolock _l(mLock);
1886 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001887 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001888}
1889
1890float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
1891{
1892 Mutex::Autolock _l(mLock);
1893 return mStreamTypes[stream].volume;
1894}
1895
1896// addTrack_l() must be called with ThreadBase::mLock held
1897status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1898{
1899 status_t status = ALREADY_EXISTS;
1900
1901 // set retry count for buffer fill
1902 track->mRetryCount = kMaxTrackStartupRetries;
1903 if (mActiveTracks.indexOf(track) < 0) {
1904 // the track is newly added, make sure it fills up all its
1905 // buffers before playing. This is to ensure the client will
1906 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07001907 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001908 TrackBase::track_state state = track->mState;
1909 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08001910 status = AudioSystem::startOutput(mId, track->streamType(),
1911 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001912 mLock.lock();
1913 // abort track was stopped/paused while we released the lock
1914 if (state != track->mState) {
1915 if (status == NO_ERROR) {
1916 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08001917 AudioSystem::stopOutput(mId, track->streamType(),
1918 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001919 mLock.lock();
1920 }
1921 return INVALID_OPERATION;
1922 }
1923 // abort if start is rejected by audio policy manager
1924 if (status != NO_ERROR) {
1925 return PERMISSION_DENIED;
1926 }
1927#ifdef ADD_BATTERY_DATA
1928 // to track the speaker usage
1929 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
1930#endif
1931 }
1932
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001933 track->mFillingUpStatus = track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent81784c32012-11-19 14:55:58 -08001934 track->mResetDone = false;
1935 track->mPresentationCompleteFrames = 0;
1936 mActiveTracks.add(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001937 mWakeLockUids.add(track->uid());
1938 mActiveTracksGeneration++;
Eric Laurentfd477972013-10-25 18:10:40 -07001939 mLatestActiveTrack = track;
Eric Laurentd0107bc2013-06-11 14:38:48 -07001940 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1941 if (chain != 0) {
1942 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
1943 track->sessionId());
1944 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08001945 }
1946
1947 status = NO_ERROR;
1948 }
1949
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08001950 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001951 return status;
1952}
1953
Eric Laurentbfb1b832013-01-07 09:53:42 -08001954bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08001955{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001956 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08001957 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001958 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
1959 track->mState = TrackBase::STOPPED;
1960 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08001961 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07001962 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001963 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08001964 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001965
1966 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08001967}
1968
1969void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1970{
1971 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
1972 mTracks.remove(track);
1973 deleteTrackName_l(track->name());
1974 // redundant as track is about to be destroyed, for dumpsys only
1975 track->mName = -1;
1976 if (track->isFastTrack()) {
1977 int index = track->mFastIndex;
1978 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
1979 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1980 mFastTrackAvailMask |= 1 << index;
1981 // redundant as track is about to be destroyed, for dumpsys only
1982 track->mFastIndex = -1;
1983 }
1984 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1985 if (chain != 0) {
1986 chain->decTrackCnt();
1987 }
1988}
1989
Eric Laurentede6c3b2013-09-19 14:37:46 -07001990void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001991{
1992 // Thread could be blocked waiting for async
1993 // so signal it to handle state changes immediately
1994 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1995 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1996 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001997 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001998}
1999
Eric Laurent81784c32012-11-19 14:55:58 -08002000String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2001{
Eric Laurent81784c32012-11-19 14:55:58 -08002002 Mutex::Autolock _l(mLock);
2003 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07002004 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002005 }
2006
Glenn Kastend8ea6992013-07-16 14:17:15 -07002007 char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
2008 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08002009 free(s);
2010 return out_s8;
2011}
2012
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002013void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002014 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2015 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002016
Eric Laurent73e26b62015-04-27 16:55:58 -07002017 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002018
2019 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002020 case AUDIO_OUTPUT_OPENED:
2021 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002022 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002023 desc->mChannelMask = mChannelMask;
2024 desc->mSamplingRate = mSampleRate;
2025 desc->mFormat = mFormat;
2026 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002027 // AudioFlinger::frameCount(audio_io_handle_t)
Eric Laurent73e26b62015-04-27 16:55:58 -07002028 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002029 break;
2030
Eric Laurent73e26b62015-04-27 16:55:58 -07002031 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002032 default:
2033 break;
2034 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002035 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002036}
2037
Eric Laurentbfb1b832013-01-07 09:53:42 -08002038void AudioFlinger::PlaybackThread::writeCallback()
2039{
2040 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002041 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002042}
2043
2044void AudioFlinger::PlaybackThread::drainCallback()
2045{
2046 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002047 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002048}
2049
Eric Laurent3b4529e2013-09-05 18:09:19 -07002050void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002051{
2052 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002053 // reject out of sequence requests
2054 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2055 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002056 mWaitWorkCV.signal();
2057 }
2058}
2059
Eric Laurent3b4529e2013-09-05 18:09:19 -07002060void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002061{
2062 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002063 // reject out of sequence requests
2064 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
2065 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002066 mWaitWorkCV.signal();
2067 }
2068}
2069
2070// static
2071int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
Glenn Kasten0f11b512014-01-31 16:18:54 -08002072 void *param __unused,
Eric Laurentbfb1b832013-01-07 09:53:42 -08002073 void *cookie)
2074{
2075 AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
2076 ALOGV("asyncCallback() event %d", event);
2077 switch (event) {
2078 case STREAM_CBK_EVENT_WRITE_READY:
2079 me->writeCallback();
2080 break;
2081 case STREAM_CBK_EVENT_DRAIN_READY:
2082 me->drainCallback();
2083 break;
2084 default:
2085 ALOGW("asyncCallback() unknown event %d", event);
2086 break;
2087 }
2088 return 0;
2089}
2090
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002091void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002092{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002093 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Phil Burkca5e6142015-07-14 09:42:29 -07002094 mSampleRate = mOutput->getSampleRate();
2095 mChannelMask = mOutput->getChannelMask();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002096 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002097 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002098 }
Andy Hung9a592762014-07-21 21:56:01 -07002099 if ((mType == MIXER || mType == DUPLICATING)
2100 && !isValidPcmSinkChannelMask(mChannelMask)) {
2101 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2102 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002103 }
Andy Hunge5412692014-05-16 11:25:07 -07002104 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002105
2106 // Get actual HAL format.
Andy Hung463be252014-07-10 16:56:07 -07002107 mHALFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Phil Burkca5e6142015-07-14 09:42:29 -07002108 // Get format from the shim, which will be different than the HAL format
2109 // if playing compressed audio over HDMI passthrough.
2110 mFormat = mOutput->getFormat();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002111 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002112 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002113 }
Andy Hung6146c082014-03-18 11:56:15 -07002114 if ((mType == MIXER || mType == DUPLICATING)
2115 && !isValidPcmSinkFormat(mFormat)) {
2116 LOG_FATAL("HAL format %#x not supported for mixed output",
2117 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002118 }
Phil Burk062e67a2015-02-11 13:40:50 -08002119 mFrameSize = mOutput->getFrameSize();
Glenn Kasten70949c42013-08-06 07:40:12 -07002120 mBufferSize = mOutput->stream->common.get_buffer_size(&mOutput->stream->common);
2121 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002122 if (mFrameCount & 15) {
2123 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
2124 mFrameCount);
2125 }
2126
Eric Laurentbfb1b832013-01-07 09:53:42 -08002127 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
2128 (mOutput->stream->set_callback != NULL)) {
2129 if (mOutput->stream->set_callback(mOutput->stream,
2130 AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
2131 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002132 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002133 }
2134 }
2135
Eric Laurentd1f69b02014-12-15 14:33:13 -08002136 mHwSupportsPause = false;
2137 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
2138 if (mOutput->stream->pause != NULL) {
2139 if (mOutput->stream->resume != NULL) {
2140 mHwSupportsPause = true;
2141 } else {
2142 ALOGW("direct output implements pause but not resume");
2143 }
2144 } else if (mOutput->stream->resume != NULL) {
2145 ALOGW("direct output implements resume but not pause");
2146 }
2147 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002148 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2149 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2150 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002151
Andy Hungfbfc3952015-01-15 13:33:51 -08002152 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2153 // For best precision, we use float instead of the associated output
2154 // device format (typically PCM 16 bit).
2155
2156 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2157 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2158 mBufferSize = mFrameSize * mFrameCount;
2159
2160 // TODO: We currently use the associated output device channel mask and sample rate.
2161 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2162 // (if a valid mask) to avoid premature downmix.
2163 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2164 // instead of the output device sample rate to avoid loss of high frequency information.
2165 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2166 }
2167
Andy Hung09a50072014-02-27 14:30:47 -08002168 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002169 double multiplier = 1.0;
2170 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2171 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002172 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2173 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Eric Laurent81784c32012-11-19 14:55:58 -08002174 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2175 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2176 maxNormalFrameCount = maxNormalFrameCount & ~15;
2177 if (maxNormalFrameCount < minNormalFrameCount) {
2178 maxNormalFrameCount = minNormalFrameCount;
2179 }
2180 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2181 if (multiplier <= 1.0) {
2182 multiplier = 1.0;
2183 } else if (multiplier <= 2.0) {
2184 if (2 * mFrameCount <= maxNormalFrameCount) {
2185 multiplier = 2.0;
2186 } else {
2187 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2188 }
2189 } else {
2190 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
Andy Hung09a50072014-02-27 14:30:47 -08002191 // 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 -08002192 // track, but we sometimes have to do this to satisfy the maximum frame count
2193 // constraint)
2194 // FIXME this rounding up should not be done if no HAL SRC
2195 uint32_t truncMult = (uint32_t) multiplier;
2196 if ((truncMult & 1)) {
2197 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
2198 ++truncMult;
2199 }
2200 }
2201 multiplier = (double) truncMult;
2202 }
2203 }
2204 mNormalFrameCount = multiplier * mFrameCount;
2205 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002206 if (mType == MIXER || mType == DUPLICATING) {
2207 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2208 }
Andy Hung09a50072014-02-27 14:30:47 -08002209 ALOGI("HAL output buffer size %u frames, normal sink buffer size %u frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002210 mNormalFrameCount);
2211
Andy Hung08fb1742015-05-31 23:22:10 -07002212 // Check if we want to throttle the processing to no more than 2x normal rate
2213 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002214 mThreadThrottleTimeMs = 0;
2215 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002216 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2217
Andy Hung010a1a12014-03-13 13:57:33 -07002218 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2219 // Originally this was int16_t[] array, need to remove legacy implications.
2220 free(mSinkBuffer);
2221 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002222 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2223 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2224 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002225 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002226
Andy Hung69aed5f2014-02-25 17:24:40 -08002227 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2228 // drives the output.
2229 free(mMixerBuffer);
2230 mMixerBuffer = NULL;
2231 if (mMixerBufferEnabled) {
2232 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2233 mMixerBufferSize = mNormalFrameCount * mChannelCount
2234 * audio_bytes_per_sample(mMixerBufferFormat);
2235 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2236 }
Andy Hung98ef9782014-03-04 14:46:50 -08002237 free(mEffectBuffer);
2238 mEffectBuffer = NULL;
2239 if (mEffectBufferEnabled) {
2240 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
2241 mEffectBufferSize = mNormalFrameCount * mChannelCount
2242 * audio_bytes_per_sample(mEffectBufferFormat);
2243 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2244 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002245
Eric Laurent81784c32012-11-19 14:55:58 -08002246 // force reconfiguration of effect chains and engines to take new buffer size and audio
2247 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002248 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002249 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2250 // matter.
2251 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2252 Vector< sp<EffectChain> > effectChains = mEffectChains;
2253 for (size_t i = 0; i < effectChains.size(); i ++) {
2254 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2255 }
2256}
2257
2258
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002259status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002260{
2261 if (halFrames == NULL || dspFrames == NULL) {
2262 return BAD_VALUE;
2263 }
2264 Mutex::Autolock _l(mLock);
2265 if (initCheck() != NO_ERROR) {
2266 return INVALID_OPERATION;
2267 }
2268 size_t framesWritten = mBytesWritten / mFrameSize;
2269 *halFrames = framesWritten;
2270
2271 if (isSuspended()) {
2272 // return an estimation of rendered frames when the output is suspended
2273 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
2274 *dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0;
2275 return NO_ERROR;
2276 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002277 status_t status;
2278 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002279 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002280 *dspFrames = (size_t)frames;
2281 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002282 }
2283}
2284
2285uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
2286{
2287 Mutex::Autolock _l(mLock);
2288 uint32_t result = 0;
2289 if (getEffectChain_l(sessionId) != 0) {
2290 result = EFFECT_SESSION;
2291 }
2292
2293 for (size_t i = 0; i < mTracks.size(); ++i) {
2294 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002295 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002296 result |= TRACK_SESSION;
2297 break;
2298 }
2299 }
2300
2301 return result;
2302}
2303
2304uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
2305{
2306 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2307 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2308 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2309 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2310 }
2311 for (size_t i = 0; i < mTracks.size(); i++) {
2312 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002313 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002314 return AudioSystem::getStrategyForStream(track->streamType());
2315 }
2316 }
2317 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2318}
2319
2320
Phil Burk062e67a2015-02-11 13:40:50 -08002321AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002322{
2323 Mutex::Autolock _l(mLock);
2324 return mOutput;
2325}
2326
Phil Burk062e67a2015-02-11 13:40:50 -08002327AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002328{
2329 Mutex::Autolock _l(mLock);
2330 AudioStreamOut *output = mOutput;
2331 mOutput = NULL;
2332 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2333 // must push a NULL and wait for ack
2334 mOutputSink.clear();
2335 mPipeSink.clear();
2336 mNormalSink.clear();
2337 return output;
2338}
2339
2340// this method must always be called either with ThreadBase mLock held or inside the thread loop
2341audio_stream_t* AudioFlinger::PlaybackThread::stream() const
2342{
2343 if (mOutput == NULL) {
2344 return NULL;
2345 }
2346 return &mOutput->stream->common;
2347}
2348
2349uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2350{
2351 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2352}
2353
2354status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2355{
2356 if (!isValidSyncEvent(event)) {
2357 return BAD_VALUE;
2358 }
2359
2360 Mutex::Autolock _l(mLock);
2361
2362 for (size_t i = 0; i < mTracks.size(); ++i) {
2363 sp<Track> track = mTracks[i];
2364 if (event->triggerSession() == track->sessionId()) {
2365 (void) track->setSyncEvent(event);
2366 return NO_ERROR;
2367 }
2368 }
2369
2370 return NAME_NOT_FOUND;
2371}
2372
2373bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2374{
2375 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2376}
2377
2378void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2379 const Vector< sp<Track> >& tracksToRemove)
2380{
2381 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002382 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002383 for (size_t i = 0 ; i < count ; i++) {
2384 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002385 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002386 AudioSystem::stopOutput(mId, track->streamType(),
2387 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002388#ifdef ADD_BATTERY_DATA
2389 // to track the speaker usage
2390 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2391#endif
2392 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002393 AudioSystem::releaseOutput(mId, track->streamType(),
2394 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002395 }
Eric Laurent81784c32012-11-19 14:55:58 -08002396 }
2397 }
2398 }
Eric Laurent81784c32012-11-19 14:55:58 -08002399}
2400
2401void AudioFlinger::PlaybackThread::checkSilentMode_l()
2402{
2403 if (!mMasterMute) {
2404 char value[PROPERTY_VALUE_MAX];
2405 if (property_get("ro.audio.silent", value, "0") > 0) {
2406 char *endptr;
2407 unsigned long ul = strtoul(value, &endptr, 0);
2408 if (*endptr == '\0' && ul != 0) {
2409 ALOGD("Silence is golden");
2410 // The setprop command will not allow a property to be changed after
2411 // the first time it is set, so we don't have to worry about un-muting.
2412 setMasterMute_l(true);
2413 }
2414 }
2415 }
2416}
2417
2418// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002419ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002420{
2421 // FIXME rewrite to reduce number of system calls
2422 mLastWriteTime = systemTime();
2423 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002424 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002425 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002426
2427 // If an NBAIO sink is present, use it to write the normal mixer's submix
2428 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002429
Andy Hung010a1a12014-03-13 13:57:33 -07002430 const size_t count = mBytesRemaining / mFrameSize;
2431
Simon Wilson2d590962012-11-29 15:18:50 -08002432 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002433 // update the setpoint when AudioFlinger::mScreenState changes
2434 uint32_t screenState = AudioFlinger::mScreenState;
2435 if (screenState != mScreenState) {
2436 mScreenState = screenState;
2437 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2438 if (pipe != NULL) {
2439 pipe->setAvgFrames((mScreenState & 1) ?
2440 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2441 }
2442 }
Andy Hung010a1a12014-03-13 13:57:33 -07002443 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002444 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002445 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002446 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002447 } else {
2448 bytesWritten = framesWritten;
2449 }
Glenn Kastenefaa7ab2014-08-20 08:48:54 -07002450 mLatchDValid = false;
Glenn Kasten767094d2013-08-23 13:51:43 -07002451 status_t status = mNormalSink->getTimestamp(mLatchD.mTimestamp);
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002452 if (status == NO_ERROR) {
2453 size_t totalFramesWritten = mNormalSink->framesWritten();
2454 if (totalFramesWritten >= mLatchD.mTimestamp.mPosition) {
2455 mLatchD.mUnpresentedFrames = totalFramesWritten - mLatchD.mTimestamp.mPosition;
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002456 // mLatchD.mFramesReleased is set immediately before D is clocked into Q
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002457 mLatchDValid = true;
2458 }
2459 }
Eric Laurent81784c32012-11-19 14:55:58 -08002460 // otherwise use the HAL / AudioStreamOut directly
2461 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002462 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002463
Eric Laurentbfb1b832013-01-07 09:53:42 -08002464 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002465 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2466 mWriteAckSequence += 2;
2467 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002468 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002469 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002470 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002471 // FIXME We should have an implementation of timestamps for direct output threads.
2472 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002473 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002474 if (mUseAsyncWrite &&
2475 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2476 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002477 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002478 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002479 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002480 }
Eric Laurent81784c32012-11-19 14:55:58 -08002481 }
2482
Eric Laurent81784c32012-11-19 14:55:58 -08002483 mNumWrites++;
2484 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002485 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002486 return bytesWritten;
2487}
2488
2489void AudioFlinger::PlaybackThread::threadLoop_drain()
2490{
2491 if (mOutput->stream->drain) {
2492 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2493 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002494 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2495 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002496 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002497 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002498 }
2499 mOutput->stream->drain(mOutput->stream,
2500 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
2501 : AUDIO_DRAIN_ALL);
2502 }
2503}
2504
2505void AudioFlinger::PlaybackThread::threadLoop_exit()
2506{
Eric Laurent275e8e92014-11-30 15:14:47 -08002507 {
2508 Mutex::Autolock _l(mLock);
2509 for (size_t i = 0; i < mTracks.size(); i++) {
2510 sp<Track> track = mTracks[i];
2511 track->invalidate();
2512 }
2513 }
Eric Laurent81784c32012-11-19 14:55:58 -08002514}
2515
2516/*
2517The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002518 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002519 - mActiveSleepTimeUs from activeSleepTimeUs()
2520 - mIdleSleepTimeUs from idleSleepTimeUs()
2521 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only)
Eric Laurent81784c32012-11-19 14:55:58 -08002522 - maxPeriod from frame count and sample rate (MIXER only)
2523
2524The parameters that affect these derived values are:
2525 - frame count
2526 - frame size
2527 - sample rate
2528 - device type: A2DP or not
2529 - device latency
2530 - format: PCM or not
2531 - active sleep time
2532 - idle sleep time
2533*/
2534
2535void AudioFlinger::PlaybackThread::cacheParameters_l()
2536{
Andy Hung25c2dac2014-02-27 14:56:00 -08002537 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002538 mActiveSleepTimeUs = activeSleepTimeUs();
2539 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent81784c32012-11-19 14:55:58 -08002540}
2541
2542void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2543{
Glenn Kasten7c027242012-12-26 14:43:16 -08002544 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurent81784c32012-11-19 14:55:58 -08002545 this, streamType, mTracks.size());
2546 Mutex::Autolock _l(mLock);
2547
2548 size_t size = mTracks.size();
2549 for (size_t i = 0; i < size; i++) {
2550 sp<Track> t = mTracks[i];
2551 if (t->streamType() == streamType) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002552 t->invalidate();
Eric Laurent81784c32012-11-19 14:55:58 -08002553 }
2554 }
2555}
2556
2557status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2558{
2559 int session = chain->sessionId();
Andy Hung010a1a12014-03-13 13:57:33 -07002560 int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled
2561 ? mEffectBuffer : mSinkBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002562 bool ownsBuffer = false;
2563
2564 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
2565 if (session > 0) {
2566 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002567 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002568 if (mType != DIRECT) {
2569 size_t numSamples = mNormalFrameCount * mChannelCount;
2570 buffer = new int16_t[numSamples];
2571 memset(buffer, 0, numSamples * sizeof(int16_t));
2572 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2573 ownsBuffer = true;
2574 }
2575
2576 // Attach all tracks with same session ID to this chain.
2577 for (size_t i = 0; i < mTracks.size(); ++i) {
2578 sp<Track> track = mTracks[i];
2579 if (session == track->sessionId()) {
2580 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2581 buffer);
2582 track->setMainBuffer(buffer);
2583 chain->incTrackCnt();
2584 }
2585 }
2586
2587 // indicate all active tracks in the chain
2588 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2589 sp<Track> track = mActiveTracks[i].promote();
2590 if (track == 0) {
2591 continue;
2592 }
2593 if (session == track->sessionId()) {
2594 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2595 chain->incActiveTrackCnt();
2596 }
2597 }
2598 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002599 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08002600 chain->setInBuffer(buffer, ownsBuffer);
Andy Hung010a1a12014-03-13 13:57:33 -07002601 chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled
2602 ? mEffectBuffer : mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002603 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
2604 // chains list in order to be processed last as it contains output stage effects
2605 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2606 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
2607 // after track specific effects and before output stage
2608 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
2609 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
2610 // Effect chain for other sessions are inserted at beginning of effect
2611 // chains list to be processed before output mix effects. Relative order between other
2612 // sessions is not important
2613 size_t size = mEffectChains.size();
2614 size_t i = 0;
2615 for (i = 0; i < size; i++) {
2616 if (mEffectChains[i]->sessionId() < session) {
2617 break;
2618 }
2619 }
2620 mEffectChains.insertAt(chain, i);
2621 checkSuspendOnAddEffectChain_l(chain);
2622
2623 return NO_ERROR;
2624}
2625
2626size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2627{
2628 int session = chain->sessionId();
2629
2630 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2631
2632 for (size_t i = 0; i < mEffectChains.size(); i++) {
2633 if (chain == mEffectChains[i]) {
2634 mEffectChains.removeAt(i);
2635 // detach all active tracks from the chain
2636 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2637 sp<Track> track = mActiveTracks[i].promote();
2638 if (track == 0) {
2639 continue;
2640 }
2641 if (session == track->sessionId()) {
2642 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2643 chain.get(), session);
2644 chain->decActiveTrackCnt();
2645 }
2646 }
2647
2648 // detach all tracks with same session ID from this chain
2649 for (size_t i = 0; i < mTracks.size(); ++i) {
2650 sp<Track> track = mTracks[i];
2651 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002652 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002653 chain->decTrackCnt();
2654 }
2655 }
2656 break;
2657 }
2658 }
2659 return mEffectChains.size();
2660}
2661
2662status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2663 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2664{
2665 Mutex::Autolock _l(mLock);
2666 return attachAuxEffect_l(track, EffectId);
2667}
2668
2669status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2670 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2671{
2672 status_t status = NO_ERROR;
2673
2674 if (EffectId == 0) {
2675 track->setAuxBuffer(0, NULL);
2676 } else {
2677 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2678 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2679 if (effect != 0) {
2680 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2681 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2682 } else {
2683 status = INVALID_OPERATION;
2684 }
2685 } else {
2686 status = BAD_VALUE;
2687 }
2688 }
2689 return status;
2690}
2691
2692void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2693{
2694 for (size_t i = 0; i < mTracks.size(); ++i) {
2695 sp<Track> track = mTracks[i];
2696 if (track->auxEffectId() == effectId) {
2697 attachAuxEffect_l(track, 0);
2698 }
2699 }
2700}
2701
2702bool AudioFlinger::PlaybackThread::threadLoop()
2703{
2704 Vector< sp<Track> > tracksToRemove;
2705
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002706 mStandbyTimeNs = systemTime();
Eric Laurent81784c32012-11-19 14:55:58 -08002707
2708 // MIXER
2709 nsecs_t lastWarning = 0;
2710
2711 // DUPLICATING
2712 // FIXME could this be made local to while loop?
2713 writeFrames = 0;
2714
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002715 int lastGeneration = 0;
2716
Eric Laurent81784c32012-11-19 14:55:58 -08002717 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002718 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08002719
2720 if (mType == MIXER) {
2721 sleepTimeShift = 0;
2722 }
2723
2724 CpuStats cpuStats;
2725 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2726
2727 acquireWakeLock();
2728
Glenn Kasten9e58b552013-01-18 15:09:48 -08002729 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2730 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2731 // and then that string will be logged at the next convenient opportunity.
2732 const char *logString = NULL;
2733
Eric Laurent664539d2013-09-23 18:24:31 -07002734 checkSilentMode_l();
2735
Eric Laurent81784c32012-11-19 14:55:58 -08002736 while (!exitPending())
2737 {
2738 cpuStats.sample(myName);
2739
2740 Vector< sp<EffectChain> > effectChains;
2741
Eric Laurent81784c32012-11-19 14:55:58 -08002742 { // scope for mLock
2743
2744 Mutex::Autolock _l(mLock);
2745
Eric Laurent021cf962014-05-13 10:18:14 -07002746 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07002747
Glenn Kasten9e58b552013-01-18 15:09:48 -08002748 if (logString != NULL) {
2749 mNBLogWriter->logTimestamp();
2750 mNBLogWriter->log(logString);
2751 logString = NULL;
2752 }
2753
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002754 // Gather the framesReleased counters for all active tracks,
2755 // and latch them atomically with the timestamp.
2756 // FIXME We're using raw pointers as indices. A unique track ID would be a better index.
2757 mLatchD.mFramesReleased.clear();
2758 size_t size = mActiveTracks.size();
2759 for (size_t i = 0; i < size; i++) {
2760 sp<Track> t = mActiveTracks[i].promote();
2761 if (t != 0) {
2762 mLatchD.mFramesReleased.add(t.get(),
2763 t->mAudioTrackServerProxy->framesReleased());
2764 }
2765 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002766 if (mLatchDValid) {
2767 mLatchQ = mLatchD;
2768 mLatchDValid = false;
2769 mLatchQValid = true;
2770 }
2771
Eric Laurent81784c32012-11-19 14:55:58 -08002772 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002773 if (mSignalPending) {
2774 // A signal was raised while we were unlocked
2775 mSignalPending = false;
2776 } else if (waitingAsyncCallback_l()) {
2777 if (exitPending()) {
2778 break;
2779 }
Marco Nelissen078538c2015-05-12 09:17:57 -07002780 bool released = false;
2781 // The following works around a bug in the offload driver. Ideally we would release
2782 // the wake lock every time, but that causes the last offload buffer(s) to be
2783 // dropped while the device is on battery, so we need to hold a wake lock during
2784 // the drain phase.
2785 if (mBytesRemaining && !(mDrainSequence & 1)) {
2786 releaseWakeLock_l();
2787 released = true;
2788 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002789 mWakeLockUids.clear();
2790 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002791 ALOGV("wait async completion");
2792 mWaitWorkCV.wait(mLock);
2793 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07002794 if (released) {
2795 acquireWakeLock_l();
2796 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002797 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
2798 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002799
2800 continue;
2801 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002802 if ((!mActiveTracks.size() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08002803 isSuspended()) {
2804 // put audio hardware into standby after short delay
2805 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002806
2807 threadLoop_standby();
2808
2809 mStandby = true;
2810 }
2811
2812 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2813 // we're about to wait, flush the binder command buffer
2814 IPCThreadState::self()->flushCommands();
2815
2816 clearOutputTracks();
2817
2818 if (exitPending()) {
2819 break;
2820 }
2821
2822 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002823 mWakeLockUids.clear();
2824 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002825 // wait until we have something to do...
2826 ALOGV("%s going to sleep", myName.string());
2827 mWaitWorkCV.wait(mLock);
2828 ALOGV("%s waking up", myName.string());
2829 acquireWakeLock_l();
2830
2831 mMixerStatus = MIXER_IDLE;
2832 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2833 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002834 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002835 checkSilentMode_l();
2836
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002837 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
2838 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08002839 if (mType == MIXER) {
2840 sleepTimeShift = 0;
2841 }
2842
2843 continue;
2844 }
2845 }
Eric Laurent81784c32012-11-19 14:55:58 -08002846 // mMixerStatusIgnoringFastTracks is also updated internally
2847 mMixerStatus = prepareTracks_l(&tracksToRemove);
2848
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002849 // compare with previously applied list
2850 if (lastGeneration != mActiveTracksGeneration) {
2851 // update wakelock
2852 updateWakeLockUids_l(mWakeLockUids);
2853 lastGeneration = mActiveTracksGeneration;
2854 }
2855
Eric Laurent81784c32012-11-19 14:55:58 -08002856 // prevent any changes in effect chain list and in each effect chain
2857 // during mixing and effect process as the audio buffers could be deleted
2858 // or modified if an effect is created or deleted
2859 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002860 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08002861
Eric Laurentbfb1b832013-01-07 09:53:42 -08002862 if (mBytesRemaining == 0) {
2863 mCurrentWriteLength = 0;
2864 if (mMixerStatus == MIXER_TRACKS_READY) {
2865 // threadLoop_mix() sets mCurrentWriteLength
2866 threadLoop_mix();
2867 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
2868 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002869 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08002870 // must be written to HAL
2871 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002872 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08002873 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002874 }
2875 }
Andy Hung98ef9782014-03-04 14:46:50 -08002876 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002877 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08002878 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
2879 // or mSinkBuffer (if there are no effects).
2880 //
2881 // This is done pre-effects computation; if effects change to
2882 // support higher precision, this needs to move.
2883 //
2884 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002885 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08002886 if (mMixerBufferValid) {
2887 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
2888 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
2889
2890 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
2891 mNormalFrameCount * mChannelCount);
2892 }
2893
Eric Laurentbfb1b832013-01-07 09:53:42 -08002894 mBytesRemaining = mCurrentWriteLength;
2895 if (isSuspended()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002896 mSleepTimeUs = suspendSleepTimeUs();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002897 // simulate write to HAL when suspended
Andy Hung25c2dac2014-02-27 14:56:00 -08002898 mBytesWritten += mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002899 mBytesRemaining = 0;
2900 }
Eric Laurent81784c32012-11-19 14:55:58 -08002901
Eric Laurentbfb1b832013-01-07 09:53:42 -08002902 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002903 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002904 for (size_t i = 0; i < effectChains.size(); i ++) {
2905 effectChains[i]->process_l();
2906 }
Eric Laurent81784c32012-11-19 14:55:58 -08002907 }
2908 }
Eric Laurent59fe0102013-09-27 18:48:26 -07002909 // Process effect chains for offloaded thread even if no audio
2910 // was read from audio track: process only updates effect state
2911 // and thus does have to be synchronized with audio writes but may have
2912 // to be called while waiting for async write callback
2913 if (mType == OFFLOAD) {
2914 for (size_t i = 0; i < effectChains.size(); i ++) {
2915 effectChains[i]->process_l();
2916 }
2917 }
Eric Laurent81784c32012-11-19 14:55:58 -08002918
Andy Hung98ef9782014-03-04 14:46:50 -08002919 // Only if the Effects buffer is enabled and there is data in the
2920 // Effects buffer (buffer valid), we need to
2921 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002922 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08002923 if (mEffectBufferValid) {
2924 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
2925 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
2926 mNormalFrameCount * mChannelCount);
2927 }
2928
Eric Laurent81784c32012-11-19 14:55:58 -08002929 // enable changes in effect chain
2930 unlockEffectChains(effectChains);
2931
Eric Laurentbfb1b832013-01-07 09:53:42 -08002932 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002933 // mSleepTimeUs == 0 means we must write to audio hardware
2934 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07002935 ssize_t ret = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002936 if (mBytesRemaining) {
Andy Hung08fb1742015-05-31 23:22:10 -07002937 ret = threadLoop_write();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002938 if (ret < 0) {
2939 mBytesRemaining = 0;
2940 } else {
2941 mBytesWritten += ret;
2942 mBytesRemaining -= ret;
2943 }
2944 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
2945 (mMixerStatus == MIXER_DRAIN_ALL)) {
2946 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08002947 }
Andy Hung08fb1742015-05-31 23:22:10 -07002948 if (mType == MIXER && !mStandby) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07002949 // write blocked detection
2950 nsecs_t now = systemTime();
2951 nsecs_t delta = now - mLastWriteTime;
Andy Hung08fb1742015-05-31 23:22:10 -07002952 if (delta > maxPeriod) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07002953 mNumDelayedWrites++;
2954 if ((now - lastWarning) > kWarningThrottleNs) {
2955 ATRACE_NAME("underrun");
2956 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2957 ns2ms(delta), mNumDelayedWrites, this);
2958 lastWarning = now;
2959 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002960 }
Andy Hung08fb1742015-05-31 23:22:10 -07002961
2962 if (mThreadThrottle
2963 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
2964 && ret > 0) { // we wrote something
2965 // Limit MixerThread data processing to no more than twice the
2966 // expected processing rate.
2967 //
2968 // This helps prevent underruns with NuPlayer and other applications
2969 // which may set up buffers that are close to the minimum size, or use
2970 // deep buffers, and rely on a double-buffering sleep strategy to fill.
2971 //
2972 // The throttle smooths out sudden large data drains from the device,
2973 // e.g. when it comes out of standby, which often causes problems with
2974 // (1) mixer threads without a fast mixer (which has its own warm-up)
2975 // (2) minimum buffer sized tracks (even if the track is full,
2976 // the app won't fill fast enough to handle the sudden draw).
2977
2978 const int32_t deltaMs = delta / 1000000;
2979 const int32_t throttleMs = mHalfBufferMs - deltaMs;
2980 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
2981 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07002982 // notify of throttle start on verbose log
2983 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
2984 "mixer(%p) throttle begin:"
2985 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07002986 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07002987 mThreadThrottleTimeMs += throttleMs;
2988 } else {
2989 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
2990 if (diff > 0) {
2991 // notify of throttle end on debug log
2992 ALOGD("mixer(%p) throttle end: throttle time(%u)", this, diff);
2993 mThreadThrottleEndMs = mThreadThrottleTimeMs;
2994 }
Andy Hung08fb1742015-05-31 23:22:10 -07002995 }
2996 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002997 }
Eric Laurent81784c32012-11-19 14:55:58 -08002998
Eric Laurentbfb1b832013-01-07 09:53:42 -08002999 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003000 ATRACE_BEGIN("sleep");
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003001 usleep(mSleepTimeUs);
Glenn Kastene7754022014-10-31 12:11:26 -07003002 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003003 }
Eric Laurent81784c32012-11-19 14:55:58 -08003004 }
3005
3006 // Finally let go of removed track(s), without the lock held
3007 // since we can't guarantee the destructors won't acquire that
3008 // same lock. This will also mutate and push a new fast mixer state.
3009 threadLoop_removeTracks(tracksToRemove);
3010 tracksToRemove.clear();
3011
3012 // FIXME I don't understand the need for this here;
3013 // it was in the original code but maybe the
3014 // assignment in saveOutputTracks() makes this unnecessary?
3015 clearOutputTracks();
3016
3017 // Effect chains will be actually deleted here if they were removed from
3018 // mEffectChains list during mixing or effects processing
3019 effectChains.clear();
3020
3021 // FIXME Note that the above .clear() is no longer necessary since effectChains
3022 // is now local to this block, but will keep it for now (at least until merge done).
3023 }
3024
Eric Laurentbfb1b832013-01-07 09:53:42 -08003025 threadLoop_exit();
3026
Eric Laurentcf817a22014-08-04 20:36:31 -07003027 if (!mStandby) {
3028 threadLoop_standby();
3029 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003030 }
3031
3032 releaseWakeLock();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003033 mWakeLockUids.clear();
3034 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08003035
3036 ALOGV("Thread %p type %d exiting", this, mType);
3037 return false;
3038}
3039
Eric Laurentbfb1b832013-01-07 09:53:42 -08003040// removeTracks_l() must be called with ThreadBase::mLock held
3041void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3042{
3043 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07003044 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003045 for (size_t i=0 ; i<count ; i++) {
3046 const sp<Track>& track = tracksToRemove.itemAt(i);
3047 mActiveTracks.remove(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003048 mWakeLockUids.remove(track->uid());
3049 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003050 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
3051 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3052 if (chain != 0) {
3053 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
3054 track->sessionId());
3055 chain->decActiveTrackCnt();
3056 }
3057 if (track->isTerminated()) {
3058 removeTrack_l(track);
3059 }
3060 }
3061 }
3062
3063}
Eric Laurent81784c32012-11-19 14:55:58 -08003064
Eric Laurentaccc1472013-09-20 09:36:34 -07003065status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3066{
3067 if (mNormalSink != 0) {
3068 return mNormalSink->getTimestamp(timestamp);
3069 }
Andy Hung9a1c8892014-12-03 11:37:42 -08003070 if ((mType == OFFLOAD || mType == DIRECT)
3071 && mOutput != NULL && mOutput->stream->get_presentation_position) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003072 uint64_t position64;
Phil Burk062e67a2015-02-11 13:40:50 -08003073 int ret = mOutput->getPresentationPosition(&position64, &timestamp.mTime);
Eric Laurentaccc1472013-09-20 09:36:34 -07003074 if (ret == 0) {
3075 timestamp.mPosition = (uint32_t)position64;
3076 return NO_ERROR;
3077 }
3078 }
3079 return INVALID_OPERATION;
3080}
Eric Laurent1c333e22014-05-20 10:48:17 -07003081
Eric Laurent054d9d32015-04-24 08:48:48 -07003082status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
3083 audio_patch_handle_t *handle)
3084{
3085 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3086 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3087 if (mFastMixer != 0) {
3088 FastMixerStateQueue *sq = mFastMixer->sq();
3089 FastMixerState *state = sq->begin();
3090 if (!(state->mCommand & FastMixerState::IDLE)) {
3091 previousCommand = state->mCommand;
3092 state->mCommand = FastMixerState::HOT_IDLE;
3093 sq->end();
3094 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3095 } else {
3096 sq->end(false /*didModify*/);
3097 }
3098 }
3099 status_t status = PlaybackThread::createAudioPatch_l(patch, handle);
3100
3101 if (!(previousCommand & FastMixerState::IDLE)) {
3102 ALOG_ASSERT(mFastMixer != 0);
3103 FastMixerStateQueue *sq = mFastMixer->sq();
3104 FastMixerState *state = sq->begin();
3105 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3106 state->mCommand = previousCommand;
3107 sq->end();
3108 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3109 }
3110
3111 return status;
3112}
3113
Eric Laurent1c333e22014-05-20 10:48:17 -07003114status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3115 audio_patch_handle_t *handle)
3116{
3117 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003118
3119 // store new device and send to effects
3120 audio_devices_t type = AUDIO_DEVICE_NONE;
3121 for (unsigned int i = 0; i < patch->num_sinks; i++) {
3122 type |= patch->sinks[i].ext.device.type;
3123 }
3124
3125#ifdef ADD_BATTERY_DATA
3126 // when changing the audio output device, call addBatteryData to notify
3127 // the change
3128 if (mOutDevice != type) {
3129 uint32_t params = 0;
3130 // check whether speaker is on
3131 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3132 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003133 }
3134
Eric Laurent054d9d32015-04-24 08:48:48 -07003135 audio_devices_t deviceWithoutSpeaker
3136 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3137 // check if any other device (except speaker) is on
3138 if (type & deviceWithoutSpeaker) {
3139 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3140 }
3141
3142 if (params != 0) {
3143 addBatteryData(params);
3144 }
3145 }
3146#endif
3147
3148 for (size_t i = 0; i < mEffectChains.size(); i++) {
3149 mEffectChains[i]->setDevice_l(type);
3150 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003151
3152 // mPrevOutDevice is the latest device set by createAudioPatch_l(). It is not set when
3153 // the thread is created so that the first patch creation triggers an ioConfigChanged callback
3154 bool configChanged = mPrevOutDevice != type;
Eric Laurent054d9d32015-04-24 08:48:48 -07003155 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003156 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003157
3158 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003159 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
3160 status = hwDevice->create_audio_patch(hwDevice,
3161 patch->num_sources,
3162 patch->sources,
3163 patch->num_sinks,
3164 patch->sinks,
3165 handle);
3166 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003167 char *address;
3168 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3169 //FIXME: we only support address on first sink with HAL version < 3.0
3170 address = audio_device_address_to_parameter(
3171 patch->sinks[0].ext.device.type,
3172 patch->sinks[0].ext.device.address);
3173 } else {
3174 address = (char *)calloc(1, 1);
3175 }
3176 AudioParameter param = AudioParameter(String8(address));
3177 free(address);
3178 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), (int)type);
3179 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3180 param.toString().string());
3181 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003182 }
Eric Laurente8726fe2015-06-26 09:39:24 -07003183 if (configChanged) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003184 mPrevOutDevice = type;
Eric Laurente8726fe2015-06-26 09:39:24 -07003185 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
3186 }
Eric Laurent1c333e22014-05-20 10:48:17 -07003187 return status;
3188}
3189
Eric Laurent054d9d32015-04-24 08:48:48 -07003190status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3191{
3192 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3193 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3194 if (mFastMixer != 0) {
3195 FastMixerStateQueue *sq = mFastMixer->sq();
3196 FastMixerState *state = sq->begin();
3197 if (!(state->mCommand & FastMixerState::IDLE)) {
3198 previousCommand = state->mCommand;
3199 state->mCommand = FastMixerState::HOT_IDLE;
3200 sq->end();
3201 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3202 } else {
3203 sq->end(false /*didModify*/);
3204 }
3205 }
3206
3207 status_t status = PlaybackThread::releaseAudioPatch_l(handle);
3208
3209 if (!(previousCommand & FastMixerState::IDLE)) {
3210 ALOG_ASSERT(mFastMixer != 0);
3211 FastMixerStateQueue *sq = mFastMixer->sq();
3212 FastMixerState *state = sq->begin();
3213 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3214 state->mCommand = previousCommand;
3215 sq->end();
3216 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3217 }
3218
3219 return status;
3220}
3221
Eric Laurent1c333e22014-05-20 10:48:17 -07003222status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3223{
3224 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003225
3226 mOutDevice = AUDIO_DEVICE_NONE;
3227
Eric Laurent1c333e22014-05-20 10:48:17 -07003228 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
3229 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
3230 status = hwDevice->release_audio_patch(hwDevice, handle);
3231 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003232 AudioParameter param;
3233 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
3234 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3235 param.toString().string());
Eric Laurent1c333e22014-05-20 10:48:17 -07003236 }
3237 return status;
3238}
3239
Eric Laurent83b88082014-06-20 18:31:16 -07003240void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3241{
3242 Mutex::Autolock _l(mLock);
3243 mTracks.add(track);
3244}
3245
3246void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3247{
3248 Mutex::Autolock _l(mLock);
3249 destroyTrack_l(track);
3250}
3251
3252void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
3253{
3254 ThreadBase::getAudioPortConfig(config);
3255 config->role = AUDIO_PORT_ROLE_SOURCE;
3256 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3257 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
3258}
3259
Eric Laurent81784c32012-11-19 14:55:58 -08003260// ----------------------------------------------------------------------------
3261
3262AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurent72e3f392015-05-20 14:43:50 -07003263 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
3264 : PlaybackThread(audioFlinger, output, id, device, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08003265 // mAudioMixer below
3266 // mFastMixer below
3267 mFastMixerFutex(0)
3268 // mOutputSink below
3269 // mPipeSink below
3270 // mNormalSink below
3271{
3272 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07003273 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, "
Eric Laurent81784c32012-11-19 14:55:58 -08003274 "mFrameCount=%d, mNormalFrameCount=%d",
3275 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3276 mNormalFrameCount);
3277 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3278
Andy Hungfbfc3952015-01-15 13:33:51 -08003279 if (type == DUPLICATING) {
3280 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3281 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3282 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3283 return;
3284 }
Eric Laurent81784c32012-11-19 14:55:58 -08003285 // create an NBAIO sink for the HAL output stream, and negotiate
3286 mOutputSink = new AudioStreamOutSink(output->stream);
3287 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003288 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Eric Laurent81784c32012-11-19 14:55:58 -08003289 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
3290 ALOG_ASSERT(index == 0);
3291
3292 // initialize fast mixer depending on configuration
3293 bool initFastMixer;
3294 switch (kUseFastMixer) {
3295 case FastMixer_Never:
3296 initFastMixer = false;
3297 break;
3298 case FastMixer_Always:
3299 initFastMixer = true;
3300 break;
3301 case FastMixer_Static:
3302 case FastMixer_Dynamic:
3303 initFastMixer = mFrameCount < mNormalFrameCount;
3304 break;
3305 }
3306 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003307 audio_format_t fastMixerFormat;
3308 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3309 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3310 } else {
3311 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3312 }
3313 if (mFormat != fastMixerFormat) {
3314 // change our Sink format to accept our intermediate precision
3315 mFormat = fastMixerFormat;
3316 free(mSinkBuffer);
3317 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3318 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3319 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3320 }
Eric Laurent81784c32012-11-19 14:55:58 -08003321
3322 // create a MonoPipe to connect our submix to FastMixer
3323 NBAIO_Format format = mOutputSink->format();
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003324 NBAIO_Format origformat = format;
Andy Hung1258c1a2014-05-23 21:22:17 -07003325 // adjust format to match that of the Fast Mixer
Glenn Kasten97b7b752014-09-28 13:04:24 -07003326 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003327 format.mFormat = fastMixerFormat;
3328 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3329
Eric Laurent81784c32012-11-19 14:55:58 -08003330 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3331 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3332 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3333 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3334 const NBAIO_Format offers[1] = {format};
3335 size_t numCounterOffers = 0;
3336 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
3337 ALOG_ASSERT(index == 0);
3338 monoPipe->setAvgFrames((mScreenState & 1) ?
3339 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3340 mPipeSink = monoPipe;
3341
Glenn Kasten46909e72013-02-26 09:20:22 -08003342#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08003343 if (mTeeSinkOutputEnabled) {
3344 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003345 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
3346 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08003347 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003348 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003349 ALOG_ASSERT(index == 0);
3350 mTeeSink = teeSink;
3351 PipeReader *teeSource = new PipeReader(*teeSink);
3352 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003353 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003354 ALOG_ASSERT(index == 0);
3355 mTeeSource = teeSource;
3356 }
Glenn Kasten46909e72013-02-26 09:20:22 -08003357#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003358
3359 // create fast mixer and configure it initially with just one fast track for our submix
3360 mFastMixer = new FastMixer();
3361 FastMixerStateQueue *sq = mFastMixer->sq();
3362#ifdef STATE_QUEUE_DUMP
3363 sq->setObserverDump(&mStateQueueObserverDump);
3364 sq->setMutatorDump(&mStateQueueMutatorDump);
3365#endif
3366 FastMixerState *state = sq->begin();
3367 FastTrack *fastTrack = &state->mFastTracks[0];
3368 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3369 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3370 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003371 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3372 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003373 fastTrack->mGeneration++;
3374 state->mFastTracksGen++;
3375 state->mTrackMask = 1;
3376 // fast mixer will use the HAL output sink
3377 state->mOutputSink = mOutputSink.get();
3378 state->mOutputSinkGen++;
3379 state->mFrameCount = mFrameCount;
3380 state->mCommand = FastMixerState::COLD_IDLE;
3381 // already done in constructor initialization list
3382 //mFastMixerFutex = 0;
3383 state->mColdFutexAddr = &mFastMixerFutex;
3384 state->mColdGen++;
3385 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08003386#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003387 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08003388#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08003389 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3390 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003391 sq->end();
3392 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3393
3394 // start the fast mixer
3395 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3396 pid_t tid = mFastMixer->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003397 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003398
3399#ifdef AUDIO_WATCHDOG
3400 // create and start the watchdog
3401 mAudioWatchdog = new AudioWatchdog();
3402 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3403 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3404 tid = mAudioWatchdog->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003405 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003406#endif
3407
Eric Laurent81784c32012-11-19 14:55:58 -08003408 }
3409
3410 switch (kUseFastMixer) {
3411 case FastMixer_Never:
3412 case FastMixer_Dynamic:
3413 mNormalSink = mOutputSink;
3414 break;
3415 case FastMixer_Always:
3416 mNormalSink = mPipeSink;
3417 break;
3418 case FastMixer_Static:
3419 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3420 break;
3421 }
3422}
3423
3424AudioFlinger::MixerThread::~MixerThread()
3425{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003426 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003427 FastMixerStateQueue *sq = mFastMixer->sq();
3428 FastMixerState *state = sq->begin();
3429 if (state->mCommand == FastMixerState::COLD_IDLE) {
3430 int32_t old = android_atomic_inc(&mFastMixerFutex);
3431 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003432 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003433 }
3434 }
3435 state->mCommand = FastMixerState::EXIT;
3436 sq->end();
3437 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3438 mFastMixer->join();
3439 // Though the fast mixer thread has exited, it's state queue is still valid.
3440 // We'll use that extract the final state which contains one remaining fast track
3441 // corresponding to our sub-mix.
3442 state = sq->begin();
3443 ALOG_ASSERT(state->mTrackMask == 1);
3444 FastTrack *fastTrack = &state->mFastTracks[0];
3445 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3446 delete fastTrack->mBufferProvider;
3447 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003448 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003449#ifdef AUDIO_WATCHDOG
3450 if (mAudioWatchdog != 0) {
3451 mAudioWatchdog->requestExit();
3452 mAudioWatchdog->requestExitAndWait();
3453 mAudioWatchdog.clear();
3454 }
3455#endif
3456 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003457 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003458 delete mAudioMixer;
3459}
3460
3461
3462uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3463{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003464 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003465 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3466 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3467 }
3468 return latency;
3469}
3470
3471
3472void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3473{
3474 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3475}
3476
Eric Laurentbfb1b832013-01-07 09:53:42 -08003477ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003478{
3479 // FIXME we should only do one push per cycle; confirm this is true
3480 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003481 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003482 FastMixerStateQueue *sq = mFastMixer->sq();
3483 FastMixerState *state = sq->begin();
3484 if (state->mCommand != FastMixerState::MIX_WRITE &&
3485 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3486 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07003487
3488 // FIXME workaround for first HAL write being CPU bound on some devices
3489 ATRACE_BEGIN("write");
3490 mOutput->write((char *)mSinkBuffer, 0);
3491 ATRACE_END();
3492
Eric Laurent81784c32012-11-19 14:55:58 -08003493 int32_t old = android_atomic_inc(&mFastMixerFutex);
3494 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003495 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003496 }
3497#ifdef AUDIO_WATCHDOG
3498 if (mAudioWatchdog != 0) {
3499 mAudioWatchdog->resume();
3500 }
3501#endif
3502 }
3503 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08003504#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003505 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08003506 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08003507#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003508 sq->end();
3509 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3510 if (kUseFastMixer == FastMixer_Dynamic) {
3511 mNormalSink = mPipeSink;
3512 }
3513 } else {
3514 sq->end(false /*didModify*/);
3515 }
3516 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003517 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003518}
3519
3520void AudioFlinger::MixerThread::threadLoop_standby()
3521{
3522 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003523 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003524 FastMixerStateQueue *sq = mFastMixer->sq();
3525 FastMixerState *state = sq->begin();
3526 if (!(state->mCommand & FastMixerState::IDLE)) {
3527 state->mCommand = FastMixerState::COLD_IDLE;
3528 state->mColdFutexAddr = &mFastMixerFutex;
3529 state->mColdGen++;
3530 mFastMixerFutex = 0;
3531 sq->end();
3532 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3533 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3534 if (kUseFastMixer == FastMixer_Dynamic) {
3535 mNormalSink = mOutputSink;
3536 }
3537#ifdef AUDIO_WATCHDOG
3538 if (mAudioWatchdog != 0) {
3539 mAudioWatchdog->pause();
3540 }
3541#endif
3542 } else {
3543 sq->end(false /*didModify*/);
3544 }
3545 }
3546 PlaybackThread::threadLoop_standby();
3547}
3548
Eric Laurentbfb1b832013-01-07 09:53:42 -08003549bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3550{
3551 return false;
3552}
3553
3554bool AudioFlinger::PlaybackThread::shouldStandby_l()
3555{
3556 return !mStandby;
3557}
3558
3559bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3560{
3561 Mutex::Autolock _l(mLock);
3562 return waitingAsyncCallback_l();
3563}
3564
Eric Laurent81784c32012-11-19 14:55:58 -08003565// shared by MIXER and DIRECT, overridden by DUPLICATING
3566void AudioFlinger::PlaybackThread::threadLoop_standby()
3567{
3568 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08003569 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003570 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003571 // discard any pending drain or write ack by incrementing sequence
3572 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3573 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003574 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003575 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3576 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003577 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003578 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003579}
3580
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003581void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3582{
3583 ALOGV("signal playback thread");
3584 broadcast_l();
3585}
3586
Eric Laurent81784c32012-11-19 14:55:58 -08003587void AudioFlinger::MixerThread::threadLoop_mix()
3588{
3589 // obtain the presentation timestamp of the next output buffer
3590 int64_t pts;
3591 status_t status = INVALID_OPERATION;
3592
3593 if (mNormalSink != 0) {
3594 status = mNormalSink->getNextWriteTimestamp(&pts);
3595 } else {
3596 status = mOutputSink->getNextWriteTimestamp(&pts);
3597 }
3598
3599 if (status != NO_ERROR) {
3600 pts = AudioBufferProvider::kInvalidPTS;
3601 }
3602
3603 // mix buffers...
3604 mAudioMixer->process(pts);
Andy Hung25c2dac2014-02-27 14:56:00 -08003605 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003606 // increase sleep time progressively when application underrun condition clears.
3607 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3608 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3609 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003610 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003611 sleepTimeShift--;
3612 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003613 mSleepTimeUs = 0;
3614 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08003615 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003616
Eric Laurent81784c32012-11-19 14:55:58 -08003617}
3618
3619void AudioFlinger::MixerThread::threadLoop_sleepTime()
3620{
3621 // If no tracks are ready, sleep once for the duration of an output
3622 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003623 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003624 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003625 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
3626 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
3627 mSleepTimeUs = kMinThreadSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003628 }
3629 // reduce sleep time in case of consecutive application underruns to avoid
3630 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3631 // duration we would end up writing less data than needed by the audio HAL if
3632 // the condition persists.
3633 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3634 sleepTimeShift++;
3635 }
3636 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003637 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003638 }
3639 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003640 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3641 // before effects processing or output.
3642 if (mMixerBufferValid) {
3643 memset(mMixerBuffer, 0, mMixerBufferSize);
3644 } else {
3645 memset(mSinkBuffer, 0, mSinkBufferSize);
3646 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003647 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003648 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3649 "anticipated start");
3650 }
3651 // TODO add standby time extension fct of effect tail
3652}
3653
3654// prepareTracks_l() must be called with ThreadBase::mLock held
3655AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3656 Vector< sp<Track> > *tracksToRemove)
3657{
3658
3659 mixer_state mixerStatus = MIXER_IDLE;
3660 // find out which tracks need to be processed
3661 size_t count = mActiveTracks.size();
3662 size_t mixedTracks = 0;
3663 size_t tracksWithEffect = 0;
3664 // counts only _active_ fast tracks
3665 size_t fastTracks = 0;
3666 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
3667
3668 float masterVolume = mMasterVolume;
3669 bool masterMute = mMasterMute;
3670
3671 if (masterMute) {
3672 masterVolume = 0;
3673 }
3674 // Delegate master volume control to effect in output mix effect chain if needed
3675 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3676 if (chain != 0) {
3677 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
3678 chain->setVolume_l(&v, &v);
3679 masterVolume = (float)((v + (1 << 23)) >> 24);
3680 chain.clear();
3681 }
3682
3683 // prepare a new state to push
3684 FastMixerStateQueue *sq = NULL;
3685 FastMixerState *state = NULL;
3686 bool didModify = false;
3687 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003688 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003689 sq = mFastMixer->sq();
3690 state = sq->begin();
3691 }
3692
Andy Hung69aed5f2014-02-25 17:24:40 -08003693 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08003694 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08003695
Eric Laurent81784c32012-11-19 14:55:58 -08003696 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003697 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003698 if (t == 0) {
3699 continue;
3700 }
3701
3702 // this const just means the local variable doesn't change
3703 Track* const track = t.get();
3704
3705 // process fast tracks
3706 if (track->isFastTrack()) {
3707
3708 // It's theoretically possible (though unlikely) for a fast track to be created
3709 // and then removed within the same normal mix cycle. This is not a problem, as
3710 // the track never becomes active so it's fast mixer slot is never touched.
3711 // The converse, of removing an (active) track and then creating a new track
3712 // at the identical fast mixer slot within the same normal mix cycle,
3713 // is impossible because the slot isn't marked available until the end of each cycle.
3714 int j = track->mFastIndex;
3715 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
3716 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
3717 FastTrack *fastTrack = &state->mFastTracks[j];
3718
3719 // Determine whether the track is currently in underrun condition,
3720 // and whether it had a recent underrun.
3721 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
3722 FastTrackUnderruns underruns = ftDump->mUnderruns;
3723 uint32_t recentFull = (underruns.mBitFields.mFull -
3724 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
3725 uint32_t recentPartial = (underruns.mBitFields.mPartial -
3726 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
3727 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
3728 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
3729 uint32_t recentUnderruns = recentPartial + recentEmpty;
3730 track->mObservedUnderruns = underruns;
3731 // don't count underruns that occur while stopping or pausing
3732 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07003733 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
3734 recentUnderruns > 0) {
3735 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
3736 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003737 }
3738
3739 // This is similar to the state machine for normal tracks,
3740 // with a few modifications for fast tracks.
3741 bool isActive = true;
3742 switch (track->mState) {
3743 case TrackBase::STOPPING_1:
3744 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08003745 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003746 track->mState = TrackBase::STOPPING_2;
3747 }
3748 break;
3749 case TrackBase::PAUSING:
3750 // ramp down is not yet implemented
3751 track->setPaused();
3752 break;
3753 case TrackBase::RESUMING:
3754 // ramp up is not yet implemented
3755 track->mState = TrackBase::ACTIVE;
3756 break;
3757 case TrackBase::ACTIVE:
3758 if (recentFull > 0 || recentPartial > 0) {
3759 // track has provided at least some frames recently: reset retry count
3760 track->mRetryCount = kMaxTrackRetries;
3761 }
3762 if (recentUnderruns == 0) {
3763 // no recent underruns: stay active
3764 break;
3765 }
3766 // there has recently been an underrun of some kind
3767 if (track->sharedBuffer() == 0) {
3768 // were any of the recent underruns "empty" (no frames available)?
3769 if (recentEmpty == 0) {
3770 // no, then ignore the partial underruns as they are allowed indefinitely
3771 break;
3772 }
3773 // there has recently been an "empty" underrun: decrement the retry counter
3774 if (--(track->mRetryCount) > 0) {
3775 break;
3776 }
3777 // indicate to client process that the track was disabled because of underrun;
3778 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003779 android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003780 // remove from active list, but state remains ACTIVE [confusing but true]
3781 isActive = false;
3782 break;
3783 }
3784 // fall through
3785 case TrackBase::STOPPING_2:
3786 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003787 case TrackBase::STOPPED:
3788 case TrackBase::FLUSHED: // flush() while active
3789 // Check for presentation complete if track is inactive
3790 // We have consumed all the buffers of this track.
3791 // This would be incomplete if we auto-paused on underrun
3792 {
3793 size_t audioHALFrames =
3794 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3795 size_t framesWritten = mBytesWritten / mFrameSize;
3796 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
3797 // track stays in active list until presentation is complete
3798 break;
3799 }
3800 }
3801 if (track->isStopping_2()) {
3802 track->mState = TrackBase::STOPPED;
3803 }
3804 if (track->isStopped()) {
3805 // Can't reset directly, as fast mixer is still polling this track
3806 // track->reset();
3807 // So instead mark this track as needing to be reset after push with ack
3808 resetMask |= 1 << i;
3809 }
3810 isActive = false;
3811 break;
3812 case TrackBase::IDLE:
3813 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08003814 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08003815 }
3816
3817 if (isActive) {
3818 // was it previously inactive?
3819 if (!(state->mTrackMask & (1 << j))) {
3820 ExtendedAudioBufferProvider *eabp = track;
3821 VolumeProvider *vp = track;
3822 fastTrack->mBufferProvider = eabp;
3823 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08003824 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003825 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08003826 fastTrack->mGeneration++;
3827 state->mTrackMask |= 1 << j;
3828 didModify = true;
3829 // no acknowledgement required for newly active tracks
3830 }
3831 // cache the combined master volume and stream type volume for fast mixer; this
3832 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08003833 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08003834 ++fastTracks;
3835 } else {
3836 // was it previously active?
3837 if (state->mTrackMask & (1 << j)) {
3838 fastTrack->mBufferProvider = NULL;
3839 fastTrack->mGeneration++;
3840 state->mTrackMask &= ~(1 << j);
3841 didModify = true;
3842 // If any fast tracks were removed, we must wait for acknowledgement
3843 // because we're about to decrement the last sp<> on those tracks.
3844 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3845 } else {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003846 LOG_ALWAYS_FATAL("fast track %d should have been active", j);
Eric Laurent81784c32012-11-19 14:55:58 -08003847 }
3848 tracksToRemove->add(track);
3849 // Avoids a misleading display in dumpsys
3850 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
3851 }
3852 continue;
3853 }
3854
3855 { // local variable scope to avoid goto warning
3856
3857 audio_track_cblk_t* cblk = track->cblk();
3858
3859 // The first time a track is added we wait
3860 // for all its buffers to be filled before processing it
3861 int name = track->name();
3862 // make sure that we have enough frames to mix one full buffer.
3863 // enforce this condition only once to enable draining the buffer in case the client
3864 // app does not call stop() and relies on underrun to stop:
3865 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
3866 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003867 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07003868 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07003869 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07003870
3871 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07003872 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07003873 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
3874 // add frames already consumed but not yet released by the resampler
3875 // because mAudioTrackServerProxy->framesReady() will include these frames
3876 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
3877
Eric Laurent81784c32012-11-19 14:55:58 -08003878 uint32_t minFrames = 1;
3879 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
3880 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003881 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08003882 }
Eric Laurent13e4c962013-12-20 17:36:01 -08003883
3884 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07003885 if (ATRACE_ENABLED()) {
3886 // I wish we had formatted trace names
3887 char traceName[16];
3888 strcpy(traceName, "nRdy");
3889 int name = track->name();
3890 if (AudioMixer::TRACK0 <= name &&
3891 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
3892 name -= AudioMixer::TRACK0;
3893 traceName[4] = (name / 10) + '0';
3894 traceName[5] = (name % 10) + '0';
3895 } else {
3896 traceName[4] = '?';
3897 traceName[5] = '?';
3898 }
3899 traceName[6] = '\0';
3900 ATRACE_INT(traceName, framesReady);
3901 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003902 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08003903 !track->isPaused() && !track->isTerminated())
3904 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003905 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003906
3907 mixedTracks++;
3908
Andy Hung69aed5f2014-02-25 17:24:40 -08003909 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
3910 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08003911 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08003912 if (track->mainBuffer() != mSinkBuffer &&
3913 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08003914 if (mEffectBufferEnabled) {
3915 mEffectBufferValid = true; // Later can set directly.
3916 }
Eric Laurent81784c32012-11-19 14:55:58 -08003917 chain = getEffectChain_l(track->sessionId());
3918 // Delegate volume control to effect in track effect chain if needed
3919 if (chain != 0) {
3920 tracksWithEffect++;
3921 } else {
3922 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
3923 "session %d",
3924 name, track->sessionId());
3925 }
3926 }
3927
3928
3929 int param = AudioMixer::VOLUME;
3930 if (track->mFillingUpStatus == Track::FS_FILLED) {
3931 // no ramp for the first volume setting
3932 track->mFillingUpStatus = Track::FS_ACTIVE;
3933 if (track->mState == TrackBase::RESUMING) {
3934 track->mState = TrackBase::ACTIVE;
3935 param = AudioMixer::RAMP_VOLUME;
3936 }
3937 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003938 // FIXME should not make a decision based on mServer
3939 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003940 // If the track is stopped before the first frame was mixed,
3941 // do not apply ramp
3942 param = AudioMixer::RAMP_VOLUME;
3943 }
3944
3945 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07003946 uint32_t vl, vr; // in U8.24 integer format
3947 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08003948 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07003949 vl = vr = 0;
3950 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08003951 if (track->isPausing()) {
3952 track->setPaused();
3953 }
3954 } else {
3955
3956 // read original volumes with volume control
3957 float typeVolume = mStreamTypes[track->streamType()].volume;
3958 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003959 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07003960 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07003961 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
3962 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08003963 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07003964 if (vlf > GAIN_FLOAT_UNITY) {
3965 ALOGV("Track left volume out of range: %.3g", vlf);
3966 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003967 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07003968 if (vrf > GAIN_FLOAT_UNITY) {
3969 ALOGV("Track right volume out of range: %.3g", vrf);
3970 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003971 }
3972 // now apply the master volume and stream type volume
Andy Hung6be49402014-05-30 10:42:03 -07003973 vlf *= v;
3974 vrf *= v;
Eric Laurent81784c32012-11-19 14:55:58 -08003975 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07003976 // then derive vl and vr as U8.24 versions for the effect chain
3977 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
3978 vl = (uint32_t) (scaleto8_24 * vlf);
3979 vr = (uint32_t) (scaleto8_24 * vrf);
3980 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08003981 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08003982 // send level comes from shared memory and so may be corrupt
3983 if (sendLevel > MAX_GAIN_INT) {
3984 ALOGV("Track send level out of range: %04X", sendLevel);
3985 sendLevel = MAX_GAIN_INT;
3986 }
Andy Hung6be49402014-05-30 10:42:03 -07003987 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
3988 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08003989 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003990
Eric Laurent81784c32012-11-19 14:55:58 -08003991 // Delegate volume control to effect in track effect chain if needed
3992 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3993 // Do not ramp volume if volume is controlled by effect
3994 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08003995 // Update remaining floating point volume levels
3996 vlf = (float)vl / (1 << 24);
3997 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08003998 track->mHasVolumeController = true;
3999 } else {
4000 // force no volume ramp when volume controller was just disabled or removed
4001 // from effect chain to avoid volume spike
4002 if (track->mHasVolumeController) {
4003 param = AudioMixer::VOLUME;
4004 }
4005 track->mHasVolumeController = false;
4006 }
4007
Eric Laurent81784c32012-11-19 14:55:58 -08004008 // XXX: these things DON'T need to be done each time
4009 mAudioMixer->setBufferProvider(name, track);
4010 mAudioMixer->enable(name);
4011
Andy Hung6be49402014-05-30 10:42:03 -07004012 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
4013 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
4014 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08004015 mAudioMixer->setParameter(
4016 name,
4017 AudioMixer::TRACK,
4018 AudioMixer::FORMAT, (void *)track->format());
4019 mAudioMixer->setParameter(
4020 name,
4021 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004022 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07004023 mAudioMixer->setParameter(
4024 name,
4025 AudioMixer::TRACK,
4026 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08004027 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07004028 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004029 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08004030 if (reqSampleRate == 0) {
4031 reqSampleRate = mSampleRate;
4032 } else if (reqSampleRate > maxSampleRate) {
4033 reqSampleRate = maxSampleRate;
4034 }
Eric Laurent81784c32012-11-19 14:55:58 -08004035 mAudioMixer->setParameter(
4036 name,
4037 AudioMixer::RESAMPLE,
4038 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004039 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004040
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004041 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004042 mAudioMixer->setParameter(
4043 name,
4044 AudioMixer::TIMESTRETCH,
4045 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004046 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004047
Andy Hung69aed5f2014-02-25 17:24:40 -08004048 /*
4049 * Select the appropriate output buffer for the track.
4050 *
Andy Hung98ef9782014-03-04 14:46:50 -08004051 * Tracks with effects go into their own effects chain buffer
4052 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08004053 *
4054 * Other tracks can use mMixerBuffer for higher precision
4055 * channel accumulation. If this buffer is enabled
4056 * (mMixerBufferEnabled true), then selected tracks will accumulate
4057 * into it.
4058 *
4059 */
4060 if (mMixerBufferEnabled
4061 && (track->mainBuffer() == mSinkBuffer
4062 || track->mainBuffer() == mMixerBuffer)) {
4063 mAudioMixer->setParameter(
4064 name,
4065 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004066 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08004067 mAudioMixer->setParameter(
4068 name,
4069 AudioMixer::TRACK,
4070 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
4071 // TODO: override track->mainBuffer()?
4072 mMixerBufferValid = true;
4073 } else {
4074 mAudioMixer->setParameter(
4075 name,
4076 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004077 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08004078 mAudioMixer->setParameter(
4079 name,
4080 AudioMixer::TRACK,
4081 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
4082 }
Eric Laurent81784c32012-11-19 14:55:58 -08004083 mAudioMixer->setParameter(
4084 name,
4085 AudioMixer::TRACK,
4086 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
4087
4088 // reset retry count
4089 track->mRetryCount = kMaxTrackRetries;
4090
4091 // If one track is ready, set the mixer ready if:
4092 // - the mixer was not ready during previous round OR
4093 // - no other track is not ready
4094 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
4095 mixerStatus != MIXER_TRACKS_ENABLED) {
4096 mixerStatus = MIXER_TRACKS_READY;
4097 }
4098 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004099 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hung08fb1742015-05-31 23:22:10 -07004100 ALOGV("track(%p) underrun, framesReady(%zu) < framesDesired(%zd)",
4101 track, framesReady, desiredFrames);
Glenn Kasten82aaf942013-07-17 16:05:07 -07004102 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004103 }
Eric Laurent81784c32012-11-19 14:55:58 -08004104 // clear effect chain input buffer if an active track underruns to avoid sending
4105 // previous audio buffer again to effects
4106 chain = getEffectChain_l(track->sessionId());
4107 if (chain != 0) {
4108 chain->clearInputBuffer();
4109 }
4110
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004111 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004112 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
4113 track->isStopped() || track->isPaused()) {
4114 // We have consumed all the buffers of this track.
4115 // Remove it from the list of active tracks.
4116 // TODO: use actual buffer filling status instead of latency when available from
4117 // audio HAL
4118 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
4119 size_t framesWritten = mBytesWritten / mFrameSize;
4120 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
4121 if (track->isStopped()) {
4122 track->reset();
4123 }
4124 tracksToRemove->add(track);
4125 }
4126 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08004127 // No buffers for this track. Give it a few chances to
4128 // fill a buffer, then remove it from active list.
4129 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004130 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004131 tracksToRemove->add(track);
4132 // indicate to client process that the track was disabled because of underrun;
4133 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07004134 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08004135 // If one track is not ready, mark the mixer also not ready if:
4136 // - the mixer was ready during previous round OR
4137 // - no other track is ready
4138 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
4139 mixerStatus != MIXER_TRACKS_READY) {
4140 mixerStatus = MIXER_TRACKS_ENABLED;
4141 }
4142 }
4143 mAudioMixer->disable(name);
4144 }
4145
4146 } // local variable scope to avoid goto warning
4147track_is_ready: ;
4148
4149 }
4150
4151 // Push the new FastMixer state if necessary
4152 bool pauseAudioWatchdog = false;
4153 if (didModify) {
4154 state->mFastTracksGen++;
4155 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4156 if (kUseFastMixer == FastMixer_Dynamic &&
4157 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4158 state->mCommand = FastMixerState::COLD_IDLE;
4159 state->mColdFutexAddr = &mFastMixerFutex;
4160 state->mColdGen++;
4161 mFastMixerFutex = 0;
4162 if (kUseFastMixer == FastMixer_Dynamic) {
4163 mNormalSink = mOutputSink;
4164 }
4165 // If we go into cold idle, need to wait for acknowledgement
4166 // so that fast mixer stops doing I/O.
4167 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4168 pauseAudioWatchdog = true;
4169 }
Eric Laurent81784c32012-11-19 14:55:58 -08004170 }
4171 if (sq != NULL) {
4172 sq->end(didModify);
4173 sq->push(block);
4174 }
4175#ifdef AUDIO_WATCHDOG
4176 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4177 mAudioWatchdog->pause();
4178 }
4179#endif
4180
4181 // Now perform the deferred reset on fast tracks that have stopped
4182 while (resetMask != 0) {
4183 size_t i = __builtin_ctz(resetMask);
4184 ALOG_ASSERT(i < count);
4185 resetMask &= ~(1 << i);
4186 sp<Track> t = mActiveTracks[i].promote();
4187 if (t == 0) {
4188 continue;
4189 }
4190 Track* track = t.get();
4191 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
4192 track->reset();
4193 }
4194
4195 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004196 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004197
Eric Laurent97d547d2014-09-02 14:45:53 -07004198 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
4199 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07004200 }
4201
4202 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07004203 // as long as there are effects we should clear the effects buffer, to avoid
4204 // passing a non-clean buffer to the effect chain
4205 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07004206 }
Andy Hung69aed5f2014-02-25 17:24:40 -08004207 // sink or mix buffer must be cleared if all tracks are connected to an
4208 // effect chain as in this case the mixer will not write to the sink or mix buffer
4209 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08004210 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4211 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08004212 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08004213 if (mMixerBufferValid) {
4214 memset(mMixerBuffer, 0, mMixerBufferSize);
4215 // TODO: In testing, mSinkBuffer below need not be cleared because
4216 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
4217 // after mixing.
4218 //
4219 // To enforce this guarantee:
4220 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4221 // (mixedTracks == 0 && fastTracks > 0))
4222 // must imply MIXER_TRACKS_READY.
4223 // Later, we may clear buffers regardless, and skip much of this logic.
4224 }
Andy Hung98ef9782014-03-04 14:46:50 -08004225 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07004226 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004227 }
4228
4229 // if any fast tracks, then status is ready
4230 mMixerStatusIgnoringFastTracks = mixerStatus;
4231 if (fastTracks > 0) {
4232 mixerStatus = MIXER_TRACKS_READY;
4233 }
4234 return mixerStatus;
4235}
4236
4237// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07004238int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
4239 audio_format_t format, int sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08004240{
Andy Hunge8a1ced2014-05-09 15:02:21 -07004241 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08004242}
4243
4244// deleteTrackName_l() must be called with ThreadBase::mLock held
4245void AudioFlinger::MixerThread::deleteTrackName_l(int name)
4246{
4247 ALOGV("remove track (%d) and delete from mixer", name);
4248 mAudioMixer->deleteTrackName(name);
4249}
4250
Eric Laurent10351942014-05-08 18:49:52 -07004251// checkForNewParameter_l() must be called with ThreadBase::mLock held
4252bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
4253 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004254{
Eric Laurent81784c32012-11-19 14:55:58 -08004255 bool reconfig = false;
4256
Eric Laurent10351942014-05-08 18:49:52 -07004257 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004258
Eric Laurent10351942014-05-08 18:49:52 -07004259 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
4260 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004261 if (mFastMixer != 0) {
Eric Laurent10351942014-05-08 18:49:52 -07004262 FastMixerStateQueue *sq = mFastMixer->sq();
4263 FastMixerState *state = sq->begin();
4264 if (!(state->mCommand & FastMixerState::IDLE)) {
4265 previousCommand = state->mCommand;
4266 state->mCommand = FastMixerState::HOT_IDLE;
4267 sq->end();
4268 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
4269 } else {
4270 sq->end(false /*didModify*/);
Eric Laurent81784c32012-11-19 14:55:58 -08004271 }
Eric Laurent10351942014-05-08 18:49:52 -07004272 }
Eric Laurent81784c32012-11-19 14:55:58 -08004273
Eric Laurent10351942014-05-08 18:49:52 -07004274 AudioParameter param = AudioParameter(keyValuePair);
4275 int value;
4276 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4277 reconfig = true;
4278 }
4279 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004280 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004281 status = BAD_VALUE;
4282 } else {
4283 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08004284 reconfig = true;
4285 }
Eric Laurent10351942014-05-08 18:49:52 -07004286 }
4287 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004288 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004289 status = BAD_VALUE;
4290 } else {
4291 // no need to save value, since it's constant
4292 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004293 }
Eric Laurent10351942014-05-08 18:49:52 -07004294 }
4295 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4296 // do not accept frame count changes if tracks are open as the track buffer
4297 // size depends on frame count and correct behavior would not be guaranteed
4298 // if frame count is changed after track creation
4299 if (!mTracks.isEmpty()) {
4300 status = INVALID_OPERATION;
4301 } else {
4302 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004303 }
Eric Laurent10351942014-05-08 18:49:52 -07004304 }
4305 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004306#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07004307 // when changing the audio output device, call addBatteryData to notify
4308 // the change
4309 if (mOutDevice != value) {
4310 uint32_t params = 0;
4311 // check whether speaker is on
4312 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
4313 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08004314 }
Eric Laurent10351942014-05-08 18:49:52 -07004315
4316 audio_devices_t deviceWithoutSpeaker
4317 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
4318 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07004319 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07004320 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4321 }
4322
4323 if (params != 0) {
4324 addBatteryData(params);
4325 }
4326 }
Eric Laurent81784c32012-11-19 14:55:58 -08004327#endif
4328
Eric Laurent10351942014-05-08 18:49:52 -07004329 // forward device change to effects that have requested to be
4330 // aware of attached audio device.
4331 if (value != AUDIO_DEVICE_NONE) {
4332 mOutDevice = value;
4333 for (size_t i = 0; i < mEffectChains.size(); i++) {
4334 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08004335 }
4336 }
Eric Laurent10351942014-05-08 18:49:52 -07004337 }
Eric Laurent81784c32012-11-19 14:55:58 -08004338
Eric Laurent10351942014-05-08 18:49:52 -07004339 if (status == NO_ERROR) {
4340 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4341 keyValuePair.string());
4342 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004343 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004344 mStandby = true;
4345 mBytesWritten = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004346 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Eric Laurent10351942014-05-08 18:49:52 -07004347 keyValuePair.string());
Eric Laurent81784c32012-11-19 14:55:58 -08004348 }
Eric Laurent10351942014-05-08 18:49:52 -07004349 if (status == NO_ERROR && reconfig) {
4350 readOutputParameters_l();
4351 delete mAudioMixer;
4352 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4353 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07004354 int name = getTrackName_l(mTracks[i]->mChannelMask,
4355 mTracks[i]->mFormat, mTracks[i]->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07004356 if (name < 0) {
4357 break;
4358 }
4359 mTracks[i]->mName = name;
4360 }
Eric Laurent73e26b62015-04-27 16:55:58 -07004361 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004362 }
Eric Laurent81784c32012-11-19 14:55:58 -08004363 }
4364
4365 if (!(previousCommand & FastMixerState::IDLE)) {
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004366 ALOG_ASSERT(mFastMixer != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08004367 FastMixerStateQueue *sq = mFastMixer->sq();
4368 FastMixerState *state = sq->begin();
4369 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
4370 state->mCommand = previousCommand;
4371 sq->end();
4372 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4373 }
4374
4375 return reconfig;
4376}
4377
4378
4379void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
4380{
4381 const size_t SIZE = 256;
4382 char buffer[SIZE];
4383 String8 result;
4384
4385 PlaybackThread::dumpInternals(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07004386 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Elliott Hughes87cebad2014-05-22 10:14:43 -07004387 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Eric Laurent81784c32012-11-19 14:55:58 -08004388
4389 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten4182c4e2013-07-15 14:45:07 -07004390 const FastMixerDumpState copy(mFastMixerDumpState);
Eric Laurent81784c32012-11-19 14:55:58 -08004391 copy.dump(fd);
4392
4393#ifdef STATE_QUEUE_DUMP
4394 // Similar for state queue
4395 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4396 observerCopy.dump(fd);
4397 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4398 mutatorCopy.dump(fd);
4399#endif
4400
Glenn Kasten46909e72013-02-26 09:20:22 -08004401#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08004402 // Write the tee output to a .wav file
4403 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08004404#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004405
4406#ifdef AUDIO_WATCHDOG
4407 if (mAudioWatchdog != 0) {
4408 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4409 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4410 wdCopy.dump(fd);
4411 }
4412#endif
4413}
4414
4415uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4416{
4417 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4418}
4419
4420uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4421{
4422 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4423}
4424
4425void AudioFlinger::MixerThread::cacheParameters_l()
4426{
4427 PlaybackThread::cacheParameters_l();
4428
4429 // FIXME: Relaxed timing because of a certain device that can't meet latency
4430 // Should be reduced to 2x after the vendor fixes the driver issue
4431 // increase threshold again due to low power audio mode. The way this warning
4432 // threshold is calculated and its usefulness should be reconsidered anyway.
4433 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4434}
4435
4436// ----------------------------------------------------------------------------
4437
4438AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07004439 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device, bool systemReady)
4440 : PlaybackThread(audioFlinger, output, id, device, DIRECT, systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08004441 // mLeftVolFloat, mRightVolFloat
4442{
4443}
4444
Eric Laurentbfb1b832013-01-07 09:53:42 -08004445AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4446 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07004447 ThreadBase::type_t type, bool systemReady)
4448 : PlaybackThread(audioFlinger, output, id, device, type, systemReady)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004449 // mLeftVolFloat, mRightVolFloat
4450{
4451}
4452
Eric Laurent81784c32012-11-19 14:55:58 -08004453AudioFlinger::DirectOutputThread::~DirectOutputThread()
4454{
4455}
4456
Eric Laurentbfb1b832013-01-07 09:53:42 -08004457void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
4458{
4459 audio_track_cblk_t* cblk = track->cblk();
4460 float left, right;
4461
4462 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4463 left = right = 0;
4464 } else {
4465 float typeVolume = mStreamTypes[track->streamType()].volume;
4466 float v = mMasterVolume * typeVolume;
4467 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004468 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4469 left = float_from_gain(gain_minifloat_unpack_left(vlr));
4470 if (left > GAIN_FLOAT_UNITY) {
4471 left = GAIN_FLOAT_UNITY;
4472 }
4473 left *= v;
4474 right = float_from_gain(gain_minifloat_unpack_right(vlr));
4475 if (right > GAIN_FLOAT_UNITY) {
4476 right = GAIN_FLOAT_UNITY;
4477 }
4478 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004479 }
4480
4481 if (lastTrack) {
4482 if (left != mLeftVolFloat || right != mRightVolFloat) {
4483 mLeftVolFloat = left;
4484 mRightVolFloat = right;
4485
4486 // Convert volumes from float to 8.24
4487 uint32_t vl = (uint32_t)(left * (1 << 24));
4488 uint32_t vr = (uint32_t)(right * (1 << 24));
4489
4490 // Delegate volume control to effect in track effect chain if needed
4491 // only one effect chain can be present on DirectOutputThread, so if
4492 // there is one, the track is connected to it
4493 if (!mEffectChains.isEmpty()) {
4494 mEffectChains[0]->setVolume_l(&vl, &vr);
4495 left = (float)vl / (1 << 24);
4496 right = (float)vr / (1 << 24);
4497 }
4498 if (mOutput->stream->set_volume) {
4499 mOutput->stream->set_volume(mOutput->stream, left, right);
4500 }
4501 }
4502 }
4503}
4504
Phil Burk43b4dcc2015-06-09 16:53:44 -07004505void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
4506{
4507 sp<Track> previousTrack = mPreviousTrack.promote();
4508 sp<Track> latestTrack = mLatestActiveTrack.promote();
4509
Eric Laurent0f0631e2015-07-06 18:01:25 -07004510 if (previousTrack != 0 && latestTrack != 0) {
4511 if (mType == DIRECT) {
4512 if (previousTrack.get() != latestTrack.get()) {
4513 mFlushPending = true;
4514 }
4515 } else /* mType == OFFLOAD */ {
4516 if (previousTrack->sessionId() != latestTrack->sessionId()) {
4517 mFlushPending = true;
4518 }
4519 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004520 }
4521 PlaybackThread::onAddNewTrack_l();
4522}
Eric Laurentbfb1b832013-01-07 09:53:42 -08004523
Eric Laurent81784c32012-11-19 14:55:58 -08004524AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4525 Vector< sp<Track> > *tracksToRemove
4526)
4527{
Eric Laurentd595b7c2013-04-03 17:27:56 -07004528 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08004529 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004530 bool doHwPause = false;
4531 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004532
4533 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07004534 for (size_t i = 0; i < count; i++) {
4535 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08004536 // The track died recently
4537 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004538 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08004539 }
4540
Phil Burk43b4dcc2015-06-09 16:53:44 -07004541 if (t->isInvalid()) {
4542 ALOGW("An invalidated track shouldn't be in active list");
4543 tracksToRemove->add(t);
4544 continue;
4545 }
4546
Eric Laurent81784c32012-11-19 14:55:58 -08004547 Track* const track = t.get();
4548 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07004549 // Only consider last track started for volume and mixer state control.
4550 // In theory an older track could underrun and restart after the new one starts
4551 // but as we only care about the transition phase between two tracks on a
4552 // direct output, it is not a problem to ignore the underrun case.
4553 sp<Track> l = mLatestActiveTrack.promote();
4554 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08004555
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004556 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004557 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004558 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004559 doHwPause = true;
4560 mHwPaused = true;
4561 }
4562 tracksToRemove->add(track);
4563 } else if (track->isFlushPending()) {
4564 track->flushAck();
4565 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004566 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004567 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004568 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004569 track->resumeAck();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004570 if (last && mHwPaused) {
4571 doHwResume = true;
4572 mHwPaused = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004573 }
4574 }
4575
Eric Laurent81784c32012-11-19 14:55:58 -08004576 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08004577 // for all its buffers to be filled before processing it.
4578 // Allow draining the buffer in case the client
4579 // app does not call stop() and relies on underrun to stop:
4580 // hence the test on (track->mRetryCount > 1).
4581 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07004582 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08004583 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08004584 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkca5e6142015-07-14 09:42:29 -07004585 && (track->mRetryCount > 1) && audio_is_linear_pcm(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004586 minFrames = mNormalFrameCount;
4587 } else {
4588 minFrames = 1;
4589 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004590
Eric Laurentab5cdba2014-06-09 17:22:27 -07004591 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4592 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08004593 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004594 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08004595
4596 if (track->mFillingUpStatus == Track::FS_FILLED) {
4597 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004598 // make sure processVolume_l() will apply new volume even if 0
4599 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004600 if (!mHwSupportsPause) {
4601 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08004602 }
4603 }
4604
4605 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004606 processVolume_l(track, last);
4607 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004608 sp<Track> previousTrack = mPreviousTrack.promote();
4609 if (previousTrack != 0) {
4610 if (track != previousTrack.get()) {
4611 // Flush any data still being written from last track
4612 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07004613 // Invalidate previous track to force a seek when resuming.
4614 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004615 }
4616 }
4617 mPreviousTrack = track;
4618
Eric Laurentd595b7c2013-04-03 17:27:56 -07004619 // reset retry count
4620 track->mRetryCount = kMaxTrackRetriesDirect;
4621 mActiveTrack = t;
4622 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07004623 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004624 doHwResume = true;
4625 mHwPaused = false;
4626 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004627 }
Eric Laurent81784c32012-11-19 14:55:58 -08004628 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004629 // clear effect chain input buffer if the last active track started underruns
4630 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07004631 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004632 mEffectChains[0]->clearInputBuffer();
4633 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004634 if (track->isStopping_1()) {
4635 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07004636 if (last && mHwPaused) {
4637 doHwResume = true;
4638 mHwPaused = false;
4639 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004640 }
4641 if ((track->sharedBuffer() != 0) || track->isStopped() ||
4642 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004643 // We have consumed all the buffers of this track.
4644 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07004645 size_t audioHALFrames;
4646 if (audio_is_linear_pcm(mFormat)) {
4647 audioHALFrames = (latency_l() * mSampleRate) / 1000;
4648 } else {
4649 audioHALFrames = 0;
4650 }
4651
Eric Laurent81784c32012-11-19 14:55:58 -08004652 size_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07004653 if (mStandby || !last ||
4654 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004655 if (track->isStopping_2()) {
4656 track->mState = TrackBase::STOPPED;
4657 }
Eric Laurent81784c32012-11-19 14:55:58 -08004658 if (track->isStopped()) {
4659 track->reset();
4660 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004661 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08004662 }
4663 } else {
4664 // No buffers for this track. Give it a few chances to
4665 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07004666 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08004667 if (--(track->mRetryCount) <= 0) {
4668 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07004669 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004670 // indicate to client process that the track was disabled because of underrun;
4671 // it will then automatically call start() when data is available
4672 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004673 } else if (last) {
Phil Burkca5e6142015-07-14 09:42:29 -07004674 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
4675 "minFrames = %u, mFormat = %#x",
4676 track->framesReady(), minFrames, mFormat);
Eric Laurent81784c32012-11-19 14:55:58 -08004677 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07004678 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004679 doHwPause = true;
4680 mHwPaused = true;
4681 }
Eric Laurent81784c32012-11-19 14:55:58 -08004682 }
4683 }
4684 }
4685 }
4686
Eric Laurentd1f69b02014-12-15 14:33:13 -08004687 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07004688 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004689 for (size_t i = 0; i < mTracks.size(); i++) {
4690 if (mTracks[i]->isFlushPending()) {
4691 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004692 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004693 }
4694 }
4695 }
4696
4697 // make sure the pause/flush/resume sequence is executed in the right order.
4698 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4699 // before flush and then resume HW. This can happen in case of pause/flush/resume
4700 // if resume is received before pause is executed.
4701 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07004702 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004703 mOutput->stream->pause(mOutput->stream);
4704 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004705 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004706 flushHw_l();
4707 }
4708 if (mHwSupportsPause && !mStandby && doHwResume) {
4709 mOutput->stream->resume(mOutput->stream);
4710 }
Eric Laurent81784c32012-11-19 14:55:58 -08004711 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004712 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004713
4714 return mixerStatus;
4715}
4716
4717void AudioFlinger::DirectOutputThread::threadLoop_mix()
4718{
Eric Laurent81784c32012-11-19 14:55:58 -08004719 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08004720 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004721 // output audio to hardware
4722 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07004723 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004724 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08004725 status_t status = mActiveTrack->getNextBuffer(&buffer);
4726 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08004727 memset(curBuf, 0, frameCount * mFrameSize);
4728 break;
4729 }
4730 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
4731 frameCount -= buffer.frameCount;
4732 curBuf += buffer.frameCount * mFrameSize;
4733 mActiveTrack->releaseBuffer(&buffer);
4734 }
Andy Hung2098f272014-02-27 14:00:06 -08004735 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004736 mSleepTimeUs = 0;
4737 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08004738 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004739}
4740
4741void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
4742{
Eric Laurentd1f69b02014-12-15 14:33:13 -08004743 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004744 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004745 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004746 return;
4747 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004748 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004749 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004750 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004751 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004752 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004753 }
4754 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08004755 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004756 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004757 }
4758}
4759
Eric Laurentd1f69b02014-12-15 14:33:13 -08004760void AudioFlinger::DirectOutputThread::threadLoop_exit()
4761{
4762 {
4763 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08004764 for (size_t i = 0; i < mTracks.size(); i++) {
4765 if (mTracks[i]->isFlushPending()) {
4766 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004767 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004768 }
4769 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004770 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004771 flushHw_l();
4772 }
4773 }
4774 PlaybackThread::threadLoop_exit();
4775}
4776
4777// must be called with thread mutex locked
4778bool AudioFlinger::DirectOutputThread::shouldStandby_l()
4779{
4780 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07004781 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004782
4783 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4784 // after a timeout and we will enter standby then.
4785 if (mTracks.size() > 0) {
4786 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07004787 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
4788 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004789 }
4790
Eric Laurent5cff4032015-05-26 13:49:58 -07004791 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08004792}
4793
Eric Laurent81784c32012-11-19 14:55:58 -08004794// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004795int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Andy Hunge8a1ced2014-05-09 15:02:21 -07004796 audio_format_t format __unused, int sessionId __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004797{
4798 return 0;
4799}
4800
4801// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004802void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004803{
4804}
4805
Eric Laurent10351942014-05-08 18:49:52 -07004806// checkForNewParameter_l() must be called with ThreadBase::mLock held
4807bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
4808 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004809{
4810 bool reconfig = false;
4811
Eric Laurent10351942014-05-08 18:49:52 -07004812 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004813
Eric Laurent10351942014-05-08 18:49:52 -07004814 AudioParameter param = AudioParameter(keyValuePair);
4815 int value;
4816 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4817 // forward device change to effects that have requested to be
4818 // aware of attached audio device.
4819 if (value != AUDIO_DEVICE_NONE) {
4820 mOutDevice = value;
4821 for (size_t i = 0; i < mEffectChains.size(); i++) {
4822 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07004823 }
4824 }
Eric Laurent81784c32012-11-19 14:55:58 -08004825 }
Eric Laurent10351942014-05-08 18:49:52 -07004826 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4827 // do not accept frame count changes if tracks are open as the track buffer
4828 // size depends on frame count and correct behavior would not be garantied
4829 // if frame count is changed after track creation
4830 if (!mTracks.isEmpty()) {
4831 status = INVALID_OPERATION;
4832 } else {
4833 reconfig = true;
4834 }
4835 }
4836 if (status == NO_ERROR) {
4837 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4838 keyValuePair.string());
4839 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004840 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004841 mStandby = true;
4842 mBytesWritten = 0;
4843 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4844 keyValuePair.string());
4845 }
4846 if (status == NO_ERROR && reconfig) {
4847 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07004848 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004849 }
4850 }
4851
Eric Laurent81784c32012-11-19 14:55:58 -08004852 return reconfig;
4853}
4854
4855uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
4856{
4857 uint32_t time;
4858 if (audio_is_linear_pcm(mFormat)) {
4859 time = PlaybackThread::activeSleepTimeUs();
4860 } else {
4861 time = 10000;
4862 }
4863 return time;
4864}
4865
4866uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
4867{
4868 uint32_t time;
4869 if (audio_is_linear_pcm(mFormat)) {
4870 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
4871 } else {
4872 time = 10000;
4873 }
4874 return time;
4875}
4876
4877uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
4878{
4879 uint32_t time;
4880 if (audio_is_linear_pcm(mFormat)) {
4881 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
4882 } else {
4883 time = 10000;
4884 }
4885 return time;
4886}
4887
4888void AudioFlinger::DirectOutputThread::cacheParameters_l()
4889{
4890 PlaybackThread::cacheParameters_l();
4891
4892 // use shorter standby delay as on normal output to release
4893 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07004894 // no delay on outputs with HW A/V sync
4895 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004896 mStandbyDelayNs = 0;
Eric Laurent5cff4032015-05-26 13:49:58 -07004897 } else if ((mType == OFFLOAD) && !audio_is_linear_pcm(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004898 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07004899 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004900 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07004901 }
Eric Laurent81784c32012-11-19 14:55:58 -08004902}
4903
Eric Laurente659ef42014-09-29 13:06:46 -07004904void AudioFlinger::DirectOutputThread::flushHw_l()
4905{
Phil Burk062e67a2015-02-11 13:40:50 -08004906 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08004907 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07004908 mFlushPending = false;
Eric Laurente659ef42014-09-29 13:06:46 -07004909}
4910
Eric Laurent81784c32012-11-19 14:55:58 -08004911// ----------------------------------------------------------------------------
4912
Eric Laurentbfb1b832013-01-07 09:53:42 -08004913AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07004914 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004915 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07004916 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07004917 mWriteAckSequence(0),
4918 mDrainSequence(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004919{
4920}
4921
4922AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
4923{
4924}
4925
4926void AudioFlinger::AsyncCallbackThread::onFirstRef()
4927{
4928 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
4929}
4930
4931bool AudioFlinger::AsyncCallbackThread::threadLoop()
4932{
4933 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004934 uint32_t writeAckSequence;
4935 uint32_t drainSequence;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004936
4937 {
4938 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08004939 while (!((mWriteAckSequence & 1) ||
4940 (mDrainSequence & 1) ||
4941 exitPending())) {
4942 mWaitWorkCV.wait(mLock);
4943 }
4944
Eric Laurentbfb1b832013-01-07 09:53:42 -08004945 if (exitPending()) {
4946 break;
4947 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004948 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
4949 mWriteAckSequence, mDrainSequence);
4950 writeAckSequence = mWriteAckSequence;
4951 mWriteAckSequence &= ~1;
4952 drainSequence = mDrainSequence;
4953 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004954 }
4955 {
Eric Laurent4de95592013-09-26 15:28:21 -07004956 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
4957 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004958 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004959 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004960 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004961 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004962 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004963 }
4964 }
4965 }
4966 }
4967 return false;
4968}
4969
4970void AudioFlinger::AsyncCallbackThread::exit()
4971{
4972 ALOGV("AsyncCallbackThread::exit");
4973 Mutex::Autolock _l(mLock);
4974 requestExit();
4975 mWaitWorkCV.broadcast();
4976}
4977
Eric Laurent3b4529e2013-09-05 18:09:19 -07004978void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004979{
4980 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004981 // bit 0 is cleared
4982 mWriteAckSequence = sequence << 1;
4983}
4984
4985void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
4986{
4987 Mutex::Autolock _l(mLock);
4988 // ignore unexpected callbacks
4989 if (mWriteAckSequence & 2) {
4990 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004991 mWaitWorkCV.signal();
4992 }
4993}
4994
Eric Laurent3b4529e2013-09-05 18:09:19 -07004995void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004996{
4997 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004998 // bit 0 is cleared
4999 mDrainSequence = sequence << 1;
5000}
5001
5002void AudioFlinger::AsyncCallbackThread::resetDraining()
5003{
5004 Mutex::Autolock _l(mLock);
5005 // ignore unexpected callbacks
5006 if (mDrainSequence & 2) {
5007 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005008 mWaitWorkCV.signal();
5009 }
5010}
5011
5012
5013// ----------------------------------------------------------------------------
5014AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07005015 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady)
5016 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady),
Eric Laurentd7e59222013-11-15 12:02:28 -08005017 mPausedBytesRemaining(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005018{
Eric Laurentfd477972013-10-25 18:10:40 -07005019 //FIXME: mStandby should be set to true by ThreadBase constructor
5020 mStandby = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005021}
5022
Eric Laurentbfb1b832013-01-07 09:53:42 -08005023void AudioFlinger::OffloadThread::threadLoop_exit()
5024{
5025 if (mFlushPending || mHwPaused) {
5026 // If a flush is pending or track was paused, just discard buffered data
5027 flushHw_l();
5028 } else {
5029 mMixerStatus = MIXER_DRAIN_ALL;
5030 threadLoop_drain();
5031 }
Uday Gupta56604aa2014-05-13 11:19:17 -07005032 if (mUseAsyncWrite) {
5033 ALOG_ASSERT(mCallbackThread != 0);
5034 mCallbackThread->exit();
5035 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005036 PlaybackThread::threadLoop_exit();
5037}
5038
5039AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
5040 Vector< sp<Track> > *tracksToRemove
5041)
5042{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005043 size_t count = mActiveTracks.size();
5044
5045 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07005046 bool doHwPause = false;
5047 bool doHwResume = false;
5048
Eric Laurentede6c3b2013-09-19 14:37:46 -07005049 ALOGV("OffloadThread::prepareTracks_l active tracks %d", count);
5050
Eric Laurentbfb1b832013-01-07 09:53:42 -08005051 // find out which tracks need to be processed
5052 for (size_t i = 0; i < count; i++) {
5053 sp<Track> t = mActiveTracks[i].promote();
5054 // The track died recently
5055 if (t == 0) {
5056 continue;
5057 }
5058 Track* const track = t.get();
5059 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07005060 // Only consider last track started for volume and mixer state control.
5061 // In theory an older track could underrun and restart after the new one starts
5062 // but as we only care about the transition phase between two tracks on a
5063 // direct output, it is not a problem to ignore the underrun case.
5064 sp<Track> l = mLatestActiveTrack.promote();
5065 bool last = l.get() == track;
5066
Haynes Mathew George7844f672014-01-15 12:32:55 -08005067 if (track->isInvalid()) {
5068 ALOGW("An invalidated track shouldn't be in active list");
5069 tracksToRemove->add(track);
5070 continue;
5071 }
5072
5073 if (track->mState == TrackBase::IDLE) {
5074 ALOGW("An idle track shouldn't be in active list");
5075 continue;
5076 }
5077
Eric Laurentbfb1b832013-01-07 09:53:42 -08005078 if (track->isPausing()) {
5079 track->setPaused();
5080 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07005081 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07005082 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005083 mHwPaused = true;
5084 }
5085 // If we were part way through writing the mixbuffer to
5086 // the HAL we must save this until we resume
5087 // BUG - this will be wrong if a different track is made active,
5088 // in that case we want to discard the pending data in the
5089 // mixbuffer and tell the client to present it again when the
5090 // track is resumed
5091 mPausedWriteLength = mCurrentWriteLength;
5092 mPausedBytesRemaining = mBytesRemaining;
5093 mBytesRemaining = 0; // stop writing
5094 }
5095 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08005096 } else if (track->isFlushPending()) {
5097 track->flushAck();
5098 if (last) {
5099 mFlushPending = true;
5100 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005101 } else if (track->isResumePending()){
5102 track->resumeAck();
5103 if (last) {
5104 if (mPausedBytesRemaining) {
5105 // Need to continue write that was interrupted
5106 mCurrentWriteLength = mPausedWriteLength;
5107 mBytesRemaining = mPausedBytesRemaining;
5108 mPausedBytesRemaining = 0;
5109 }
5110 if (mHwPaused) {
5111 doHwResume = true;
5112 mHwPaused = false;
5113 // threadLoop_mix() will handle the case that we need to
5114 // resume an interrupted write
5115 }
5116 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005117 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005118
5119 // Do not handle new data in this iteration even if track->framesReady()
5120 mixerStatus = MIXER_TRACKS_ENABLED;
5121 }
5122 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07005123 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005124 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005125 if (track->mFillingUpStatus == Track::FS_FILLED) {
5126 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07005127 // make sure processVolume_l() will apply new volume even if 0
5128 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005129 }
5130
5131 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08005132 sp<Track> previousTrack = mPreviousTrack.promote();
5133 if (previousTrack != 0) {
5134 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08005135 // Flush any data still being written from last track
5136 mBytesRemaining = 0;
5137 if (mPausedBytesRemaining) {
5138 // Last track was paused so we also need to flush saved
5139 // mixbuffer state and invalidate track so that it will
5140 // re-submit that unwritten data when it is next resumed
5141 mPausedBytesRemaining = 0;
5142 // Invalidate is a bit drastic - would be more efficient
5143 // to have a flag to tell client that some of the
5144 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08005145 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005146 }
5147 // flush data already sent to the DSP if changing audio session as audio
5148 // comes from a different source. Also invalidate previous track to force a
5149 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08005150 if (previousTrack->sessionId() != track->sessionId()) {
5151 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005152 }
5153 }
5154 }
5155 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005156 // reset retry count
5157 track->mRetryCount = kMaxTrackRetriesOffload;
5158 mActiveTrack = t;
5159 mixerStatus = MIXER_TRACKS_READY;
5160 }
5161 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005162 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005163 if (track->isStopping_1()) {
5164 // Hardware buffer can hold a large amount of audio so we must
5165 // wait for all current track's data to drain before we say
5166 // that the track is stopped.
5167 if (mBytesRemaining == 0) {
5168 // Only start draining when all data in mixbuffer
5169 // has been written
5170 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
5171 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005172 // do not drain if no data was ever sent to HAL (mStandby == true)
5173 if (last && !mStandby) {
Eric Laurent1b9f9b12013-11-12 19:10:17 -08005174 // do not modify drain sequence if we are already draining. This happens
5175 // when resuming from pause after drain.
5176 if ((mDrainSequence & 1) == 0) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005177 mSleepTimeUs = 0;
5178 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent1b9f9b12013-11-12 19:10:17 -08005179 mixerStatus = MIXER_DRAIN_TRACK;
5180 mDrainSequence += 2;
5181 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005182 if (mHwPaused) {
5183 // It is possible to move from PAUSED to STOPPING_1 without
5184 // a resume so we must ensure hardware is running
Eric Laurent1b9f9b12013-11-12 19:10:17 -08005185 doHwResume = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005186 mHwPaused = false;
5187 }
5188 }
5189 }
5190 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005191 // Drain has completed or we are in standby, signal presentation complete
5192 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005193 track->mState = TrackBase::STOPPED;
5194 size_t audioHALFrames =
5195 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
5196 size_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08005197 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005198 track->presentationComplete(framesWritten, audioHALFrames);
5199 track->reset();
5200 tracksToRemove->add(track);
5201 }
5202 } else {
5203 // No buffers for this track. Give it a few chances to
5204 // fill a buffer, then remove it from active list.
5205 if (--(track->mRetryCount) <= 0) {
5206 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
5207 track->name());
5208 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08005209 // indicate to client process that the track was disabled because of underrun;
5210 // it will then automatically call start() when data is available
5211 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005212 } else if (last){
5213 mixerStatus = MIXER_TRACKS_ENABLED;
5214 }
5215 }
5216 }
5217 // compute volume for this track
5218 processVolume_l(track, last);
5219 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005220
Eric Laurentea0fade2013-10-04 16:23:48 -07005221 // make sure the pause/flush/resume sequence is executed in the right order.
5222 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5223 // before flush and then resume HW. This can happen in case of pause/flush/resume
5224 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07005225 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurent972a1732013-09-04 09:42:59 -07005226 mOutput->stream->pause(mOutput->stream);
5227 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005228 if (mFlushPending) {
5229 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005230 }
Eric Laurentfd477972013-10-25 18:10:40 -07005231 if (!mStandby && doHwResume) {
Eric Laurent972a1732013-09-04 09:42:59 -07005232 mOutput->stream->resume(mOutput->stream);
5233 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005234
Eric Laurentbfb1b832013-01-07 09:53:42 -08005235 // remove all the tracks that need to be...
5236 removeTracks_l(*tracksToRemove);
5237
5238 return mixerStatus;
5239}
5240
Eric Laurentbfb1b832013-01-07 09:53:42 -08005241// must be called with thread mutex locked
5242bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
5243{
Eric Laurent3b4529e2013-09-05 18:09:19 -07005244 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
5245 mWriteAckSequence, mDrainSequence);
5246 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005247 return true;
5248 }
5249 return false;
5250}
5251
Eric Laurentbfb1b832013-01-07 09:53:42 -08005252bool AudioFlinger::OffloadThread::waitingAsyncCallback()
5253{
5254 Mutex::Autolock _l(mLock);
5255 return waitingAsyncCallback_l();
5256}
5257
5258void AudioFlinger::OffloadThread::flushHw_l()
5259{
Eric Laurente659ef42014-09-29 13:06:46 -07005260 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005261 // Flush anything still waiting in the mixbuffer
5262 mCurrentWriteLength = 0;
5263 mBytesRemaining = 0;
5264 mPausedWriteLength = 0;
5265 mPausedBytesRemaining = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08005266
Eric Laurentbfb1b832013-01-07 09:53:42 -08005267 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005268 // discard any pending drain or write ack by incrementing sequence
5269 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5270 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005271 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005272 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5273 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005274 }
5275}
5276
5277// ----------------------------------------------------------------------------
5278
Eric Laurent81784c32012-11-19 14:55:58 -08005279AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07005280 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08005281 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
Eric Laurent72e3f392015-05-20 14:43:50 -07005282 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08005283 mWaitTimeMs(UINT_MAX)
5284{
5285 addOutputTrack(mainThread);
5286}
5287
5288AudioFlinger::DuplicatingThread::~DuplicatingThread()
5289{
5290 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5291 mOutputTracks[i]->destroy();
5292 }
5293}
5294
5295void AudioFlinger::DuplicatingThread::threadLoop_mix()
5296{
5297 // mix buffers...
5298 if (outputsReady(outputTracks)) {
5299 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
5300 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08005301 if (mMixerBufferValid) {
5302 memset(mMixerBuffer, 0, mMixerBufferSize);
5303 } else {
5304 memset(mSinkBuffer, 0, mSinkBufferSize);
5305 }
Eric Laurent81784c32012-11-19 14:55:58 -08005306 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005307 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005308 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005309 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005310 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005311}
5312
5313void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
5314{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005315 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005316 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005317 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005318 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005319 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005320 }
5321 } else if (mBytesWritten != 0) {
5322 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5323 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005324 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005325 } else {
5326 // flush remaining overflow buffers in output tracks
5327 writeFrames = 0;
5328 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005329 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005330 }
5331}
5332
Eric Laurentbfb1b832013-01-07 09:53:42 -08005333ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005334{
5335 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08005336 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005337 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07005338 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08005339 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005340}
5341
5342void AudioFlinger::DuplicatingThread::threadLoop_standby()
5343{
5344 // DuplicatingThread implements standby by stopping all tracks
5345 for (size_t i = 0; i < outputTracks.size(); i++) {
5346 outputTracks[i]->stop();
5347 }
5348}
5349
5350void AudioFlinger::DuplicatingThread::saveOutputTracks()
5351{
5352 outputTracks = mOutputTracks;
5353}
5354
5355void AudioFlinger::DuplicatingThread::clearOutputTracks()
5356{
5357 outputTracks.clear();
5358}
5359
5360void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
5361{
5362 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08005363 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
5364 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
5365 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
5366 const size_t frameCount =
5367 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
5368 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
5369 // from different OutputTracks and their associated MixerThreads (e.g. one may
5370 // nearly empty and the other may be dropping data).
5371
5372 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08005373 this,
5374 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08005375 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08005376 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005377 frameCount,
5378 IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08005379 if (outputTrack->cblk() != NULL) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005380 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
Eric Laurent81784c32012-11-19 14:55:58 -08005381 mOutputTracks.add(outputTrack);
Andy Hungc25b84a2015-01-14 19:04:10 -08005382 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005383 updateWaitTime_l();
5384 }
5385}
5386
5387void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
5388{
5389 Mutex::Autolock _l(mLock);
5390 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5391 if (mOutputTracks[i]->thread() == thread) {
5392 mOutputTracks[i]->destroy();
5393 mOutputTracks.removeAt(i);
5394 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07005395 if (thread->getOutput() == mOutput) {
5396 mOutput = NULL;
5397 }
Eric Laurent81784c32012-11-19 14:55:58 -08005398 return;
5399 }
5400 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07005401 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005402}
5403
5404// caller must hold mLock
5405void AudioFlinger::DuplicatingThread::updateWaitTime_l()
5406{
5407 mWaitTimeMs = UINT_MAX;
5408 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5409 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
5410 if (strong != 0) {
5411 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
5412 if (waitTimeMs < mWaitTimeMs) {
5413 mWaitTimeMs = waitTimeMs;
5414 }
5415 }
5416 }
5417}
5418
5419
5420bool AudioFlinger::DuplicatingThread::outputsReady(
5421 const SortedVector< sp<OutputTrack> > &outputTracks)
5422{
5423 for (size_t i = 0; i < outputTracks.size(); i++) {
5424 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
5425 if (thread == 0) {
5426 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
5427 outputTracks[i].get());
5428 return false;
5429 }
5430 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5431 // see note at standby() declaration
5432 if (playbackThread->standby() && !playbackThread->isSuspended()) {
5433 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
5434 thread.get());
5435 return false;
5436 }
5437 }
5438 return true;
5439}
5440
5441uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
5442{
5443 return (mWaitTimeMs * 1000) / 2;
5444}
5445
5446void AudioFlinger::DuplicatingThread::cacheParameters_l()
5447{
5448 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
5449 updateWaitTime_l();
5450
5451 MixerThread::cacheParameters_l();
5452}
5453
5454// ----------------------------------------------------------------------------
5455// Record
5456// ----------------------------------------------------------------------------
5457
5458AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5459 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08005460 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08005461 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07005462 audio_devices_t inDevice,
5463 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08005464#ifdef TEE_SINK
5465 , const sp<NBAIO_Sink>& teeSink
5466#endif
5467 ) :
Eric Laurent72e3f392015-05-20 14:43:50 -07005468 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005469 mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005470 // mRsmpInFrames and mRsmpInFramesP2 are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005471 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08005472#ifdef TEE_SINK
5473 , mTeeSink(teeSink)
5474#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07005475 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
5476 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005477 // mFastCapture below
5478 , mFastCaptureFutex(0)
5479 // mInputSource
5480 // mPipeSink
5481 // mPipeSource
5482 , mPipeFramesP2(0)
5483 // mPipeMemory
5484 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005485 , mFastTrackAvail(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005486{
Glenn Kastend7dca052015-03-05 16:05:54 -08005487 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
5488 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08005489
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005490 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005491
5492 // create an NBAIO source for the HAL input stream, and negotiate
5493 mInputSource = new AudioStreamInSource(input->stream);
5494 size_t numCounterOffers = 0;
5495 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
5496 ssize_t index = mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
5497 ALOG_ASSERT(index == 0);
5498
5499 // initialize fast capture depending on configuration
5500 bool initFastCapture;
5501 switch (kUseFastCapture) {
5502 case FastCapture_Never:
5503 initFastCapture = false;
5504 break;
5505 case FastCapture_Always:
5506 initFastCapture = true;
5507 break;
5508 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07005509 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005510 break;
5511 // case FastCapture_Dynamic:
5512 }
5513
5514 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07005515 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005516 NBAIO_Format format = mInputSource->format();
Glenn Kasten49d00ad2014-07-21 11:22:03 -07005517 size_t pipeFramesP2 = roundup(mSampleRate / 25); // double-buffering of 20 ms each
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005518 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
5519 void *pipeBuffer;
5520 const sp<MemoryDealer> roHeap(readOnlyHeap());
5521 sp<IMemory> pipeMemory;
5522 if ((roHeap == 0) ||
5523 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
5524 (pipeBuffer = pipeMemory->pointer()) == NULL) {
5525 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
5526 goto failed;
5527 }
5528 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
5529 memset(pipeBuffer, 0, pipeSize);
5530 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
5531 const NBAIO_Format offers[1] = {format};
5532 size_t numCounterOffers = 0;
5533 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
5534 ALOG_ASSERT(index == 0);
5535 mPipeSink = pipe;
5536 PipeReader *pipeReader = new PipeReader(*pipe);
5537 numCounterOffers = 0;
5538 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
5539 ALOG_ASSERT(index == 0);
5540 mPipeSource = pipeReader;
5541 mPipeFramesP2 = pipeFramesP2;
5542 mPipeMemory = pipeMemory;
5543
5544 // create fast capture
5545 mFastCapture = new FastCapture();
5546 FastCaptureStateQueue *sq = mFastCapture->sq();
5547#ifdef STATE_QUEUE_DUMP
5548 // FIXME
5549#endif
5550 FastCaptureState *state = sq->begin();
5551 state->mCblk = NULL;
5552 state->mInputSource = mInputSource.get();
5553 state->mInputSourceGen++;
5554 state->mPipeSink = pipe;
5555 state->mPipeSinkGen++;
5556 state->mFrameCount = mFrameCount;
5557 state->mCommand = FastCaptureState::COLD_IDLE;
5558 // already done in constructor initialization list
5559 //mFastCaptureFutex = 0;
5560 state->mColdFutexAddr = &mFastCaptureFutex;
5561 state->mColdGen++;
5562 state->mDumpState = &mFastCaptureDumpState;
5563#ifdef TEE_SINK
5564 // FIXME
5565#endif
5566 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
5567 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
5568 sq->end();
5569 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5570
5571 // start the fast capture
5572 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
5573 pid_t tid = mFastCapture->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07005574 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005575#ifdef AUDIO_WATCHDOG
5576 // FIXME
5577#endif
5578
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005579 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005580 }
5581failed: ;
5582
5583 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08005584}
5585
Eric Laurent81784c32012-11-19 14:55:58 -08005586AudioFlinger::RecordThread::~RecordThread()
5587{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005588 if (mFastCapture != 0) {
5589 FastCaptureStateQueue *sq = mFastCapture->sq();
5590 FastCaptureState *state = sq->begin();
5591 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5592 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5593 if (old == -1) {
5594 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5595 }
5596 }
5597 state->mCommand = FastCaptureState::EXIT;
5598 sq->end();
5599 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5600 mFastCapture->join();
5601 mFastCapture.clear();
5602 }
5603 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07005604 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07005605 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08005606}
5607
5608void AudioFlinger::RecordThread::onFirstRef()
5609{
Glenn Kastend7dca052015-03-05 16:05:54 -08005610 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08005611}
5612
Eric Laurent81784c32012-11-19 14:55:58 -08005613bool AudioFlinger::RecordThread::threadLoop()
5614{
Eric Laurent81784c32012-11-19 14:55:58 -08005615 nsecs_t lastWarning = 0;
5616
5617 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08005618
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005619reacquire_wakelock:
5620 sp<RecordTrack> activeTrack;
Glenn Kasten2b806402013-11-20 16:37:38 -08005621 int activeTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005622 {
5623 Mutex::Autolock _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005624 size_t size = mActiveTracks.size();
5625 activeTracksGen = mActiveTracksGen;
5626 if (size > 0) {
5627 // FIXME an arbitrary choice
5628 activeTrack = mActiveTracks[0];
5629 acquireWakeLock_l(activeTrack->uid());
5630 if (size > 1) {
5631 SortedVector<int> tmp;
5632 for (size_t i = 0; i < size; i++) {
5633 tmp.add(mActiveTracks[i]->uid());
5634 }
5635 updateWakeLockUids_l(tmp);
5636 }
5637 } else {
5638 acquireWakeLock_l(-1);
5639 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005640 }
5641
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005642 // used to request a deferred sleep, to be executed later while mutex is unlocked
5643 uint32_t sleepUs = 0;
5644
5645 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005646 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005647 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07005648
Glenn Kasten5edadd42013-08-14 16:30:49 -07005649 // sleep with mutex unlocked
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005650 if (sleepUs > 0) {
Glenn Kastene7754022014-10-31 12:11:26 -07005651 ATRACE_BEGIN("sleep");
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005652 usleep(sleepUs);
Glenn Kastene7754022014-10-31 12:11:26 -07005653 ATRACE_END();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005654 sleepUs = 0;
Glenn Kasten5edadd42013-08-14 16:30:49 -07005655 }
5656
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005657 // activeTracks accumulates a copy of a subset of mActiveTracks
5658 Vector< sp<RecordTrack> > activeTracks;
5659
Glenn Kasten735f45f2014-08-18 15:51:59 -07005660 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005661 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07005662
Glenn Kasten735f45f2014-08-18 15:51:59 -07005663 // reference to a fast track which is about to be removed
5664 sp<RecordTrack> fastTrackToRemove;
5665
Eric Laurent81784c32012-11-19 14:55:58 -08005666 { // scope for mLock
5667 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08005668
Eric Laurent021cf962014-05-13 10:18:14 -07005669 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005670
Eric Laurent000a4192014-01-29 15:17:32 -08005671 // check exitPending here because checkForNewParameters_l() and
5672 // checkForNewParameters_l() can temporarily release mLock
5673 if (exitPending()) {
5674 break;
5675 }
5676
Glenn Kasten2b806402013-11-20 16:37:38 -08005677 // if no active track(s), then standby and release wakelock
5678 size_t size = mActiveTracks.size();
5679 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07005680 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005681 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08005682 releaseWakeLock_l();
5683 ALOGV("RecordThread: loop stopping");
5684 // go to sleep
5685 mWaitWorkCV.wait(mLock);
5686 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005687 goto reacquire_wakelock;
5688 }
5689
Glenn Kasten2b806402013-11-20 16:37:38 -08005690 if (mActiveTracksGen != activeTracksGen) {
5691 activeTracksGen = mActiveTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005692 SortedVector<int> tmp;
Glenn Kasten2b806402013-11-20 16:37:38 -08005693 for (size_t i = 0; i < size; i++) {
5694 tmp.add(mActiveTracks[i]->uid());
5695 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005696 updateWakeLockUids_l(tmp);
Eric Laurent81784c32012-11-19 14:55:58 -08005697 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005698
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005699 bool doBroadcast = false;
5700 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07005701
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005702 activeTrack = mActiveTracks[i];
5703 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07005704 if (activeTrack->isFastTrack()) {
5705 ALOG_ASSERT(fastTrackToRemove == 0);
5706 fastTrackToRemove = activeTrack;
5707 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005708 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08005709 mActiveTracks.remove(activeTrack);
5710 mActiveTracksGen++;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005711 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07005712 continue;
5713 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005714
5715 TrackBase::track_state activeTrackState = activeTrack->mState;
5716 switch (activeTrackState) {
5717
5718 case TrackBase::PAUSING:
5719 mActiveTracks.remove(activeTrack);
5720 mActiveTracksGen++;
5721 doBroadcast = true;
5722 size--;
5723 continue;
5724
5725 case TrackBase::STARTING_1:
5726 sleepUs = 10000;
5727 i++;
5728 continue;
5729
5730 case TrackBase::STARTING_2:
5731 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005732 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07005733 activeTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005734 break;
5735
5736 case TrackBase::ACTIVE:
5737 break;
5738
5739 case TrackBase::IDLE:
5740 i++;
5741 continue;
5742
5743 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08005744 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07005745 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005746
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005747 activeTracks.add(activeTrack);
5748 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07005749
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005750 if (activeTrack->isFastTrack()) {
5751 ALOG_ASSERT(!mFastTrackAvail);
5752 ALOG_ASSERT(fastTrack == 0);
5753 fastTrack = activeTrack;
5754 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005755 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005756 if (doBroadcast) {
5757 mStartStopCond.broadcast();
5758 }
5759
5760 // sleep if there are no active tracks to process
5761 if (activeTracks.size() == 0) {
5762 if (sleepUs == 0) {
5763 sleepUs = kRecordThreadSleepUs;
5764 }
5765 continue;
5766 }
5767 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07005768
Eric Laurent81784c32012-11-19 14:55:58 -08005769 lockEffectChains_l(effectChains);
5770 }
5771
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005772 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07005773
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005774 size_t size = effectChains.size();
5775 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005776 // thread mutex is not locked, but effect chain is locked
5777 effectChains[i]->process_l();
5778 }
5779
Glenn Kasten735f45f2014-08-18 15:51:59 -07005780 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005781 if (mFastCapture != 0) {
5782 FastCaptureStateQueue *sq = mFastCapture->sq();
5783 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07005784 bool didModify = false;
5785 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005786 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
5787 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
5788 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5789 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5790 if (old == -1) {
5791 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5792 }
5793 }
5794 state->mCommand = FastCaptureState::READ_WRITE;
5795#if 0 // FIXME
5796 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08005797 FastThreadDumpState::kSamplingNforLowRamDevice :
5798 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005799#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07005800 didModify = true;
5801 }
5802 audio_track_cblk_t *cblkOld = state->mCblk;
5803 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
5804 if (cblkNew != cblkOld) {
5805 state->mCblk = cblkNew;
5806 // block until acked if removing a fast track
5807 if (cblkOld != NULL) {
5808 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
5809 }
5810 didModify = true;
5811 }
5812 sq->end(didModify);
5813 if (didModify) {
5814 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005815#if 0
5816 if (kUseFastCapture == FastCapture_Dynamic) {
5817 mNormalSource = mPipeSource;
5818 }
5819#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005820 }
5821 }
5822
Glenn Kasten735f45f2014-08-18 15:51:59 -07005823 // now run the fast track destructor with thread mutex unlocked
5824 fastTrackToRemove.clear();
5825
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005826 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
5827 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
5828 // slow, then this RecordThread will overrun by not calling HAL read often enough.
5829 // If destination is non-contiguous, first read past the nominal end of buffer, then
5830 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005831
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005832 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005833 ssize_t framesRead;
5834
5835 // If an NBAIO source is present, use it to read the normal capture's data
5836 if (mPipeSource != 0) {
5837 size_t framesToRead = mBufferSize / mFrameSize;
Andy Hung57446612015-04-19 23:56:46 -07005838 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005839 framesToRead, AudioBufferProvider::kInvalidPTS);
5840 if (framesRead == 0) {
5841 // since pipe is non-blocking, simulate blocking input
5842 sleepUs = (framesToRead * 1000000LL) / mSampleRate;
5843 }
5844 // otherwise use the HAL / AudioStreamIn directly
5845 } else {
5846 ssize_t bytesRead = mInput->stream->read(mInput->stream,
Andy Hung57446612015-04-19 23:56:46 -07005847 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005848 if (bytesRead < 0) {
5849 framesRead = bytesRead;
5850 } else {
5851 framesRead = bytesRead / mFrameSize;
5852 }
5853 }
5854
5855 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
5856 ALOGE("read failed: framesRead=%d", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005857 // Force input into standby so that it tries to recover at next read attempt
5858 inputStandBy();
5859 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005860 }
5861 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005862 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005863 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005864 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005865
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005866 if (mTeeSink != 0) {
Andy Hung57446612015-04-19 23:56:46 -07005867 (void) mTeeSink->write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005868 }
5869 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005870 {
5871 size_t part1 = mRsmpInFramesP2 - rear;
5872 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07005873 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005874 (framesRead - part1) * mFrameSize);
5875 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005876 }
5877 rear = mRsmpInRear += framesRead;
5878
5879 size = activeTracks.size();
5880 // loop over each active track
5881 for (size_t i = 0; i < size; i++) {
5882 activeTrack = activeTracks[i];
5883
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005884 // skip fast tracks, as those are handled directly by FastCapture
5885 if (activeTrack->isFastTrack()) {
5886 continue;
5887 }
5888
Andy Hung73c02e42015-03-29 01:13:58 -07005889 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07005890 // TODO: Update the activeTrack buffer converter in case of reconfigure.
5891
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005892 enum {
5893 OVERRUN_UNKNOWN,
5894 OVERRUN_TRUE,
5895 OVERRUN_FALSE
5896 } overrun = OVERRUN_UNKNOWN;
5897
5898 // loop over getNextBuffer to handle circular sink
5899 for (;;) {
5900
5901 activeTrack->mSink.frameCount = ~0;
5902 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
5903 size_t framesOut = activeTrack->mSink.frameCount;
5904 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
5905
Andy Hung73c02e42015-03-29 01:13:58 -07005906 // check available frames and handle overrun conditions
5907 // if the record track isn't draining fast enough.
5908 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005909 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07005910 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
5911 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005912 overrun = OVERRUN_TRUE;
5913 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005914 if (framesOut == 0 || framesIn == 0) {
5915 break;
5916 }
5917
Andy Hung6770c6f2015-04-07 13:43:36 -07005918 // Don't allow framesOut to be larger than what is possible with resampling
5919 // from framesIn.
5920 // This isn't strictly necessary but helps limit buffer resizing in
5921 // RecordBufferConverter. TODO: remove when no longer needed.
5922 framesOut = min(framesOut,
5923 destinationFramesPossible(
5924 framesIn, mSampleRate, activeTrack->mSampleRate));
Andy Hung97a893e2015-03-29 01:03:07 -07005925 // process frames from the RecordThread buffer provider to the RecordTrack buffer
5926 framesOut = activeTrack->mRecordBufferConverter->convert(
5927 activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005928
5929 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
5930 overrun = OVERRUN_FALSE;
5931 }
5932
5933 if (activeTrack->mFramesToDrop == 0) {
5934 if (framesOut > 0) {
5935 activeTrack->mSink.frameCount = framesOut;
5936 activeTrack->releaseBuffer(&activeTrack->mSink);
5937 }
5938 } else {
5939 // FIXME could do a partial drop of framesOut
5940 if (activeTrack->mFramesToDrop > 0) {
5941 activeTrack->mFramesToDrop -= framesOut;
5942 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005943 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005944 }
5945 } else {
5946 activeTrack->mFramesToDrop += framesOut;
5947 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
5948 activeTrack->mSyncStartEvent->isCancelled()) {
5949 ALOGW("Synced record %s, session %d, trigger session %d",
5950 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
5951 activeTrack->sessionId(),
5952 (activeTrack->mSyncStartEvent != 0) ?
5953 activeTrack->mSyncStartEvent->triggerSession() : 0);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005954 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005955 }
5956 }
5957 }
5958
5959 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005960 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005961 }
5962 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005963
5964 switch (overrun) {
5965 case OVERRUN_TRUE:
5966 // client isn't retrieving buffers fast enough
5967 if (!activeTrack->setOverflow()) {
5968 nsecs_t now = systemTime();
5969 // FIXME should lastWarning per track?
5970 if ((now - lastWarning) > kWarningThrottleNs) {
5971 ALOGW("RecordThread: buffer overflow");
5972 lastWarning = now;
5973 }
5974 }
5975 break;
5976 case OVERRUN_FALSE:
5977 activeTrack->clearOverflow();
5978 break;
5979 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005980 break;
5981 }
5982
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005983 }
5984
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005985unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08005986 // enable changes in effect chain
5987 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005988 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08005989 }
5990
Glenn Kasten93e471f2013-08-19 08:40:07 -07005991 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08005992
5993 {
5994 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07005995 for (size_t i = 0; i < mTracks.size(); i++) {
5996 sp<RecordTrack> track = mTracks[i];
5997 track->invalidate();
5998 }
Glenn Kasten2b806402013-11-20 16:37:38 -08005999 mActiveTracks.clear();
6000 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08006001 mStartStopCond.broadcast();
6002 }
6003
6004 releaseWakeLock();
6005
6006 ALOGV("RecordThread %p exiting", this);
6007 return false;
6008}
6009
Glenn Kasten93e471f2013-08-19 08:40:07 -07006010void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08006011{
6012 if (!mStandby) {
6013 inputStandBy();
6014 mStandby = true;
6015 }
6016}
6017
6018void AudioFlinger::RecordThread::inputStandBy()
6019{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006020 // Idle the fast capture if it's currently running
6021 if (mFastCapture != 0) {
6022 FastCaptureStateQueue *sq = mFastCapture->sq();
6023 FastCaptureState *state = sq->begin();
6024 if (!(state->mCommand & FastCaptureState::IDLE)) {
6025 state->mCommand = FastCaptureState::COLD_IDLE;
6026 state->mColdFutexAddr = &mFastCaptureFutex;
6027 state->mColdGen++;
6028 mFastCaptureFutex = 0;
6029 sq->end();
6030 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
6031 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
6032#if 0
6033 if (kUseFastCapture == FastCapture_Dynamic) {
6034 // FIXME
6035 }
6036#endif
6037#ifdef AUDIO_WATCHDOG
6038 // FIXME
6039#endif
6040 } else {
6041 sq->end(false /*didModify*/);
6042 }
6043 }
Eric Laurent81784c32012-11-19 14:55:58 -08006044 mInput->stream->common.standby(&mInput->stream->common);
6045}
6046
Glenn Kasten05997e22014-03-13 15:08:33 -07006047// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07006048sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08006049 const sp<AudioFlinger::Client>& client,
6050 uint32_t sampleRate,
6051 audio_format_t format,
6052 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08006053 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08006054 int sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07006055 size_t *notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08006056 int uid,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07006057 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08006058 pid_t tid,
6059 status_t *status)
6060{
Glenn Kasten74935e42013-12-19 08:56:45 -08006061 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08006062 sp<RecordTrack> track;
6063 status_t lStatus;
6064
Glenn Kasten90e58b12013-07-31 16:16:02 -07006065 // client expresses a preference for FAST, but we get the final say
6066 if (*flags & IAudioFlinger::TRACK_FAST) {
6067 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07006068 // we formerly checked for a callback handler (non-0 tid),
6069 // but that is no longer required for TRANSFER_OBTAIN mode
6070 //
Glenn Kasten74105912014-07-03 12:28:53 -07006071 // frame count is not specified, or is exactly the pipe depth
6072 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006073 // PCM data
6074 audio_is_linear_pcm(format) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006075 // native format
6076 (format == mFormat) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006077 // native channel mask
6078 (channelMask == mChannelMask) &&
6079 // native hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07006080 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006081 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006082 hasFastCapture() &&
6083 // there are sufficient fast track slots available
6084 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07006085 ) {
Glenn Kasten74105912014-07-03 12:28:53 -07006086 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%u mFrameCount=%u",
Glenn Kasten90e58b12013-07-31 16:16:02 -07006087 frameCount, mFrameCount);
6088 } else {
Glenn Kasten74105912014-07-03 12:28:53 -07006089 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%u mFrameCount=%u mPipeFramesP2=%u "
6090 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006091 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Glenn Kasten74105912014-07-03 12:28:53 -07006092 frameCount, mFrameCount, mPipeFramesP2,
6093 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
6094 hasFastCapture(), tid, mFastTrackAvail);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006095 *flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kasten74105912014-07-03 12:28:53 -07006096 }
6097 }
6098
6099 // compute track buffer size in frames, and suggest the notification frame count
6100 if (*flags & IAudioFlinger::TRACK_FAST) {
6101 // fast track: frame count is exactly the pipe depth
6102 frameCount = mPipeFramesP2;
6103 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
6104 *notificationFrames = mFrameCount;
6105 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006106 // not fast track: max notification period is resampled equivalent of one HAL buffer time
6107 // or 20 ms if there is a fast capture
6108 // TODO This could be a roundupRatio inline, and const
6109 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
6110 * sampleRate + mSampleRate - 1) / mSampleRate;
6111 // minimum number of notification periods is at least kMinNotifications,
6112 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
6113 static const size_t kMinNotifications = 3;
6114 static const uint32_t kMinMs = 30;
6115 // TODO This could be a roundupRatio inline
6116 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
6117 // TODO This could be a roundupRatio inline
6118 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
6119 maxNotificationFrames;
6120 const size_t minFrameCount = maxNotificationFrames *
6121 max(kMinNotifications, minNotificationsByMs);
6122 frameCount = max(frameCount, minFrameCount);
6123 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
6124 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07006125 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07006126 }
Glenn Kasten74935e42013-12-19 08:56:45 -08006127 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07006128
Glenn Kasten15e57982013-09-24 11:52:37 -07006129 lStatus = initCheck();
6130 if (lStatus != NO_ERROR) {
6131 ALOGE("createRecordTrack_l() audio driver not initialized");
6132 goto Exit;
6133 }
Eric Laurent81784c32012-11-19 14:55:58 -08006134
6135 { // scope for mLock
6136 Mutex::Autolock _l(mLock);
6137
6138 track = new RecordTrack(this, client, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07006139 format, channelMask, frameCount, NULL, sessionId, uid,
6140 *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08006141
Glenn Kasten03003332013-08-06 15:40:54 -07006142 lStatus = track->initCheck();
6143 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07006144 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08006145 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08006146 goto Exit;
6147 }
6148 mTracks.add(track);
6149
6150 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6151 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6152 mAudioFlinger->btNrecIsOff();
6153 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6154 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006155
6156 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
6157 pid_t callingPid = IPCThreadState::self()->getCallingPid();
6158 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
6159 // so ask activity manager to do this on our behalf
6160 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
6161 }
Eric Laurent81784c32012-11-19 14:55:58 -08006162 }
Glenn Kasten05997e22014-03-13 15:08:33 -07006163
Eric Laurent81784c32012-11-19 14:55:58 -08006164 lStatus = NO_ERROR;
6165
6166Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07006167 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08006168 return track;
6169}
6170
6171status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
6172 AudioSystem::sync_event_t event,
6173 int triggerSession)
6174{
6175 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
6176 sp<ThreadBase> strongMe = this;
6177 status_t status = NO_ERROR;
6178
6179 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006180 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006181 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006182 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08006183 triggerSession,
6184 recordTrack->sessionId(),
6185 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006186 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08006187 // Sync event can be cancelled by the trigger session if the track is not in a
6188 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006189 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006190 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006191 } else {
6192 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006193 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006194 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08006195 }
6196 }
6197
6198 {
Glenn Kasten47c20702013-08-13 15:37:35 -07006199 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08006200 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006201 if (mActiveTracks.indexOf(recordTrack) >= 0) {
6202 if (recordTrack->mState == TrackBase::PAUSING) {
6203 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006204 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006205 } else {
6206 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08006207 }
6208 return status;
6209 }
6210
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006211 // TODO consider other ways of handling this, such as changing the state to :STARTING and
6212 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
6213 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006214 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08006215 mActiveTracks.add(recordTrack);
6216 mActiveTracksGen++;
Eric Laurent83b88082014-06-20 18:31:16 -07006217 status_t status = NO_ERROR;
6218 if (recordTrack->isExternalTrack()) {
6219 mLock.unlock();
Eric Laurent4dc68062014-07-28 17:26:49 -07006220 status = AudioSystem::startInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006221 mLock.lock();
6222 // FIXME should verify that recordTrack is still in mActiveTracks
6223 if (status != NO_ERROR) {
6224 mActiveTracks.remove(recordTrack);
6225 mActiveTracksGen++;
6226 recordTrack->clearSyncStartEvent();
6227 ALOGV("RecordThread::start error %d", status);
6228 return status;
6229 }
Eric Laurent81784c32012-11-19 14:55:58 -08006230 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006231 // Catch up with current buffer indices if thread is already running.
6232 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
6233 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
6234 // see previously buffered data before it called start(), but with greater risk of overrun.
6235
Andy Hung73c02e42015-03-29 01:13:58 -07006236 recordTrack->mResamplerBufferProvider->reset();
Andy Hung97a893e2015-03-29 01:03:07 -07006237 // clear any converter state as new data will be discontinuous
6238 recordTrack->mRecordBufferConverter->reset();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006239 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08006240 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08006241 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08006242 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006243 ALOGV("Record failed to start");
6244 status = BAD_VALUE;
6245 goto startError;
6246 }
Eric Laurent81784c32012-11-19 14:55:58 -08006247 return status;
6248 }
Glenn Kasten7c027242012-12-26 14:43:16 -08006249
Eric Laurent81784c32012-11-19 14:55:58 -08006250startError:
Eric Laurent83b88082014-06-20 18:31:16 -07006251 if (recordTrack->isExternalTrack()) {
Eric Laurent4dc68062014-07-28 17:26:49 -07006252 AudioSystem::stopInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006253 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006254 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006255 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08006256 return status;
6257}
6258
Eric Laurent81784c32012-11-19 14:55:58 -08006259void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6260{
6261 sp<SyncEvent> strongEvent = event.promote();
6262
6263 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08006264 sp<RefBase> ptr = strongEvent->cookie().promote();
6265 if (ptr != 0) {
6266 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
6267 recordTrack->handleSyncStartEvent(strongEvent);
6268 }
Eric Laurent81784c32012-11-19 14:55:58 -08006269 }
6270}
6271
Glenn Kastena8356f62013-07-25 14:37:52 -07006272bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08006273 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07006274 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006275 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08006276 return false;
6277 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006278 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08006279 recordTrack->mState = TrackBase::PAUSING;
6280 // do not wait for mStartStopCond if exiting
6281 if (exitPending()) {
6282 return true;
6283 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006284 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08006285 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006286 // if we have been restarted, recordTrack is in mActiveTracks here
6287 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006288 ALOGV("Record stopped OK");
6289 return true;
6290 }
6291 return false;
6292}
6293
Glenn Kasten0f11b512014-01-31 16:18:54 -08006294bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08006295{
6296 return false;
6297}
6298
Glenn Kasten0f11b512014-01-31 16:18:54 -08006299status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006300{
6301#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
6302 if (!isValidSyncEvent(event)) {
6303 return BAD_VALUE;
6304 }
6305
6306 int eventSession = event->triggerSession();
6307 status_t ret = NAME_NOT_FOUND;
6308
6309 Mutex::Autolock _l(mLock);
6310
6311 for (size_t i = 0; i < mTracks.size(); i++) {
6312 sp<RecordTrack> track = mTracks[i];
6313 if (eventSession == track->sessionId()) {
6314 (void) track->setSyncEvent(event);
6315 ret = NO_ERROR;
6316 }
6317 }
6318 return ret;
6319#else
6320 return BAD_VALUE;
6321#endif
6322}
6323
6324// destroyTrack_l() must be called with ThreadBase::mLock held
6325void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6326{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006327 track->terminate();
6328 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08006329 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08006330 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006331 removeTrack_l(track);
6332 }
6333}
6334
6335void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6336{
6337 mTracks.remove(track);
6338 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006339 if (track->isFastTrack()) {
6340 ALOG_ASSERT(!mFastTrackAvail);
6341 mFastTrackAvail = true;
6342 }
Eric Laurent81784c32012-11-19 14:55:58 -08006343}
6344
6345void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6346{
6347 dumpInternals(fd, args);
6348 dumpTracks(fd, args);
6349 dumpEffectChains(fd, args);
6350}
6351
6352void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6353{
Elliott Hughes87cebad2014-05-22 10:14:43 -07006354 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08006355
Glenn Kasten44182c22015-03-05 17:12:23 -08006356 dumpBase(fd, args);
6357
6358 if (mActiveTracks.size() == 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006359 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006360 }
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006361 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006362 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08006363
6364 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
6365 const FastCaptureDumpState copy(mFastCaptureDumpState);
6366 copy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006367}
6368
Glenn Kasten0f11b512014-01-31 16:18:54 -08006369void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006370{
6371 const size_t SIZE = 256;
6372 char buffer[SIZE];
6373 String8 result;
6374
Marco Nelissenb2208842014-02-07 14:00:50 -08006375 size_t numtracks = mTracks.size();
6376 size_t numactive = mActiveTracks.size();
6377 size_t numactiveseen = 0;
Elliott Hughes87cebad2014-05-22 10:14:43 -07006378 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08006379 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006380 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08006381 RecordTrack::appendDumpHeader(result);
6382 for (size_t i = 0; i < numtracks ; ++i) {
6383 sp<RecordTrack> track = mTracks[i];
6384 if (track != 0) {
6385 bool active = mActiveTracks.indexOf(track) >= 0;
6386 if (active) {
6387 numactiveseen++;
6388 }
6389 track->dump(buffer, SIZE, active);
6390 result.append(buffer);
6391 }
Eric Laurent81784c32012-11-19 14:55:58 -08006392 }
Marco Nelissenb2208842014-02-07 14:00:50 -08006393 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006394 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006395 }
6396
Marco Nelissenb2208842014-02-07 14:00:50 -08006397 if (numactiveseen != numactive) {
6398 snprintf(buffer, SIZE, " The following tracks are in the active list but"
6399 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006400 result.append(buffer);
6401 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08006402 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08006403 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08006404 if (mTracks.indexOf(track) < 0) {
6405 track->dump(buffer, SIZE, true);
6406 result.append(buffer);
6407 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006408 }
Eric Laurent81784c32012-11-19 14:55:58 -08006409
6410 }
6411 write(fd, result.string(), result.size());
6412}
6413
Andy Hung73c02e42015-03-29 01:13:58 -07006414
6415void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
6416{
6417 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6418 RecordThread *recordThread = (RecordThread *) threadBase.get();
6419 mRsmpInFront = recordThread->mRsmpInRear;
6420 mRsmpInUnrel = 0;
6421}
6422
6423void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
6424 size_t *framesAvailable, bool *hasOverrun)
6425{
6426 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6427 RecordThread *recordThread = (RecordThread *) threadBase.get();
6428 const int32_t rear = recordThread->mRsmpInRear;
6429 const int32_t front = mRsmpInFront;
6430 const ssize_t filled = rear - front;
6431
6432 size_t framesIn;
6433 bool overrun = false;
6434 if (filled < 0) {
6435 // should not happen, but treat like a massive overrun and re-sync
6436 framesIn = 0;
6437 mRsmpInFront = rear;
6438 overrun = true;
6439 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
6440 framesIn = (size_t) filled;
6441 } else {
6442 // client is not keeping up with server, but give it latest data
6443 framesIn = recordThread->mRsmpInFrames;
6444 mRsmpInFront = /* front = */ rear - framesIn;
6445 overrun = true;
6446 }
6447 if (framesAvailable != NULL) {
6448 *framesAvailable = framesIn;
6449 }
6450 if (hasOverrun != NULL) {
6451 *hasOverrun = overrun;
6452 }
6453}
6454
Eric Laurent81784c32012-11-19 14:55:58 -08006455// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006456status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
6457 AudioBufferProvider::Buffer* buffer, int64_t pts __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006458{
Andy Hung73c02e42015-03-29 01:13:58 -07006459 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006460 if (threadBase == 0) {
6461 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006462 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006463 return NOT_ENOUGH_DATA;
6464 }
6465 RecordThread *recordThread = (RecordThread *) threadBase.get();
6466 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07006467 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07006468 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006469 // FIXME should not be P2 (don't want to increase latency)
6470 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006471 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07006472 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006473 front &= recordThread->mRsmpInFramesP2 - 1;
6474 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07006475 if (part1 > (size_t) filled) {
6476 part1 = filled;
6477 }
6478 size_t ask = buffer->frameCount;
6479 ALOG_ASSERT(ask > 0);
6480 if (part1 > ask) {
6481 part1 = ask;
6482 }
6483 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07006484 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07006485 buffer->raw = NULL;
6486 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07006487 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07006488 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08006489 }
6490
Andy Hung57446612015-04-19 23:56:46 -07006491 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07006492 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07006493 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08006494 return NO_ERROR;
6495}
6496
6497// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006498void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
6499 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006500{
Glenn Kasten85948432013-08-19 12:09:05 -07006501 size_t stepCount = buffer->frameCount;
6502 if (stepCount == 0) {
6503 return;
6504 }
Andy Hung73c02e42015-03-29 01:13:58 -07006505 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
6506 mRsmpInUnrel -= stepCount;
6507 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07006508 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006509 buffer->frameCount = 0;
6510}
6511
Andy Hung97a893e2015-03-29 01:03:07 -07006512AudioFlinger::RecordThread::RecordBufferConverter::RecordBufferConverter(
6513 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6514 uint32_t srcSampleRate,
6515 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6516 uint32_t dstSampleRate) :
6517 mSrcChannelMask(AUDIO_CHANNEL_INVALID), // updateParameters will set following vars
6518 // mSrcFormat
6519 // mSrcSampleRate
6520 // mDstChannelMask
6521 // mDstFormat
6522 // mDstSampleRate
6523 // mSrcChannelCount
6524 // mDstChannelCount
6525 // mDstFrameSize
6526 mBuf(NULL), mBufFrames(0), mBufFrameSize(0),
Andy Hungd330ee42015-04-20 13:23:41 -07006527 mResampler(NULL),
6528 mIsLegacyDownmix(false),
6529 mIsLegacyUpmix(false),
6530 mRequiresFloat(false),
6531 mInputConverterProvider(NULL)
Andy Hung97a893e2015-03-29 01:03:07 -07006532{
6533 (void)updateParameters(srcChannelMask, srcFormat, srcSampleRate,
6534 dstChannelMask, dstFormat, dstSampleRate);
6535}
6536
6537AudioFlinger::RecordThread::RecordBufferConverter::~RecordBufferConverter() {
6538 free(mBuf);
6539 delete mResampler;
Andy Hungd330ee42015-04-20 13:23:41 -07006540 delete mInputConverterProvider;
Andy Hung97a893e2015-03-29 01:03:07 -07006541}
6542
6543size_t AudioFlinger::RecordThread::RecordBufferConverter::convert(void *dst,
6544 AudioBufferProvider *provider, size_t frames)
6545{
Andy Hungd330ee42015-04-20 13:23:41 -07006546 if (mInputConverterProvider != NULL) {
6547 mInputConverterProvider->setBufferProvider(provider);
6548 provider = mInputConverterProvider;
6549 }
6550
6551 if (mResampler == NULL) {
Andy Hung97a893e2015-03-29 01:03:07 -07006552 ALOGVV("NO RESAMPLING sampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6553 mSrcSampleRate, mSrcFormat, mDstFormat);
6554
6555 AudioBufferProvider::Buffer buffer;
6556 for (size_t i = frames; i > 0; ) {
6557 buffer.frameCount = i;
6558 status_t status = provider->getNextBuffer(&buffer, 0);
6559 if (status != OK || buffer.frameCount == 0) {
6560 frames -= i; // cannot fill request.
6561 break;
6562 }
Andy Hungd330ee42015-04-20 13:23:41 -07006563 // format convert to destination buffer
6564 convertNoResampler(dst, buffer.raw, buffer.frameCount);
Andy Hung97a893e2015-03-29 01:03:07 -07006565
6566 dst = (int8_t*)dst + buffer.frameCount * mDstFrameSize;
6567 i -= buffer.frameCount;
6568 provider->releaseBuffer(&buffer);
6569 }
6570 } else {
6571 ALOGVV("RESAMPLING mSrcSampleRate:%u mDstSampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6572 mSrcSampleRate, mDstSampleRate, mSrcFormat, mDstFormat);
6573
Andy Hungd330ee42015-04-20 13:23:41 -07006574 // reallocate buffer if needed
6575 if (mBufFrameSize != 0 && mBufFrames < frames) {
6576 free(mBuf);
6577 mBufFrames = frames;
6578 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
6579 }
Andy Hung97a893e2015-03-29 01:03:07 -07006580 // resampler accumulates, but we only have one source track
Andy Hungd330ee42015-04-20 13:23:41 -07006581 memset(mBuf, 0, frames * mBufFrameSize);
6582 frames = mResampler->resample((int32_t*)mBuf, frames, provider);
6583 // format convert to destination buffer
6584 convertResampler(dst, mBuf, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006585 }
6586 return frames;
6587}
6588
6589status_t AudioFlinger::RecordThread::RecordBufferConverter::updateParameters(
6590 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6591 uint32_t srcSampleRate,
6592 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6593 uint32_t dstSampleRate)
6594{
6595 // quick evaluation if there is any change.
6596 if (mSrcFormat == srcFormat
6597 && mSrcChannelMask == srcChannelMask
6598 && mSrcSampleRate == srcSampleRate
6599 && mDstFormat == dstFormat
6600 && mDstChannelMask == dstChannelMask
6601 && mDstSampleRate == dstSampleRate) {
6602 return NO_ERROR;
6603 }
6604
Andy Hungdb4c0312015-05-06 08:46:52 -07006605 ALOGV("RecordBufferConverter updateParameters srcMask:%#x dstMask:%#x"
6606 " srcFormat:%#x dstFormat:%#x srcRate:%u dstRate:%u",
6607 srcChannelMask, dstChannelMask, srcFormat, dstFormat, srcSampleRate, dstSampleRate);
Andy Hung97a893e2015-03-29 01:03:07 -07006608 const bool valid =
6609 audio_is_input_channel(srcChannelMask)
6610 && audio_is_input_channel(dstChannelMask)
6611 && audio_is_valid_format(srcFormat) && audio_is_linear_pcm(srcFormat)
6612 && audio_is_valid_format(dstFormat) && audio_is_linear_pcm(dstFormat)
6613 && (srcSampleRate <= dstSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX)
6614 ; // no upsampling checks for now
6615 if (!valid) {
6616 return BAD_VALUE;
6617 }
6618
6619 mSrcFormat = srcFormat;
6620 mSrcChannelMask = srcChannelMask;
6621 mSrcSampleRate = srcSampleRate;
6622 mDstFormat = dstFormat;
6623 mDstChannelMask = dstChannelMask;
6624 mDstSampleRate = dstSampleRate;
6625
6626 // compute derived parameters
6627 mSrcChannelCount = audio_channel_count_from_in_mask(srcChannelMask);
6628 mDstChannelCount = audio_channel_count_from_in_mask(dstChannelMask);
6629 mDstFrameSize = mDstChannelCount * audio_bytes_per_sample(mDstFormat);
6630
Andy Hungd330ee42015-04-20 13:23:41 -07006631 // do we need to resample?
6632 delete mResampler;
6633 mResampler = NULL;
6634 if (mSrcSampleRate != mDstSampleRate) {
6635 mResampler = AudioResampler::create(AUDIO_FORMAT_PCM_FLOAT,
6636 mSrcChannelCount, mDstSampleRate);
6637 mResampler->setSampleRate(mSrcSampleRate);
6638 mResampler->setVolume(AudioMixer::UNITY_GAIN_FLOAT, AudioMixer::UNITY_GAIN_FLOAT);
6639 }
6640
6641 // are we running legacy channel conversion modes?
6642 mIsLegacyDownmix = (mSrcChannelMask == AUDIO_CHANNEL_IN_STEREO
6643 || mSrcChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK)
6644 && mDstChannelMask == AUDIO_CHANNEL_IN_MONO;
6645 mIsLegacyUpmix = mSrcChannelMask == AUDIO_CHANNEL_IN_MONO
6646 && (mDstChannelMask == AUDIO_CHANNEL_IN_STEREO
6647 || mDstChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK);
6648
6649 // do we need to process in float?
6650 mRequiresFloat = mResampler != NULL || mIsLegacyDownmix || mIsLegacyUpmix;
6651
6652 // do we need a staging buffer to convert for destination (we can still optimize this)?
6653 // we use mBufFrameSize > 0 to indicate both frame size as well as buffer necessity
6654 if (mResampler != NULL) {
6655 mBufFrameSize = max(mSrcChannelCount, FCC_2)
6656 * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
Andy Hunga97630b2015-07-22 23:27:24 -07006657 } else if (mIsLegacyUpmix || mIsLegacyDownmix) { // legacy modes always float
Andy Hungd330ee42015-04-20 13:23:41 -07006658 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
6659 } else if (mSrcChannelMask != mDstChannelMask && mDstFormat != mSrcFormat) {
Andy Hung97a893e2015-03-29 01:03:07 -07006660 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(mSrcFormat);
6661 } else {
6662 mBufFrameSize = 0;
6663 }
6664 mBufFrames = 0; // force the buffer to be resized.
6665
Andy Hungd330ee42015-04-20 13:23:41 -07006666 // do we need an input converter buffer provider to give us float?
6667 delete mInputConverterProvider;
6668 mInputConverterProvider = NULL;
6669 if (mRequiresFloat && mSrcFormat != AUDIO_FORMAT_PCM_FLOAT) {
6670 mInputConverterProvider = new ReformatBufferProvider(
6671 audio_channel_count_from_in_mask(mSrcChannelMask),
6672 mSrcFormat,
6673 AUDIO_FORMAT_PCM_FLOAT,
6674 256 /* provider buffer frame count */);
6675 }
6676
6677 // do we need a remixer to do channel mask conversion
6678 if (!mIsLegacyDownmix && !mIsLegacyUpmix && mSrcChannelMask != mDstChannelMask) {
6679 (void) memcpy_by_index_array_initialization_from_channel_mask(
6680 mIdxAry, ARRAY_SIZE(mIdxAry), mDstChannelMask, mSrcChannelMask);
Andy Hung97a893e2015-03-29 01:03:07 -07006681 }
6682 return NO_ERROR;
6683}
6684
Andy Hungd330ee42015-04-20 13:23:41 -07006685void AudioFlinger::RecordThread::RecordBufferConverter::convertNoResampler(
6686 void *dst, const void *src, size_t frames)
Andy Hung97a893e2015-03-29 01:03:07 -07006687{
Andy Hungd330ee42015-04-20 13:23:41 -07006688 // src is native type unless there is legacy upmix or downmix, whereupon it is float.
Andy Hung97a893e2015-03-29 01:03:07 -07006689 if (mBufFrameSize != 0 && mBufFrames < frames) {
6690 free(mBuf);
6691 mBufFrames = frames;
6692 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
6693 }
Andy Hungd330ee42015-04-20 13:23:41 -07006694 // do we need to do legacy upmix and downmix?
6695 if (mIsLegacyUpmix || mIsLegacyDownmix) {
Andy Hung97a893e2015-03-29 01:03:07 -07006696 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07006697 if (mIsLegacyUpmix) {
6698 upmix_to_stereo_float_from_mono_float((float *)dstBuf,
6699 (const float *)src, frames);
6700 } else /*mIsLegacyDownmix */ {
6701 downmix_to_mono_float_from_stereo_float((float *)dstBuf,
6702 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006703 }
Andy Hungd330ee42015-04-20 13:23:41 -07006704 if (mBuf != NULL) {
6705 memcpy_by_audio_format(dst, mDstFormat, mBuf, AUDIO_FORMAT_PCM_FLOAT,
6706 frames * mDstChannelCount);
6707 }
6708 return;
6709 }
6710 // do we need to do channel mask conversion?
6711 if (mSrcChannelMask != mDstChannelMask) {
Andy Hung97a893e2015-03-29 01:03:07 -07006712 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07006713 memcpy_by_index_array(dstBuf, mDstChannelCount,
6714 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mSrcFormat), frames);
6715 if (dstBuf == dst) {
6716 return; // format is the same
6717 }
6718 }
6719 // convert to destination buffer
6720 const void *convertBuf = mBuf != NULL ? mBuf : src;
6721 memcpy_by_audio_format(dst, mDstFormat, convertBuf, mSrcFormat,
6722 frames * mDstChannelCount);
6723}
6724
6725void AudioFlinger::RecordThread::RecordBufferConverter::convertResampler(
6726 void *dst, /*not-a-const*/ void *src, size_t frames)
6727{
6728 // src buffer format is ALWAYS float when entering this routine
6729 if (mIsLegacyUpmix) {
6730 ; // mono to stereo already handled by resampler
6731 } else if (mIsLegacyDownmix
6732 || (mSrcChannelMask == mDstChannelMask && mSrcChannelCount == 1)) {
6733 // the resampler outputs stereo for mono input channel (a feature?)
6734 // must convert to mono
6735 downmix_to_mono_float_from_stereo_float((float *)src,
6736 (const float *)src, frames);
6737 } else if (mSrcChannelMask != mDstChannelMask) {
6738 // convert to mono channel again for channel mask conversion (could be skipped
6739 // with further optimization).
Andy Hung97a893e2015-03-29 01:03:07 -07006740 if (mSrcChannelCount == 1) {
Andy Hungd330ee42015-04-20 13:23:41 -07006741 downmix_to_mono_float_from_stereo_float((float *)src,
6742 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006743 }
Andy Hungd330ee42015-04-20 13:23:41 -07006744 // convert to destination format (in place, OK as float is larger than other types)
6745 if (mDstFormat != AUDIO_FORMAT_PCM_FLOAT) {
6746 memcpy_by_audio_format(src, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
6747 frames * mSrcChannelCount);
6748 }
6749 // channel convert and save to dst
6750 memcpy_by_index_array(dst, mDstChannelCount,
6751 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mDstFormat), frames);
6752 return;
Andy Hung97a893e2015-03-29 01:03:07 -07006753 }
Andy Hungd330ee42015-04-20 13:23:41 -07006754 // convert to destination format and save to dst
6755 memcpy_by_audio_format(dst, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
6756 frames * mDstChannelCount);
Andy Hung97a893e2015-03-29 01:03:07 -07006757}
6758
Eric Laurent10351942014-05-08 18:49:52 -07006759bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
6760 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006761{
6762 bool reconfig = false;
6763
Eric Laurent10351942014-05-08 18:49:52 -07006764 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006765
Eric Laurent10351942014-05-08 18:49:52 -07006766 audio_format_t reqFormat = mFormat;
6767 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07006768 // 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 -07006769 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
6770
6771 AudioParameter param = AudioParameter(keyValuePair);
6772 int value;
6773 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
6774 // channel count change can be requested. Do we mandate the first client defines the
6775 // HAL sampling rate and channel count or do we allow changes on the fly?
6776 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6777 samplingRate = value;
6778 reconfig = true;
6779 }
6780 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07006781 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07006782 status = BAD_VALUE;
6783 } else {
6784 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08006785 reconfig = true;
6786 }
Eric Laurent10351942014-05-08 18:49:52 -07006787 }
6788 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
6789 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07006790 if (!audio_is_input_channel(mask) ||
6791 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07006792 status = BAD_VALUE;
6793 } else {
6794 channelMask = mask;
6795 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006796 }
Eric Laurent10351942014-05-08 18:49:52 -07006797 }
6798 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6799 // do not accept frame count changes if tracks are open as the track buffer
6800 // size depends on frame count and correct behavior would not be guaranteed
6801 // if frame count is changed after track creation
6802 if (mActiveTracks.size() > 0) {
6803 status = INVALID_OPERATION;
6804 } else {
6805 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006806 }
Eric Laurent10351942014-05-08 18:49:52 -07006807 }
6808 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6809 // forward device change to effects that have requested to be
6810 // aware of attached audio device.
6811 for (size_t i = 0; i < mEffectChains.size(); i++) {
6812 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08006813 }
Eric Laurent81784c32012-11-19 14:55:58 -08006814
Eric Laurent10351942014-05-08 18:49:52 -07006815 // store input device and output device but do not forward output device to audio HAL.
6816 // Note that status is ignored by the caller for output device
6817 // (see AudioFlinger::setParameters()
6818 if (audio_is_output_devices(value)) {
6819 mOutDevice = value;
6820 status = BAD_VALUE;
6821 } else {
6822 mInDevice = value;
Eric Laurente8726fe2015-06-26 09:39:24 -07006823 if (value != AUDIO_DEVICE_NONE) {
6824 mPrevInDevice = value;
6825 }
Eric Laurent10351942014-05-08 18:49:52 -07006826 // disable AEC and NS if the device is a BT SCO headset supporting those
6827 // pre processings
6828 if (mTracks.size() > 0) {
6829 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6830 mAudioFlinger->btNrecIsOff();
6831 for (size_t i = 0; i < mTracks.size(); i++) {
6832 sp<RecordTrack> track = mTracks[i];
6833 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
6834 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08006835 }
6836 }
6837 }
Eric Laurent10351942014-05-08 18:49:52 -07006838 }
6839 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
6840 mAudioSource != (audio_source_t)value) {
6841 // forward device change to effects that have requested to be
6842 // aware of attached audio device.
6843 for (size_t i = 0; i < mEffectChains.size(); i++) {
6844 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08006845 }
Eric Laurent10351942014-05-08 18:49:52 -07006846 mAudioSource = (audio_source_t)value;
6847 }
Glenn Kastene198c362013-08-13 09:13:36 -07006848
Eric Laurent10351942014-05-08 18:49:52 -07006849 if (status == NO_ERROR) {
6850 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6851 keyValuePair.string());
6852 if (status == INVALID_OPERATION) {
6853 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006854 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6855 keyValuePair.string());
Eric Laurent10351942014-05-08 18:49:52 -07006856 }
6857 if (reconfig) {
6858 if (status == BAD_VALUE &&
Andy Hung97a893e2015-03-29 01:03:07 -07006859 audio_is_linear_pcm(mInput->stream->common.get_format(&mInput->stream->common)) &&
6860 audio_is_linear_pcm(reqFormat) &&
Eric Laurent10351942014-05-08 18:49:52 -07006861 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
Andy Hung97a893e2015-03-29 01:03:07 -07006862 <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate)) &&
Andy Hunge5412692014-05-16 11:25:07 -07006863 audio_channel_count_from_in_mask(
Andy Hungd1abb8f2015-05-05 23:42:34 -07006864 mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07006865 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006866 }
Eric Laurent10351942014-05-08 18:49:52 -07006867 if (status == NO_ERROR) {
6868 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07006869 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08006870 }
6871 }
Eric Laurent81784c32012-11-19 14:55:58 -08006872 }
Eric Laurent10351942014-05-08 18:49:52 -07006873
Eric Laurent81784c32012-11-19 14:55:58 -08006874 return reconfig;
6875}
6876
6877String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6878{
Eric Laurent81784c32012-11-19 14:55:58 -08006879 Mutex::Autolock _l(mLock);
6880 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07006881 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08006882 }
6883
Glenn Kastend8ea6992013-07-16 14:17:15 -07006884 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
6885 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08006886 free(s);
6887 return out_s8;
6888}
6889
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07006890void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07006891 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
6892
6893 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08006894
6895 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07006896 case AUDIO_INPUT_OPENED:
6897 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07006898 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07006899 desc->mChannelMask = mChannelMask;
6900 desc->mSamplingRate = mSampleRate;
6901 desc->mFormat = mFormat;
6902 desc->mFrameCount = mFrameCount;
6903 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006904 break;
6905
Eric Laurent73e26b62015-04-27 16:55:58 -07006906 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08006907 default:
6908 break;
6909 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07006910 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08006911}
6912
Glenn Kastendeca2ae2014-02-07 10:25:56 -08006913void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006914{
Eric Laurent81784c32012-11-19 14:55:58 -08006915 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
6916 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Andy Hunge5412692014-05-16 11:25:07 -07006917 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Andy Hungd330ee42015-04-20 13:23:41 -07006918 if (mChannelCount > FCC_8) {
6919 ALOGE("HAL channel count %d > %d", mChannelCount, FCC_8);
6920 }
Andy Hung463be252014-07-10 16:56:07 -07006921 mHALFormat = mInput->stream->common.get_format(&mInput->stream->common);
6922 mFormat = mHALFormat;
Andy Hungd330ee42015-04-20 13:23:41 -07006923 if (!audio_is_linear_pcm(mFormat)) {
6924 ALOGE("HAL format %#x is not linear pcm", mFormat);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07006925 }
Eric Laurent665470b2014-07-03 16:37:08 -07006926 mFrameSize = audio_stream_in_frame_size(mInput->stream);
Glenn Kasten548efc92012-11-29 08:48:51 -08006927 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
6928 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006929 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08006930 // 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 -07006931 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08006932 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006933 // A larger value should allow more old data to be read after a track calls start(),
6934 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07006935 //
6936 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08006937 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07006938 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07006939 free(mRsmpInBuffer);
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006940
6941 // TODO optimize audio capture buffer sizes ...
6942 // Here we calculate the size of the sliding buffer used as a source
6943 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
6944 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
6945 // be better to have it derived from the pipe depth in the long term.
6946 // The current value is higher than necessary. However it should not add to latency.
6947
Glenn Kasten85948432013-08-19 12:09:05 -07006948 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Andy Hung57446612015-04-19 23:56:46 -07006949 (void)posix_memalign(&mRsmpInBuffer, 32, (mRsmpInFramesP2 + mFrameCount - 1) * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006950
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006951 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
6952 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08006953}
6954
Glenn Kasten5f972c02014-01-13 09:59:31 -08006955uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08006956{
6957 Mutex::Autolock _l(mLock);
6958 if (initCheck() != NO_ERROR) {
6959 return 0;
6960 }
6961
6962 return mInput->stream->get_input_frames_lost(mInput->stream);
6963}
6964
6965uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
6966{
6967 Mutex::Autolock _l(mLock);
6968 uint32_t result = 0;
6969 if (getEffectChain_l(sessionId) != 0) {
6970 result = EFFECT_SESSION;
6971 }
6972
6973 for (size_t i = 0; i < mTracks.size(); ++i) {
6974 if (sessionId == mTracks[i]->sessionId()) {
6975 result |= TRACK_SESSION;
6976 break;
6977 }
6978 }
6979
6980 return result;
6981}
6982
6983KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
6984{
6985 KeyedVector<int, bool> ids;
6986 Mutex::Autolock _l(mLock);
6987 for (size_t j = 0; j < mTracks.size(); ++j) {
6988 sp<RecordThread::RecordTrack> track = mTracks[j];
6989 int sessionId = track->sessionId();
6990 if (ids.indexOfKey(sessionId) < 0) {
6991 ids.add(sessionId, true);
6992 }
6993 }
6994 return ids;
6995}
6996
6997AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
6998{
6999 Mutex::Autolock _l(mLock);
7000 AudioStreamIn *input = mInput;
7001 mInput = NULL;
7002 return input;
7003}
7004
7005// this method must always be called either with ThreadBase mLock held or inside the thread loop
7006audio_stream_t* AudioFlinger::RecordThread::stream() const
7007{
7008 if (mInput == NULL) {
7009 return NULL;
7010 }
7011 return &mInput->stream->common;
7012}
7013
7014status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7015{
7016 // only one chain per input thread
7017 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07007018 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08007019 return INVALID_OPERATION;
7020 }
7021 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07007022 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08007023 chain->setInBuffer(NULL);
7024 chain->setOutBuffer(NULL);
7025
7026 checkSuspendOnAddEffectChain_l(chain);
7027
Eric Laurent1b928682014-10-02 19:41:47 -07007028 // make sure enabled pre processing effects state is communicated to the HAL as we
7029 // just moved them to a new input stream.
7030 chain->syncHalEffectsState();
7031
Eric Laurent81784c32012-11-19 14:55:58 -08007032 mEffectChains.add(chain);
7033
7034 return NO_ERROR;
7035}
7036
7037size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7038{
7039 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
7040 ALOGW_IF(mEffectChains.size() != 1,
7041 "removeEffectChain_l() %p invalid chain size %d on thread %p",
7042 chain.get(), mEffectChains.size(), this);
7043 if (mEffectChains.size() == 1) {
7044 mEffectChains.removeAt(0);
7045 }
7046 return 0;
7047}
7048
Eric Laurent1c333e22014-05-20 10:48:17 -07007049status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
7050 audio_patch_handle_t *handle)
7051{
7052 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007053
7054 // store new device and send to effects
7055 mInDevice = patch->sources[0].ext.device.type;
Eric Laurent296fb132015-05-01 11:38:42 -07007056 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07007057 for (size_t i = 0; i < mEffectChains.size(); i++) {
7058 mEffectChains[i]->setDevice_l(mInDevice);
7059 }
7060
7061 // disable AEC and NS if the device is a BT SCO headset supporting those
7062 // pre processings
7063 if (mTracks.size() > 0) {
7064 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7065 mAudioFlinger->btNrecIsOff();
7066 for (size_t i = 0; i < mTracks.size(); i++) {
7067 sp<RecordTrack> track = mTracks[i];
7068 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7069 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
7070 }
7071 }
7072
7073 // store new source and send to effects
7074 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7075 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07007076 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07007077 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07007078 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007079 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007080
Eric Laurent054d9d32015-04-24 08:48:48 -07007081 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007082 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
7083 status = hwDevice->create_audio_patch(hwDevice,
7084 patch->num_sources,
7085 patch->sources,
7086 patch->num_sinks,
7087 patch->sinks,
7088 handle);
7089 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007090 char *address;
7091 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
7092 address = audio_device_address_to_parameter(
7093 patch->sources[0].ext.device.type,
7094 patch->sources[0].ext.device.address);
7095 } else {
7096 address = (char *)calloc(1, 1);
7097 }
7098 AudioParameter param = AudioParameter(String8(address));
7099 free(address);
7100 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING),
7101 (int)patch->sources[0].ext.device.type);
7102 param.addInt(String8(AUDIO_PARAMETER_STREAM_INPUT_SOURCE),
7103 (int)patch->sinks[0].ext.mix.usecase.source);
7104 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7105 param.toString().string());
7106 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07007107 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007108
Eric Laurente8726fe2015-06-26 09:39:24 -07007109 if (mInDevice != mPrevInDevice) {
7110 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
7111 mPrevInDevice = mInDevice;
7112 }
Eric Laurent296fb132015-05-01 11:38:42 -07007113
Eric Laurent1c333e22014-05-20 10:48:17 -07007114 return status;
7115}
7116
7117status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
7118{
7119 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007120
7121 mInDevice = AUDIO_DEVICE_NONE;
7122
Eric Laurent1c333e22014-05-20 10:48:17 -07007123 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
7124 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
7125 status = hwDevice->release_audio_patch(hwDevice, handle);
7126 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007127 AudioParameter param;
7128 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
7129 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7130 param.toString().string());
Eric Laurent1c333e22014-05-20 10:48:17 -07007131 }
7132 return status;
7133}
7134
Eric Laurent83b88082014-06-20 18:31:16 -07007135void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
7136{
7137 Mutex::Autolock _l(mLock);
7138 mTracks.add(record);
7139}
7140
7141void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
7142{
7143 Mutex::Autolock _l(mLock);
7144 destroyTrack_l(record);
7145}
7146
7147void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
7148{
7149 ThreadBase::getAudioPortConfig(config);
7150 config->role = AUDIO_PORT_ROLE_SINK;
7151 config->ext.mix.hw_module = mInput->audioHwDev->handle();
7152 config->ext.mix.usecase.source = mAudioSource;
7153}
Eric Laurent1c333e22014-05-20 10:48:17 -07007154
Glenn Kasten63238ef2015-03-02 15:50:29 -08007155} // namespace android