blob: f1303d4eb1217759ac27e3ecc2cccedb254027e4 [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"
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -070063#include "mediautils/SchedulingPolicyService.h"
Eric Laurent81784c32012-11-19 14:55:58 -080064
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",
447 AUDIO_INPUT_FLAG_NONE, "NONE", // must be last
448 };
449 String8 result;
450 audio_input_flags_t allFlags = AUDIO_INPUT_FLAG_NONE;
451 const mapping *entry;
452 for (entry = mappings; entry->mFlag != AUDIO_INPUT_FLAG_NONE; entry++) {
453 allFlags = (audio_input_flags_t) (allFlags | entry->mFlag);
454 if (flags & entry->mFlag) {
455 if (!result.isEmpty()) {
456 result.append("|");
457 }
458 result.append(entry->mString);
459 }
460 }
461 if (flags & ~allFlags) {
462 if (!result.isEmpty()) {
463 result.append("|");
464 }
465 result.appendFormat("0x%X", flags & ~allFlags);
466 }
467 if (result.isEmpty()) {
468 result.append(entry->mString);
469 }
470 return result;
471}
472
473String8 outputFlagsToString(audio_output_flags_t flags)
Glenn Kasten97b7b752014-09-28 13:04:24 -0700474{
475 static const struct mapping {
476 audio_output_flags_t mFlag;
477 const char * mString;
478 } mappings[] = {
479 AUDIO_OUTPUT_FLAG_DIRECT, "DIRECT",
480 AUDIO_OUTPUT_FLAG_PRIMARY, "PRIMARY",
481 AUDIO_OUTPUT_FLAG_FAST, "FAST",
482 AUDIO_OUTPUT_FLAG_DEEP_BUFFER, "DEEP_BUFFER",
Glenn Kastendfb0e112015-02-18 14:33:39 -0800483 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD, "COMPRESS_OFFLOAD",
Glenn Kasten97b7b752014-09-28 13:04:24 -0700484 AUDIO_OUTPUT_FLAG_NON_BLOCKING, "NON_BLOCKING",
485 AUDIO_OUTPUT_FLAG_HW_AV_SYNC, "HW_AV_SYNC",
486 AUDIO_OUTPUT_FLAG_NONE, "NONE", // must be last
487 };
488 String8 result;
489 audio_output_flags_t allFlags = AUDIO_OUTPUT_FLAG_NONE;
490 const mapping *entry;
491 for (entry = mappings; entry->mFlag != AUDIO_OUTPUT_FLAG_NONE; entry++) {
492 allFlags = (audio_output_flags_t) (allFlags | entry->mFlag);
493 if (flags & entry->mFlag) {
494 if (!result.isEmpty()) {
495 result.append("|");
496 }
497 result.append(entry->mString);
498 }
499 }
500 if (flags & ~allFlags) {
501 if (!result.isEmpty()) {
502 result.append("|");
503 }
504 result.appendFormat("0x%X", flags & ~allFlags);
505 }
506 if (result.isEmpty()) {
507 result.append(entry->mString);
508 }
509 return result;
510}
511
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800512const char *sourceToString(audio_source_t source)
513{
514 switch (source) {
515 case AUDIO_SOURCE_DEFAULT: return "default";
516 case AUDIO_SOURCE_MIC: return "mic";
517 case AUDIO_SOURCE_VOICE_UPLINK: return "voice uplink";
518 case AUDIO_SOURCE_VOICE_DOWNLINK: return "voice downlink";
519 case AUDIO_SOURCE_VOICE_CALL: return "voice call";
520 case AUDIO_SOURCE_CAMCORDER: return "camcorder";
521 case AUDIO_SOURCE_VOICE_RECOGNITION: return "voice recognition";
522 case AUDIO_SOURCE_VOICE_COMMUNICATION: return "voice communication";
523 case AUDIO_SOURCE_REMOTE_SUBMIX: return "remote submix";
524 case AUDIO_SOURCE_FM_TUNER: return "FM tuner";
525 case AUDIO_SOURCE_HOTWORD: return "hotword";
526 default: return "unknown";
527 }
528}
529
Eric Laurent81784c32012-11-19 14:55:58 -0800530AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -0700531 audio_devices_t outDevice, audio_devices_t inDevice, type_t type, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -0800532 : Thread(false /*canCallJava*/),
533 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700534 mAudioFlinger(audioFlinger),
Glenn Kasten70949c42013-08-06 07:40:12 -0700535 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800536 // are set by PlaybackThread::readOutputParameters_l() or
537 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700538 //FIXME: mStandby should be true here. Is this some kind of hack?
Eric Laurent81784c32012-11-19 14:55:58 -0800539 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700540 mPrevOutDevice(AUDIO_DEVICE_NONE), mPrevInDevice(AUDIO_DEVICE_NONE),
541 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Eric Laurent81784c32012-11-19 14:55:58 -0800542 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700543 mDeathRecipient(new PMDeathRecipient(this)),
544 mSystemReady(systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -0800545{
Eric Laurent296fb132015-05-01 11:38:42 -0700546 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800547}
548
549AudioFlinger::ThreadBase::~ThreadBase()
550{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700551 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700552 mConfigEvents.clear();
553
Eric Laurent81784c32012-11-19 14:55:58 -0800554 // do not lock the mutex in destructor
555 releaseWakeLock_l();
556 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800557 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800558 binder->unlinkToDeath(mDeathRecipient);
559 }
560}
561
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700562status_t AudioFlinger::ThreadBase::readyToRun()
563{
564 status_t status = initCheck();
565 if (status == NO_ERROR) {
566 ALOGI("AudioFlinger's thread %p ready to run", this);
567 } else {
568 ALOGE("No working audio driver found.");
569 }
570 return status;
571}
572
Eric Laurent81784c32012-11-19 14:55:58 -0800573void AudioFlinger::ThreadBase::exit()
574{
575 ALOGV("ThreadBase::exit");
576 // do any cleanup required for exit to succeed
577 preExit();
578 {
579 // This lock prevents the following race in thread (uniprocessor for illustration):
580 // if (!exitPending()) {
581 // // context switch from here to exit()
582 // // exit() calls requestExit(), what exitPending() observes
583 // // exit() calls signal(), which is dropped since no waiters
584 // // context switch back from exit() to here
585 // mWaitWorkCV.wait(...);
586 // // now thread is hung
587 // }
588 AutoMutex lock(mLock);
589 requestExit();
590 mWaitWorkCV.broadcast();
591 }
592 // When Thread::requestExitAndWait is made virtual and this method is renamed to
593 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
594 requestExitAndWait();
595}
596
597status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
598{
599 status_t status;
600
601 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
602 Mutex::Autolock _l(mLock);
603
Eric Laurent10351942014-05-08 18:49:52 -0700604 return sendSetParameterConfigEvent_l(keyValuePairs);
605}
606
607// sendConfigEvent_l() must be called with ThreadBase::mLock held
608// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
609status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
610{
611 status_t status = NO_ERROR;
612
Eric Laurent72e3f392015-05-20 14:43:50 -0700613 if (event->mRequiresSystemReady && !mSystemReady) {
614 event->mWaitStatus = false;
615 mPendingConfigEvents.add(event);
616 return status;
617 }
Eric Laurent10351942014-05-08 18:49:52 -0700618 mConfigEvents.add(event);
619 ALOGV("sendConfigEvent_l() num events %d event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800620 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700621 mLock.unlock();
622 {
623 Mutex::Autolock _l(event->mLock);
624 while (event->mWaitStatus) {
625 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
626 event->mStatus = TIMED_OUT;
627 event->mWaitStatus = false;
628 }
629 }
630 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800631 }
Eric Laurent10351942014-05-08 18:49:52 -0700632 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800633 return status;
634}
635
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700636void AudioFlinger::ThreadBase::sendIoConfigEvent(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800637{
638 Mutex::Autolock _l(mLock);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700639 sendIoConfigEvent_l(event, pid);
Eric Laurent81784c32012-11-19 14:55:58 -0800640}
641
642// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700643void AudioFlinger::ThreadBase::sendIoConfigEvent_l(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800644{
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700645 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid);
Eric Laurent10351942014-05-08 18:49:52 -0700646 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800647}
648
Eric Laurent72e3f392015-05-20 14:43:50 -0700649void AudioFlinger::ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio)
650{
651 Mutex::Autolock _l(mLock);
652 sendPrioConfigEvent_l(pid, tid, prio);
653}
654
Eric Laurent81784c32012-11-19 14:55:58 -0800655// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
656void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
657{
Eric Laurent10351942014-05-08 18:49:52 -0700658 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio);
659 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800660}
661
Eric Laurent10351942014-05-08 18:49:52 -0700662// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
663status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800664{
Eric Laurent10351942014-05-08 18:49:52 -0700665 sp<ConfigEvent> configEvent = (ConfigEvent *)new SetParameterConfigEvent(keyValuePair);
666 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700667}
668
Eric Laurent1c333e22014-05-20 10:48:17 -0700669status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
670 const struct audio_patch *patch,
671 audio_patch_handle_t *handle)
672{
673 Mutex::Autolock _l(mLock);
674 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
675 status_t status = sendConfigEvent_l(configEvent);
676 if (status == NO_ERROR) {
677 CreateAudioPatchConfigEventData *data =
678 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
679 *handle = data->mHandle;
680 }
681 return status;
682}
683
684status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
685 const audio_patch_handle_t handle)
686{
687 Mutex::Autolock _l(mLock);
688 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
689 return sendConfigEvent_l(configEvent);
690}
691
692
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700693// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700694void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700695{
Eric Laurent10351942014-05-08 18:49:52 -0700696 bool configChanged = false;
697
Eric Laurent81784c32012-11-19 14:55:58 -0800698 while (!mConfigEvents.isEmpty()) {
Eric Laurent10351942014-05-08 18:49:52 -0700699 ALOGV("processConfigEvents_l() remaining events %d", mConfigEvents.size());
700 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800701 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700702 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700703 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700704 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
705 // FIXME Need to understand why this has to be done asynchronously
706 int err = requestPriority(data->mPid, data->mTid, data->mPrio,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700707 true /*asynchronous*/);
708 if (err != 0) {
709 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700710 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700711 }
712 } break;
713 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700714 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700715 ioConfigChanged(data->mEvent, data->mPid);
Eric Laurent10351942014-05-08 18:49:52 -0700716 } break;
717 case CFG_EVENT_SET_PARAMETER: {
718 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
719 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
720 configChanged = true;
Glenn Kastend5418eb2013-08-14 13:11:06 -0700721 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700722 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700723 case CFG_EVENT_CREATE_AUDIO_PATCH: {
724 CreateAudioPatchConfigEventData *data =
725 (CreateAudioPatchConfigEventData *)event->mData.get();
726 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
727 } break;
728 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
729 ReleaseAudioPatchConfigEventData *data =
730 (ReleaseAudioPatchConfigEventData *)event->mData.get();
731 event->mStatus = releaseAudioPatch_l(data->mHandle);
732 } break;
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700733 default:
Eric Laurent10351942014-05-08 18:49:52 -0700734 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700735 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800736 }
Eric Laurent10351942014-05-08 18:49:52 -0700737 {
738 Mutex::Autolock _l(event->mLock);
739 if (event->mWaitStatus) {
740 event->mWaitStatus = false;
741 event->mCond.signal();
742 }
743 }
744 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
745 }
746
747 if (configChanged) {
748 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800749 }
Eric Laurent81784c32012-11-19 14:55:58 -0800750}
751
Marco Nelissenb2208842014-02-07 14:00:50 -0800752String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
753 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700754 const audio_channel_representation_t representation =
755 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700756
757 switch (representation) {
758 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
759 if (output) {
760 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
761 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
762 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
763 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
764 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
765 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
766 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
767 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
768 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
769 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
770 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
771 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
772 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
773 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
774 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
775 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
776 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
777 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
778 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
779 } else {
780 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
781 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
782 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
783 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
784 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
785 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
786 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
787 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
788 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
789 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
790 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
791 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
792 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
793 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
794 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
795 }
796 const int len = s.length();
797 if (len > 2) {
798 char *str = s.lockBuffer(len); // needed?
799 s.unlockBuffer(len - 2); // remove trailing ", "
800 }
801 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800802 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700803 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
804 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
805 return s;
806 default:
807 s.appendFormat("unknown mask, representation:%d bits:%#x",
808 representation, audio_channel_mask_get_bits(mask));
809 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800810 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800811}
812
Glenn Kasten0f11b512014-01-31 16:18:54 -0800813void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800814{
815 const size_t SIZE = 256;
816 char buffer[SIZE];
817 String8 result;
818
819 bool locked = AudioFlinger::dumpTryLock(mLock);
820 if (!locked) {
Glenn Kasten97b7b752014-09-28 13:04:24 -0700821 dprintf(fd, "thread %p may be deadlocked\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -0800822 }
823
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800824 dprintf(fd, " Thread name: %s\n", mThreadName);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700825 dprintf(fd, " I/O handle: %d\n", mId);
826 dprintf(fd, " TID: %d\n", getTid());
827 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700828 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700829 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700830 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat));
Elliott Hughes87cebad2014-05-22 10:14:43 -0700831 dprintf(fd, " HAL buffer size: %u bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700832 dprintf(fd, " Channel count: %u\n", mChannelCount);
833 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800834 channelMaskToString(mChannelMask, mType != RECORD).string());
Glenn Kasten97b7b752014-09-28 13:04:24 -0700835 dprintf(fd, " Format: 0x%x (%s)\n", mFormat, formatToString(mFormat));
836 dprintf(fd, " Frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700837 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800838 size_t numConfig = mConfigEvents.size();
839 if (numConfig) {
840 for (size_t i = 0; i < numConfig; i++) {
841 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700842 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800843 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700844 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800845 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700846 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800847 }
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800848 dprintf(fd, " Output device: %#x (%s)\n", mOutDevice, devicesToString(mOutDevice).string());
849 dprintf(fd, " Input device: %#x (%s)\n", mInDevice, devicesToString(mInDevice).string());
850 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, sourceToString(mAudioSource));
Eric Laurent81784c32012-11-19 14:55:58 -0800851
852 if (locked) {
853 mLock.unlock();
854 }
855}
856
857void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
858{
859 const size_t SIZE = 256;
860 char buffer[SIZE];
861 String8 result;
862
Marco Nelissenb2208842014-02-07 14:00:50 -0800863 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000864 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800865 write(fd, buffer, strlen(buffer));
866
Marco Nelissenb2208842014-02-07 14:00:50 -0800867 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800868 sp<EffectChain> chain = mEffectChains[i];
869 if (chain != 0) {
870 chain->dump(fd, args);
871 }
872 }
873}
874
Marco Nelissene14a5d62013-10-03 08:51:24 -0700875void AudioFlinger::ThreadBase::acquireWakeLock(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800876{
877 Mutex::Autolock _l(mLock);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700878 acquireWakeLock_l(uid);
Eric Laurent81784c32012-11-19 14:55:58 -0800879}
880
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100881String16 AudioFlinger::ThreadBase::getWakeLockTag()
882{
883 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -0800884 case MIXER:
885 return String16("AudioMix");
886 case DIRECT:
887 return String16("AudioDirectOut");
888 case DUPLICATING:
889 return String16("AudioDup");
890 case RECORD:
891 return String16("AudioIn");
892 case OFFLOAD:
893 return String16("AudioOffload");
894 default:
895 ALOG_ASSERT(false);
896 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100897 }
898}
899
Marco Nelissene14a5d62013-10-03 08:51:24 -0700900void AudioFlinger::ThreadBase::acquireWakeLock_l(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800901{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800902 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800903 if (mPowerManager != 0) {
904 sp<IBinder> binder = new BBinder();
Marco Nelissene14a5d62013-10-03 08:51:24 -0700905 status_t status;
906 if (uid >= 0) {
Eric Laurent547789d2013-10-04 11:46:55 -0700907 status = mPowerManager->acquireWakeLockWithUid(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700908 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100909 getWakeLockTag(),
Marco Nelissene14a5d62013-10-03 08:51:24 -0700910 String16("media"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700911 uid,
912 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700913 } else {
Eric Laurent547789d2013-10-04 11:46:55 -0700914 status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700915 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100916 getWakeLockTag(),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700917 String16("media"),
918 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700919 }
Eric Laurent81784c32012-11-19 14:55:58 -0800920 if (status == NO_ERROR) {
921 mWakeLockToken = binder;
922 }
Glenn Kastend7dca052015-03-05 16:05:54 -0800923 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Eric Laurent81784c32012-11-19 14:55:58 -0800924 }
925}
926
927void AudioFlinger::ThreadBase::releaseWakeLock()
928{
929 Mutex::Autolock _l(mLock);
930 releaseWakeLock_l();
931}
932
933void AudioFlinger::ThreadBase::releaseWakeLock_l()
934{
935 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800936 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -0800937 if (mPowerManager != 0) {
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700938 mPowerManager->releaseWakeLock(mWakeLockToken, 0,
939 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800940 }
941 mWakeLockToken.clear();
942 }
943}
944
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800945void AudioFlinger::ThreadBase::updateWakeLockUids(const SortedVector<int> &uids) {
946 Mutex::Autolock _l(mLock);
947 updateWakeLockUids_l(uids);
948}
949
950void AudioFlinger::ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -0700951 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800952 // use checkService() to avoid blocking if power service is not up yet
953 sp<IBinder> binder =
954 defaultServiceManager()->checkService(String16("power"));
955 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800956 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800957 } else {
958 mPowerManager = interface_cast<IPowerManager>(binder);
959 binder->linkToDeath(mDeathRecipient);
960 }
961 }
962}
963
964void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<int> &uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800965 getPowerManager_l();
966 if (mWakeLockToken == NULL) {
967 ALOGE("no wake lock to update!");
968 return;
969 }
970 if (mPowerManager != 0) {
971 sp<IBinder> binder = new BBinder();
972 status_t status;
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700973 status = mPowerManager->updateWakeLockUids(mWakeLockToken, uids.size(), uids.array(),
974 true /* FIXME force oneway contrary to .aidl */);
Glenn Kastend7dca052015-03-05 16:05:54 -0800975 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800976 }
977}
978
Eric Laurent81784c32012-11-19 14:55:58 -0800979void AudioFlinger::ThreadBase::clearPowerManager()
980{
981 Mutex::Autolock _l(mLock);
982 releaseWakeLock_l();
983 mPowerManager.clear();
984}
985
Glenn Kasten0f11b512014-01-31 16:18:54 -0800986void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800987{
988 sp<ThreadBase> thread = mThread.promote();
989 if (thread != 0) {
990 thread->clearPowerManager();
991 }
992 ALOGW("power manager service died !!!");
993}
994
995void AudioFlinger::ThreadBase::setEffectSuspended(
996 const effect_uuid_t *type, bool suspend, int sessionId)
997{
998 Mutex::Autolock _l(mLock);
999 setEffectSuspended_l(type, suspend, sessionId);
1000}
1001
1002void AudioFlinger::ThreadBase::setEffectSuspended_l(
1003 const effect_uuid_t *type, bool suspend, int sessionId)
1004{
1005 sp<EffectChain> chain = getEffectChain_l(sessionId);
1006 if (chain != 0) {
1007 if (type != NULL) {
1008 chain->setEffectSuspended_l(type, suspend);
1009 } else {
1010 chain->setEffectSuspendedAll_l(suspend);
1011 }
1012 }
1013
1014 updateSuspendedSessions_l(type, suspend, sessionId);
1015}
1016
1017void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1018{
1019 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1020 if (index < 0) {
1021 return;
1022 }
1023
1024 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1025 mSuspendedSessions.valueAt(index);
1026
1027 for (size_t i = 0; i < sessionEffects.size(); i++) {
1028 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
1029 for (int j = 0; j < desc->mRefCount; j++) {
1030 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1031 chain->setEffectSuspendedAll_l(true);
1032 } else {
1033 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1034 desc->mType.timeLow);
1035 chain->setEffectSuspended_l(&desc->mType, true);
1036 }
1037 }
1038 }
1039}
1040
1041void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1042 bool suspend,
1043 int sessionId)
1044{
1045 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1046
1047 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1048
1049 if (suspend) {
1050 if (index >= 0) {
1051 sessionEffects = mSuspendedSessions.valueAt(index);
1052 } else {
1053 mSuspendedSessions.add(sessionId, sessionEffects);
1054 }
1055 } else {
1056 if (index < 0) {
1057 return;
1058 }
1059 sessionEffects = mSuspendedSessions.valueAt(index);
1060 }
1061
1062
1063 int key = EffectChain::kKeyForSuspendAll;
1064 if (type != NULL) {
1065 key = type->timeLow;
1066 }
1067 index = sessionEffects.indexOfKey(key);
1068
1069 sp<SuspendedSessionDesc> desc;
1070 if (suspend) {
1071 if (index >= 0) {
1072 desc = sessionEffects.valueAt(index);
1073 } else {
1074 desc = new SuspendedSessionDesc();
1075 if (type != NULL) {
1076 desc->mType = *type;
1077 }
1078 sessionEffects.add(key, desc);
1079 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1080 }
1081 desc->mRefCount++;
1082 } else {
1083 if (index < 0) {
1084 return;
1085 }
1086 desc = sessionEffects.valueAt(index);
1087 if (--desc->mRefCount == 0) {
1088 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1089 sessionEffects.removeItemsAt(index);
1090 if (sessionEffects.isEmpty()) {
1091 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1092 sessionId);
1093 mSuspendedSessions.removeItem(sessionId);
1094 }
1095 }
1096 }
1097 if (!sessionEffects.isEmpty()) {
1098 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1099 }
1100}
1101
1102void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1103 bool enabled,
1104 int sessionId)
1105{
1106 Mutex::Autolock _l(mLock);
1107 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1108}
1109
1110void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1111 bool enabled,
1112 int sessionId)
1113{
1114 if (mType != RECORD) {
1115 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1116 // another session. This gives the priority to well behaved effect control panels
1117 // and applications not using global effects.
1118 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1119 // global effects
1120 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
1121 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1122 }
1123 }
1124
1125 sp<EffectChain> chain = getEffectChain_l(sessionId);
1126 if (chain != 0) {
1127 chain->checkSuspendOnEffectEnabled(effect, enabled);
1128 }
1129}
1130
1131// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1132sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1133 const sp<AudioFlinger::Client>& client,
1134 const sp<IEffectClient>& effectClient,
1135 int32_t priority,
1136 int sessionId,
1137 effect_descriptor_t *desc,
1138 int *enabled,
Eric Laurentbc7f3472016-12-01 15:28:29 -08001139 status_t *status,
1140 bool pinned)
Eric Laurent81784c32012-11-19 14:55:58 -08001141{
1142 sp<EffectModule> effect;
1143 sp<EffectHandle> handle;
1144 status_t lStatus;
1145 sp<EffectChain> chain;
1146 bool chainCreated = false;
1147 bool effectCreated = false;
1148 bool effectRegistered = false;
1149
1150 lStatus = initCheck();
1151 if (lStatus != NO_ERROR) {
1152 ALOGW("createEffect_l() Audio driver not initialized.");
1153 goto Exit;
1154 }
1155
Andy Hung98ef9782014-03-04 14:46:50 -08001156 // Reject any effect on Direct output threads for now, since the format of
1157 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1158 if (mType == DIRECT) {
1159 ALOGW("createEffect_l() Cannot add effect %s on Direct output type thread %s",
Glenn Kastend7dca052015-03-05 16:05:54 -08001160 desc->name, mThreadName);
Andy Hung98ef9782014-03-04 14:46:50 -08001161 lStatus = BAD_VALUE;
1162 goto Exit;
1163 }
1164
Andy Hung389cfdb2014-08-07 17:49:53 -07001165 // Reject any effect on mixer or duplicating multichannel sinks.
Andy Hung9a592762014-07-21 21:56:01 -07001166 // TODO: fix both format and multichannel issues with effects.
Andy Hung389cfdb2014-08-07 17:49:53 -07001167 if ((mType == MIXER || mType == DUPLICATING) && mChannelCount != FCC_2) {
1168 ALOGW("createEffect_l() Cannot add effect %s for multichannel(%d) %s threads",
1169 desc->name, mChannelCount, mType == MIXER ? "MIXER" : "DUPLICATING");
Andy Hung9a592762014-07-21 21:56:01 -07001170 lStatus = BAD_VALUE;
1171 goto Exit;
1172 }
1173
Eric Laurent5baf2af2013-09-12 17:37:00 -07001174 // Allow global effects only on offloaded and mixer threads
1175 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1176 switch (mType) {
1177 case MIXER:
1178 case OFFLOAD:
1179 break;
1180 case DIRECT:
1181 case DUPLICATING:
1182 case RECORD:
1183 default:
Glenn Kastend7dca052015-03-05 16:05:54 -08001184 ALOGW("createEffect_l() Cannot add global effect %s on thread %s",
1185 desc->name, mThreadName);
Eric Laurent5baf2af2013-09-12 17:37:00 -07001186 lStatus = BAD_VALUE;
1187 goto Exit;
1188 }
Eric Laurent81784c32012-11-19 14:55:58 -08001189 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07001190
Eric Laurent81784c32012-11-19 14:55:58 -08001191 // Only Pre processor effects are allowed on input threads and only on input threads
1192 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
1193 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
1194 desc->name, desc->flags, mType);
1195 lStatus = BAD_VALUE;
1196 goto Exit;
1197 }
1198
1199 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1200
1201 { // scope for mLock
1202 Mutex::Autolock _l(mLock);
1203
1204 // check for existing effect chain with the requested audio session
1205 chain = getEffectChain_l(sessionId);
1206 if (chain == 0) {
1207 // create a new chain for this session
1208 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1209 chain = new EffectChain(this, sessionId);
1210 addEffectChain_l(chain);
1211 chain->setStrategy(getStrategyForSession_l(sessionId));
1212 chainCreated = true;
1213 } else {
1214 effect = chain->getEffectFromDesc_l(desc);
1215 }
1216
1217 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1218
1219 if (effect == 0) {
1220 int id = mAudioFlinger->nextUniqueId();
1221 // Check CPU and memory usage
1222 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
1223 if (lStatus != NO_ERROR) {
1224 goto Exit;
1225 }
1226 effectRegistered = true;
1227 // create a new effect module if none present in the chain
Eric Laurentbc7f3472016-12-01 15:28:29 -08001228 lStatus = chain->createEffect_l(effect, this, desc, id, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001229 if (lStatus != NO_ERROR) {
1230 goto Exit;
1231 }
1232 effectCreated = true;
1233
1234 effect->setDevice(mOutDevice);
1235 effect->setDevice(mInDevice);
1236 effect->setMode(mAudioFlinger->getMode());
1237 effect->setAudioSource(mAudioSource);
1238 }
1239 // create effect handle and connect it to effect module
1240 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001241 lStatus = handle->initCheck();
1242 if (lStatus == OK) {
1243 lStatus = effect->addHandle(handle.get());
1244 }
Eric Laurent81784c32012-11-19 14:55:58 -08001245 if (enabled != NULL) {
1246 *enabled = (int)effect->isEnabled();
1247 }
1248 }
1249
1250Exit:
1251 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1252 Mutex::Autolock _l(mLock);
1253 if (effectCreated) {
1254 chain->removeEffect_l(effect);
1255 }
1256 if (effectRegistered) {
1257 AudioSystem::unregisterEffect(effect->id());
1258 }
1259 if (chainCreated) {
1260 removeEffectChain_l(chain);
1261 }
1262 handle.clear();
1263 }
1264
Glenn Kasten9156ef32013-08-06 15:39:08 -07001265 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001266 return handle;
1267}
1268
Eric Laurentbc7f3472016-12-01 15:28:29 -08001269void AudioFlinger::ThreadBase::disconnectEffectHandle(EffectHandle *handle,
1270 bool unpinIfLast)
1271{
1272 bool remove = false;
1273 sp<EffectModule> effect;
1274 {
1275 Mutex::Autolock _l(mLock);
1276
1277 effect = handle->effect().promote();
1278 if (effect == 0) {
1279 return;
1280 }
1281 // restore suspended effects if the disconnected handle was enabled and the last one.
1282 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1283 if (remove) {
1284 removeEffect_l(effect, true);
1285 }
1286 }
1287 if (remove) {
1288 mAudioFlinger->updateOrphanEffectChains(effect);
1289 AudioSystem::unregisterEffect(effect->id());
1290 if (handle->enabled()) {
1291 checkSuspendOnEffectEnabled(effect, false, effect->sessionId());
1292 }
1293 }
1294}
1295
Eric Laurent81784c32012-11-19 14:55:58 -08001296sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
1297{
1298 Mutex::Autolock _l(mLock);
1299 return getEffect_l(sessionId, effectId);
1300}
1301
1302sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
1303{
1304 sp<EffectChain> chain = getEffectChain_l(sessionId);
1305 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1306}
1307
1308// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1309// PlaybackThread::mLock held
1310status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1311{
1312 // check for existing effect chain with the requested audio session
1313 int sessionId = effect->sessionId();
1314 sp<EffectChain> chain = getEffectChain_l(sessionId);
1315 bool chainCreated = false;
1316
Eric Laurent5baf2af2013-09-12 17:37:00 -07001317 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
1318 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
1319 this, effect->desc().name, effect->desc().flags);
1320
Eric Laurent81784c32012-11-19 14:55:58 -08001321 if (chain == 0) {
1322 // create a new chain for this session
1323 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1324 chain = new EffectChain(this, sessionId);
1325 addEffectChain_l(chain);
1326 chain->setStrategy(getStrategyForSession_l(sessionId));
1327 chainCreated = true;
1328 }
1329 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1330
1331 if (chain->getEffectFromId_l(effect->id()) != 0) {
1332 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1333 this, effect->desc().name, chain.get());
1334 return BAD_VALUE;
1335 }
1336
Eric Laurent5baf2af2013-09-12 17:37:00 -07001337 effect->setOffloaded(mType == OFFLOAD, mId);
1338
Eric Laurent81784c32012-11-19 14:55:58 -08001339 status_t status = chain->addEffect_l(effect);
1340 if (status != NO_ERROR) {
1341 if (chainCreated) {
1342 removeEffectChain_l(chain);
1343 }
1344 return status;
1345 }
1346
1347 effect->setDevice(mOutDevice);
1348 effect->setDevice(mInDevice);
1349 effect->setMode(mAudioFlinger->getMode());
1350 effect->setAudioSource(mAudioSource);
1351 return NO_ERROR;
1352}
1353
Eric Laurentbc7f3472016-12-01 15:28:29 -08001354void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001355
Eric Laurentbc7f3472016-12-01 15:28:29 -08001356 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001357 effect_descriptor_t desc = effect->desc();
1358 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1359 detachAuxEffect_l(effect->id());
1360 }
1361
1362 sp<EffectChain> chain = effect->chain().promote();
1363 if (chain != 0) {
1364 // remove effect chain if removing last effect
Eric Laurentbc7f3472016-12-01 15:28:29 -08001365 if (chain->removeEffect_l(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001366 removeEffectChain_l(chain);
1367 }
1368 } else {
1369 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1370 }
1371}
1372
1373void AudioFlinger::ThreadBase::lockEffectChains_l(
1374 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1375{
1376 effectChains = mEffectChains;
1377 for (size_t i = 0; i < mEffectChains.size(); i++) {
1378 mEffectChains[i]->lock();
1379 }
1380}
1381
1382void AudioFlinger::ThreadBase::unlockEffectChains(
1383 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1384{
1385 for (size_t i = 0; i < effectChains.size(); i++) {
1386 effectChains[i]->unlock();
1387 }
1388}
1389
1390sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
1391{
1392 Mutex::Autolock _l(mLock);
1393 return getEffectChain_l(sessionId);
1394}
1395
1396sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const
1397{
1398 size_t size = mEffectChains.size();
1399 for (size_t i = 0; i < size; i++) {
1400 if (mEffectChains[i]->sessionId() == sessionId) {
1401 return mEffectChains[i];
1402 }
1403 }
1404 return 0;
1405}
1406
1407void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1408{
1409 Mutex::Autolock _l(mLock);
1410 size_t size = mEffectChains.size();
1411 for (size_t i = 0; i < size; i++) {
1412 mEffectChains[i]->setMode_l(mode);
1413 }
1414}
1415
Eric Laurent83b88082014-06-20 18:31:16 -07001416void AudioFlinger::ThreadBase::getAudioPortConfig(struct audio_port_config *config)
1417{
1418 config->type = AUDIO_PORT_TYPE_MIX;
1419 config->ext.mix.handle = mId;
1420 config->sample_rate = mSampleRate;
1421 config->format = mFormat;
1422 config->channel_mask = mChannelMask;
1423 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1424 AUDIO_PORT_CONFIG_FORMAT;
1425}
1426
Eric Laurent72e3f392015-05-20 14:43:50 -07001427void AudioFlinger::ThreadBase::systemReady()
1428{
1429 Mutex::Autolock _l(mLock);
1430 if (mSystemReady) {
1431 return;
1432 }
1433 mSystemReady = true;
1434
1435 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1436 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1437 }
1438 mPendingConfigEvents.clear();
1439}
1440
Eric Laurent83b88082014-06-20 18:31:16 -07001441
Eric Laurent81784c32012-11-19 14:55:58 -08001442// ----------------------------------------------------------------------------
1443// Playback
1444// ----------------------------------------------------------------------------
1445
1446AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1447 AudioStreamOut* output,
1448 audio_io_handle_t id,
1449 audio_devices_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07001450 type_t type,
1451 bool systemReady)
1452 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type, systemReady),
Andy Hung2098f272014-02-27 14:00:06 -08001453 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001454 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001455 mMixerBuffer(NULL),
1456 mMixerBufferSize(0),
1457 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1458 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001459 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001460 mEffectBuffer(NULL),
1461 mEffectBufferSize(0),
1462 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1463 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001464 mSuspended(0), mBytesWritten(0),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001465 mActiveTracksGeneration(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001466 // mStreamTypes[] initialized in constructor body
1467 mOutput(output),
1468 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
1469 mMixerStatus(MIXER_IDLE),
1470 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001471 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001472 mBytesRemaining(0),
1473 mCurrentWriteLength(0),
1474 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001475 mWriteAckSequence(0),
1476 mDrainSequence(0),
Eric Laurentede6c3b2013-09-19 14:37:46 -07001477 mSignalPending(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001478 mScreenState(AudioFlinger::mScreenState),
1479 // index 0 is reserved for normal mixer's submix
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001480 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1),
Eric Laurentd1f69b02014-12-15 14:33:13 -08001481 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001482 // mLatchD, mLatchQ,
1483 mLatchDValid(false), mLatchQValid(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001484{
Glenn Kastend7dca052015-03-05 16:05:54 -08001485 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1486 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001487
1488 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1489 // it would be safer to explicitly pass initial masterVolume/masterMute as
1490 // parameter.
1491 //
1492 // If the HAL we are using has support for master volume or master mute,
1493 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1494 // and the mute set to false).
1495 mMasterVolume = audioFlinger->masterVolume_l();
1496 mMasterMute = audioFlinger->masterMute_l();
1497 if (mOutput && mOutput->audioHwDev) {
1498 if (mOutput->audioHwDev->canSetMasterVolume()) {
1499 mMasterVolume = 1.0;
1500 }
1501
1502 if (mOutput->audioHwDev->canSetMasterMute()) {
1503 mMasterMute = false;
1504 }
1505 }
1506
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001507 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001508
Eric Laurent223fd5c2014-11-11 13:43:36 -08001509 // ++ operator does not compile
Glenn Kasten66e46352014-01-16 17:44:23 -08001510 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001511 stream = (audio_stream_type_t) (stream + 1)) {
1512 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1513 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1514 }
Eric Laurent81784c32012-11-19 14:55:58 -08001515}
1516
1517AudioFlinger::PlaybackThread::~PlaybackThread()
1518{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001519 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001520 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001521 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001522 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001523}
1524
1525void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1526{
1527 dumpInternals(fd, args);
1528 dumpTracks(fd, args);
1529 dumpEffectChains(fd, args);
1530}
1531
Glenn Kasten0f11b512014-01-31 16:18:54 -08001532void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001533{
1534 const size_t SIZE = 256;
1535 char buffer[SIZE];
1536 String8 result;
1537
Marco Nelissenb2208842014-02-07 14:00:50 -08001538 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001539 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1540 const stream_type_t *st = &mStreamTypes[i];
1541 if (i > 0) {
1542 result.appendFormat(", ");
1543 }
1544 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1545 if (st->mute) {
1546 result.append("M");
1547 }
1548 }
1549 result.append("\n");
1550 write(fd, result.string(), result.length());
1551 result.clear();
1552
Eric Laurent81784c32012-11-19 14:55:58 -08001553 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1554 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001555 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001556 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001557
1558 size_t numtracks = mTracks.size();
1559 size_t numactive = mActiveTracks.size();
Elliott Hughes87cebad2014-05-22 10:14:43 -07001560 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001561 size_t numactiveseen = 0;
1562 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07001563 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08001564 Track::appendDumpHeader(result);
1565 for (size_t i = 0; i < numtracks; ++i) {
1566 sp<Track> track = mTracks[i];
1567 if (track != 0) {
1568 bool active = mActiveTracks.indexOf(track) >= 0;
1569 if (active) {
1570 numactiveseen++;
1571 }
1572 track->dump(buffer, SIZE, active);
1573 result.append(buffer);
1574 }
1575 }
1576 } else {
1577 result.append("\n");
1578 }
1579 if (numactiveseen != numactive) {
1580 // some tracks in the active list were not in the tracks list
1581 snprintf(buffer, SIZE, " The following tracks are in the active list but"
1582 " not in the track list\n");
1583 result.append(buffer);
1584 Track::appendDumpHeader(result);
1585 for (size_t i = 0; i < numactive; ++i) {
1586 sp<Track> track = mActiveTracks[i].promote();
1587 if (track != 0 && mTracks.indexOf(track) < 0) {
1588 track->dump(buffer, SIZE, true);
1589 result.append(buffer);
1590 }
1591 }
1592 }
1593
1594 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001595}
1596
1597void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1598{
Glenn Kasten97b7b752014-09-28 13:04:24 -07001599 dprintf(fd, "\nOutput thread %p type %d (%s):\n", this, type(), threadTypeToString(type()));
Glenn Kasten44182c22015-03-05 17:12:23 -08001600
1601 dumpBase(fd, args);
1602
Elliott Hughes87cebad2014-05-22 10:14:43 -07001603 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
1604 dprintf(fd, " Last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1605 dprintf(fd, " Total writes: %d\n", mNumWrites);
1606 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1607 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1608 dprintf(fd, " Suspend count: %d\n", mSuspended);
1609 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1610 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1611 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1612 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent113efbb2016-01-08 17:16:42 -08001613 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001614 AudioStreamOut *output = mOutput;
1615 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
1616 String8 flagsAsString = outputFlagsToString(flags);
1617 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n", output, flags, flagsAsString.string());
Eric Laurent81784c32012-11-19 14:55:58 -08001618}
1619
1620// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001621
1622void AudioFlinger::PlaybackThread::onFirstRef()
1623{
Glenn Kastend7dca052015-03-05 16:05:54 -08001624 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001625}
1626
1627// ThreadBase virtuals
1628void AudioFlinger::PlaybackThread::preExit()
1629{
1630 ALOGV(" preExit()");
1631 // FIXME this is using hard-coded strings but in the future, this functionality will be
1632 // converted to use audio HAL extensions required to support tunneling
1633 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1634}
1635
1636// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1637sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1638 const sp<AudioFlinger::Client>& client,
1639 audio_stream_type_t streamType,
1640 uint32_t sampleRate,
1641 audio_format_t format,
1642 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001643 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001644 const sp<IMemory>& sharedBuffer,
1645 int sessionId,
1646 IAudioFlinger::track_flags_t *flags,
1647 pid_t tid,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001648 int uid,
Eric Laurent81784c32012-11-19 14:55:58 -08001649 status_t *status)
1650{
Glenn Kasten74935e42013-12-19 08:56:45 -08001651 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001652 sp<Track> track;
1653 status_t lStatus;
1654
1655 bool isTimed = (*flags & IAudioFlinger::TRACK_TIMED) != 0;
1656
1657 // client expresses a preference for FAST, but we get the final say
1658 if (*flags & IAudioFlinger::TRACK_FAST) {
1659 if (
1660 // not timed
1661 (!isTimed) &&
1662 // either of these use cases:
1663 (
1664 // use case 1: shared buffer with any frame count
1665 (
1666 (sharedBuffer != 0)
1667 ) ||
Glenn Kasten1dfe2f92015-03-09 12:03:14 -07001668 // use case 2: frame count is default or at least as large as HAL
Eric Laurent81784c32012-11-19 14:55:58 -08001669 (
Glenn Kasten1dfe2f92015-03-09 12:03:14 -07001670 // we formerly checked for a callback handler (non-0 tid),
1671 // but that is no longer required for TRANSFER_OBTAIN mode
Eric Laurent81784c32012-11-19 14:55:58 -08001672 ((frameCount == 0) ||
Glenn Kastenb5fed682013-12-03 09:06:43 -08001673 (frameCount >= mFrameCount))
Eric Laurent81784c32012-11-19 14:55:58 -08001674 )
1675 ) &&
1676 // PCM data
1677 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07001678 // TODO: extract as a data library function that checks that a computationally
1679 // expensive downmixer is not required: isFastOutputChannelConversion()
Andy Hung9a592762014-07-21 21:56:01 -07001680 (channelMask == mChannelMask ||
Andy Hung1f439e12015-05-19 12:57:41 -07001681 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
1682 (channelMask == AUDIO_CHANNEL_OUT_MONO
1683 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001684 // hardware sample rate
1685 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001686 // normal mixer has an associated fast mixer
1687 hasFastMixer() &&
1688 // there are sufficient fast track slots available
1689 (mFastTrackAvailMask != 0)
1690 // FIXME test that MixerThread for this fast track has a capable output HAL
1691 // FIXME add a permission test also?
1692 ) {
1693 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1694 if (frameCount == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001695 // read the fast track multiplier property the first time it is needed
1696 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1697 if (ok != 0) {
1698 ALOGE("%s pthread_once failed: %d", __func__, ok);
1699 }
1700 frameCount = mFrameCount * sFastTrackMultiplier;
Eric Laurent81784c32012-11-19 14:55:58 -08001701 }
1702 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
1703 frameCount, mFrameCount);
1704 } else {
1705 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
Andy Hung6146c082014-03-18 11:56:15 -07001706 "mFrameCount=%d format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
1707 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001708 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Andy Hung6146c082014-03-18 11:56:15 -07001709 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001710 audio_is_linear_pcm(format),
1711 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
1712 *flags &= ~IAudioFlinger::TRACK_FAST;
Andy Hung0e48d252015-01-26 11:43:15 -08001713 }
1714 }
1715 // For normal PCM streaming tracks, update minimum frame count.
1716 // For compatibility with AudioTrack calculation, buffer depth is forced
1717 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1718 // This is probably too conservative, but legacy application code may depend on it.
1719 // If you change this calculation, also review the start threshold which is related.
1720 if (!(*flags & IAudioFlinger::TRACK_FAST)
1721 && audio_is_linear_pcm(format) && sharedBuffer == 0) {
Andy Hung8edb8dc2015-03-26 19:13:55 -07001722 // this must match AudioTrack.cpp calculateMinFrameCount().
1723 // TODO: Move to a common library
Eric Laurent81784c32012-11-19 14:55:58 -08001724 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1725 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1726 if (minBufCount < 2) {
1727 minBufCount = 2;
1728 }
Andy Hung8edb8dc2015-03-26 19:13:55 -07001729 // For normal mixing tracks, if speed is > 1.0f (normal), AudioTrack
1730 // or the client should compute and pass in a larger buffer request.
Andy Hung0e48d252015-01-26 11:43:15 -08001731 size_t minFrameCount =
Andy Hung8edb8dc2015-03-26 19:13:55 -07001732 minBufCount * sourceFramesNeededWithTimestretch(
1733 sampleRate, mNormalFrameCount,
1734 mSampleRate, AUDIO_TIMESTRETCH_SPEED_NORMAL /*speed*/);
Andy Hung0e48d252015-01-26 11:43:15 -08001735 if (frameCount < minFrameCount) { // including frameCount == 0
Eric Laurent81784c32012-11-19 14:55:58 -08001736 frameCount = minFrameCount;
1737 }
Eric Laurent81784c32012-11-19 14:55:58 -08001738 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001739 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001740
Glenn Kastenc3df8382014-03-13 15:05:25 -07001741 switch (mType) {
1742
1743 case DIRECT:
Glenn Kasten993fa062014-05-02 11:14:34 -07001744 if (audio_is_linear_pcm(format)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001745 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001746 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1747 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001748 sampleRate, format, channelMask, mOutput, mFormat);
1749 lStatus = BAD_VALUE;
1750 goto Exit;
1751 }
1752 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001753 break;
1754
1755 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001756 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001757 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1758 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001759 sampleRate, format, channelMask, mOutput, mFormat);
1760 lStatus = BAD_VALUE;
1761 goto Exit;
1762 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001763 break;
1764
1765 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07001766 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001767 ALOGE("createTrack_l() Bad parameter: format %#x \""
1768 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001769 format, mOutput, mFormat);
1770 lStatus = BAD_VALUE;
1771 goto Exit;
1772 }
Andy Hungcd044842014-08-07 11:04:34 -07001773 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08001774 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1775 lStatus = BAD_VALUE;
1776 goto Exit;
1777 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001778 break;
1779
Eric Laurent81784c32012-11-19 14:55:58 -08001780 }
1781
1782 lStatus = initCheck();
1783 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07001784 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08001785 goto Exit;
1786 }
1787
1788 { // scope for mLock
1789 Mutex::Autolock _l(mLock);
1790
1791 // all tracks in same audio session must share the same routing strategy otherwise
1792 // conflicts will happen when tracks are moved from one output to another by audio policy
1793 // manager
1794 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1795 for (size_t i = 0; i < mTracks.size(); ++i) {
1796 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07001797 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001798 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1799 if (sessionId == t->sessionId() && strategy != actual) {
1800 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1801 strategy, actual);
1802 lStatus = BAD_VALUE;
1803 goto Exit;
1804 }
1805 }
1806 }
1807
1808 if (!isTimed) {
1809 track = new Track(this, client, streamType, sampleRate, format,
Eric Laurent83b88082014-06-20 18:31:16 -07001810 channelMask, frameCount, NULL, sharedBuffer,
1811 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08001812 } else {
1813 track = TimedTrack::create(this, client, streamType, sampleRate, format,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001814 channelMask, frameCount, sharedBuffer, sessionId, uid);
Eric Laurent81784c32012-11-19 14:55:58 -08001815 }
Glenn Kasten03003332013-08-06 15:40:54 -07001816
1817 // new Track always returns non-NULL,
1818 // but TimedTrack::create() is a factory that could fail by returning NULL
1819 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
1820 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08001821 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001822 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08001823 goto Exit;
1824 }
1825 mTracks.add(track);
1826
1827 sp<EffectChain> chain = getEffectChain_l(sessionId);
1828 if (chain != 0) {
1829 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1830 track->setMainBuffer(chain->inBuffer());
1831 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1832 chain->incTrackCnt();
1833 }
1834
1835 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1836 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1837 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1838 // so ask activity manager to do this on our behalf
1839 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1840 }
1841 }
1842
1843 lStatus = NO_ERROR;
1844
1845Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001846 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001847 return track;
1848}
1849
1850uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1851{
1852 return latency;
1853}
1854
1855uint32_t AudioFlinger::PlaybackThread::latency() const
1856{
1857 Mutex::Autolock _l(mLock);
1858 return latency_l();
1859}
1860uint32_t AudioFlinger::PlaybackThread::latency_l() const
1861{
1862 if (initCheck() == NO_ERROR) {
1863 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
1864 } else {
1865 return 0;
1866 }
1867}
1868
1869void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1870{
1871 Mutex::Autolock _l(mLock);
1872 // Don't apply master volume in SW if our HAL can do it for us.
1873 if (mOutput && mOutput->audioHwDev &&
1874 mOutput->audioHwDev->canSetMasterVolume()) {
1875 mMasterVolume = 1.0;
1876 } else {
1877 mMasterVolume = value;
1878 }
1879}
1880
1881void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1882{
1883 Mutex::Autolock _l(mLock);
1884 // Don't apply master mute in SW if our HAL can do it for us.
1885 if (mOutput && mOutput->audioHwDev &&
1886 mOutput->audioHwDev->canSetMasterMute()) {
1887 mMasterMute = false;
1888 } else {
1889 mMasterMute = muted;
1890 }
1891}
1892
1893void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
1894{
1895 Mutex::Autolock _l(mLock);
1896 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001897 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001898}
1899
1900void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
1901{
1902 Mutex::Autolock _l(mLock);
1903 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001904 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001905}
1906
1907float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
1908{
1909 Mutex::Autolock _l(mLock);
1910 return mStreamTypes[stream].volume;
1911}
1912
1913// addTrack_l() must be called with ThreadBase::mLock held
1914status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1915{
1916 status_t status = ALREADY_EXISTS;
1917
1918 // set retry count for buffer fill
1919 track->mRetryCount = kMaxTrackStartupRetries;
1920 if (mActiveTracks.indexOf(track) < 0) {
1921 // the track is newly added, make sure it fills up all its
1922 // buffers before playing. This is to ensure the client will
1923 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07001924 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001925 TrackBase::track_state state = track->mState;
1926 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08001927 status = AudioSystem::startOutput(mId, track->streamType(),
1928 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001929 mLock.lock();
1930 // abort track was stopped/paused while we released the lock
1931 if (state != track->mState) {
1932 if (status == NO_ERROR) {
1933 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08001934 AudioSystem::stopOutput(mId, track->streamType(),
1935 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001936 mLock.lock();
1937 }
1938 return INVALID_OPERATION;
1939 }
1940 // abort if start is rejected by audio policy manager
1941 if (status != NO_ERROR) {
1942 return PERMISSION_DENIED;
1943 }
1944#ifdef ADD_BATTERY_DATA
1945 // to track the speaker usage
1946 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
1947#endif
1948 }
1949
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001950 track->mFillingUpStatus = track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent81784c32012-11-19 14:55:58 -08001951 track->mResetDone = false;
1952 track->mPresentationCompleteFrames = 0;
1953 mActiveTracks.add(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001954 mWakeLockUids.add(track->uid());
1955 mActiveTracksGeneration++;
Eric Laurentfd477972013-10-25 18:10:40 -07001956 mLatestActiveTrack = track;
Eric Laurentd0107bc2013-06-11 14:38:48 -07001957 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1958 if (chain != 0) {
1959 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
1960 track->sessionId());
1961 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08001962 }
1963
1964 status = NO_ERROR;
1965 }
1966
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08001967 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001968 return status;
1969}
1970
Eric Laurentbfb1b832013-01-07 09:53:42 -08001971bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08001972{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001973 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08001974 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001975 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
1976 track->mState = TrackBase::STOPPED;
1977 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08001978 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07001979 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001980 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08001981 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001982
1983 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08001984}
1985
1986void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1987{
1988 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
1989 mTracks.remove(track);
1990 deleteTrackName_l(track->name());
1991 // redundant as track is about to be destroyed, for dumpsys only
1992 track->mName = -1;
1993 if (track->isFastTrack()) {
1994 int index = track->mFastIndex;
1995 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
1996 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1997 mFastTrackAvailMask |= 1 << index;
1998 // redundant as track is about to be destroyed, for dumpsys only
1999 track->mFastIndex = -1;
2000 }
2001 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2002 if (chain != 0) {
2003 chain->decTrackCnt();
2004 }
2005}
2006
Eric Laurentede6c3b2013-09-19 14:37:46 -07002007void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002008{
2009 // Thread could be blocked waiting for async
2010 // so signal it to handle state changes immediately
2011 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
2012 // be lost so we also flag to prevent it blocking on mWaitWorkCV
2013 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002014 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002015}
2016
Eric Laurent81784c32012-11-19 14:55:58 -08002017String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2018{
Eric Laurent81784c32012-11-19 14:55:58 -08002019 Mutex::Autolock _l(mLock);
2020 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07002021 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002022 }
2023
Glenn Kastend8ea6992013-07-16 14:17:15 -07002024 char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
2025 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08002026 free(s);
2027 return out_s8;
2028}
2029
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002030void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002031 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2032 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002033
Eric Laurent73e26b62015-04-27 16:55:58 -07002034 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002035
2036 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002037 case AUDIO_OUTPUT_OPENED:
2038 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002039 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002040 desc->mChannelMask = mChannelMask;
2041 desc->mSamplingRate = mSampleRate;
2042 desc->mFormat = mFormat;
2043 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002044 // AudioFlinger::frameCount(audio_io_handle_t)
Eric Laurent73e26b62015-04-27 16:55:58 -07002045 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002046 break;
2047
Eric Laurent73e26b62015-04-27 16:55:58 -07002048 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002049 default:
2050 break;
2051 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002052 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002053}
2054
Eric Laurentbfb1b832013-01-07 09:53:42 -08002055void AudioFlinger::PlaybackThread::writeCallback()
2056{
2057 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002058 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002059}
2060
2061void AudioFlinger::PlaybackThread::drainCallback()
2062{
2063 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002064 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002065}
2066
Eric Laurent3b4529e2013-09-05 18:09:19 -07002067void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002068{
2069 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002070 // reject out of sequence requests
2071 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2072 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002073 mWaitWorkCV.signal();
2074 }
2075}
2076
Eric Laurent3b4529e2013-09-05 18:09:19 -07002077void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002078{
2079 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002080 // reject out of sequence requests
2081 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
2082 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002083 mWaitWorkCV.signal();
2084 }
2085}
2086
2087// static
2088int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
Glenn Kasten0f11b512014-01-31 16:18:54 -08002089 void *param __unused,
Eric Laurentbfb1b832013-01-07 09:53:42 -08002090 void *cookie)
2091{
2092 AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
2093 ALOGV("asyncCallback() event %d", event);
2094 switch (event) {
2095 case STREAM_CBK_EVENT_WRITE_READY:
2096 me->writeCallback();
2097 break;
2098 case STREAM_CBK_EVENT_DRAIN_READY:
2099 me->drainCallback();
2100 break;
2101 default:
2102 ALOGW("asyncCallback() unknown event %d", event);
2103 break;
2104 }
2105 return 0;
2106}
2107
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002108void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002109{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002110 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Phil Burkca5e6142015-07-14 09:42:29 -07002111 mSampleRate = mOutput->getSampleRate();
2112 mChannelMask = mOutput->getChannelMask();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002113 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002114 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002115 }
Andy Hung9a592762014-07-21 21:56:01 -07002116 if ((mType == MIXER || mType == DUPLICATING)
2117 && !isValidPcmSinkChannelMask(mChannelMask)) {
2118 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2119 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002120 }
Andy Hunge5412692014-05-16 11:25:07 -07002121 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002122
2123 // Get actual HAL format.
Andy Hung463be252014-07-10 16:56:07 -07002124 mHALFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Phil Burkca5e6142015-07-14 09:42:29 -07002125 // Get format from the shim, which will be different than the HAL format
2126 // if playing compressed audio over HDMI passthrough.
2127 mFormat = mOutput->getFormat();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002128 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002129 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002130 }
Andy Hung6146c082014-03-18 11:56:15 -07002131 if ((mType == MIXER || mType == DUPLICATING)
2132 && !isValidPcmSinkFormat(mFormat)) {
2133 LOG_FATAL("HAL format %#x not supported for mixed output",
2134 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002135 }
Phil Burk062e67a2015-02-11 13:40:50 -08002136 mFrameSize = mOutput->getFrameSize();
Glenn Kasten70949c42013-08-06 07:40:12 -07002137 mBufferSize = mOutput->stream->common.get_buffer_size(&mOutput->stream->common);
2138 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002139 if (mFrameCount & 15) {
2140 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
2141 mFrameCount);
2142 }
2143
Eric Laurentbfb1b832013-01-07 09:53:42 -08002144 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
2145 (mOutput->stream->set_callback != NULL)) {
2146 if (mOutput->stream->set_callback(mOutput->stream,
2147 AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
2148 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002149 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002150 }
2151 }
2152
Eric Laurentd1f69b02014-12-15 14:33:13 -08002153 mHwSupportsPause = false;
2154 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
2155 if (mOutput->stream->pause != NULL) {
2156 if (mOutput->stream->resume != NULL) {
2157 mHwSupportsPause = true;
2158 } else {
2159 ALOGW("direct output implements pause but not resume");
2160 }
2161 } else if (mOutput->stream->resume != NULL) {
2162 ALOGW("direct output implements resume but not pause");
2163 }
2164 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002165 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2166 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2167 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002168
Andy Hungfbfc3952015-01-15 13:33:51 -08002169 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2170 // For best precision, we use float instead of the associated output
2171 // device format (typically PCM 16 bit).
2172
2173 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2174 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2175 mBufferSize = mFrameSize * mFrameCount;
2176
2177 // TODO: We currently use the associated output device channel mask and sample rate.
2178 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2179 // (if a valid mask) to avoid premature downmix.
2180 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2181 // instead of the output device sample rate to avoid loss of high frequency information.
2182 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2183 }
2184
Andy Hung09a50072014-02-27 14:30:47 -08002185 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002186 double multiplier = 1.0;
2187 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2188 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002189 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2190 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Eric Laurent81784c32012-11-19 14:55:58 -08002191 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2192 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2193 maxNormalFrameCount = maxNormalFrameCount & ~15;
2194 if (maxNormalFrameCount < minNormalFrameCount) {
2195 maxNormalFrameCount = minNormalFrameCount;
2196 }
2197 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2198 if (multiplier <= 1.0) {
2199 multiplier = 1.0;
2200 } else if (multiplier <= 2.0) {
2201 if (2 * mFrameCount <= maxNormalFrameCount) {
2202 multiplier = 2.0;
2203 } else {
2204 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2205 }
2206 } else {
2207 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
Andy Hung09a50072014-02-27 14:30:47 -08002208 // 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 -08002209 // track, but we sometimes have to do this to satisfy the maximum frame count
2210 // constraint)
2211 // FIXME this rounding up should not be done if no HAL SRC
2212 uint32_t truncMult = (uint32_t) multiplier;
2213 if ((truncMult & 1)) {
2214 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
2215 ++truncMult;
2216 }
2217 }
2218 multiplier = (double) truncMult;
2219 }
2220 }
2221 mNormalFrameCount = multiplier * mFrameCount;
2222 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002223 if (mType == MIXER || mType == DUPLICATING) {
2224 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2225 }
Andy Hung09a50072014-02-27 14:30:47 -08002226 ALOGI("HAL output buffer size %u frames, normal sink buffer size %u frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002227 mNormalFrameCount);
2228
Andy Hung08fb1742015-05-31 23:22:10 -07002229 // Check if we want to throttle the processing to no more than 2x normal rate
2230 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002231 mThreadThrottleTimeMs = 0;
2232 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002233 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2234
Andy Hung010a1a12014-03-13 13:57:33 -07002235 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2236 // Originally this was int16_t[] array, need to remove legacy implications.
2237 free(mSinkBuffer);
2238 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002239 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2240 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2241 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002242 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002243
Andy Hung69aed5f2014-02-25 17:24:40 -08002244 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2245 // drives the output.
2246 free(mMixerBuffer);
2247 mMixerBuffer = NULL;
2248 if (mMixerBufferEnabled) {
2249 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2250 mMixerBufferSize = mNormalFrameCount * mChannelCount
2251 * audio_bytes_per_sample(mMixerBufferFormat);
2252 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2253 }
Andy Hung98ef9782014-03-04 14:46:50 -08002254 free(mEffectBuffer);
2255 mEffectBuffer = NULL;
2256 if (mEffectBufferEnabled) {
2257 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
2258 mEffectBufferSize = mNormalFrameCount * mChannelCount
2259 * audio_bytes_per_sample(mEffectBufferFormat);
2260 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2261 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002262
Eric Laurent81784c32012-11-19 14:55:58 -08002263 // force reconfiguration of effect chains and engines to take new buffer size and audio
2264 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002265 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002266 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2267 // matter.
2268 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2269 Vector< sp<EffectChain> > effectChains = mEffectChains;
2270 for (size_t i = 0; i < effectChains.size(); i ++) {
2271 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2272 }
2273}
2274
2275
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002276status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002277{
2278 if (halFrames == NULL || dspFrames == NULL) {
2279 return BAD_VALUE;
2280 }
2281 Mutex::Autolock _l(mLock);
2282 if (initCheck() != NO_ERROR) {
2283 return INVALID_OPERATION;
2284 }
2285 size_t framesWritten = mBytesWritten / mFrameSize;
2286 *halFrames = framesWritten;
2287
2288 if (isSuspended()) {
2289 // return an estimation of rendered frames when the output is suspended
2290 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
2291 *dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0;
2292 return NO_ERROR;
2293 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002294 status_t status;
2295 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002296 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002297 *dspFrames = (size_t)frames;
2298 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002299 }
2300}
2301
2302uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
2303{
2304 Mutex::Autolock _l(mLock);
2305 uint32_t result = 0;
2306 if (getEffectChain_l(sessionId) != 0) {
2307 result = EFFECT_SESSION;
2308 }
2309
2310 for (size_t i = 0; i < mTracks.size(); ++i) {
2311 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002312 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002313 result |= TRACK_SESSION;
2314 break;
2315 }
2316 }
2317
2318 return result;
2319}
2320
2321uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
2322{
2323 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2324 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2325 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2326 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2327 }
2328 for (size_t i = 0; i < mTracks.size(); i++) {
2329 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002330 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002331 return AudioSystem::getStrategyForStream(track->streamType());
2332 }
2333 }
2334 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2335}
2336
2337
Phil Burk062e67a2015-02-11 13:40:50 -08002338AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002339{
2340 Mutex::Autolock _l(mLock);
2341 return mOutput;
2342}
2343
Phil Burk062e67a2015-02-11 13:40:50 -08002344AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002345{
2346 Mutex::Autolock _l(mLock);
2347 AudioStreamOut *output = mOutput;
2348 mOutput = NULL;
2349 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2350 // must push a NULL and wait for ack
2351 mOutputSink.clear();
2352 mPipeSink.clear();
2353 mNormalSink.clear();
2354 return output;
2355}
2356
2357// this method must always be called either with ThreadBase mLock held or inside the thread loop
2358audio_stream_t* AudioFlinger::PlaybackThread::stream() const
2359{
2360 if (mOutput == NULL) {
2361 return NULL;
2362 }
2363 return &mOutput->stream->common;
2364}
2365
2366uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2367{
2368 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2369}
2370
2371status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2372{
2373 if (!isValidSyncEvent(event)) {
2374 return BAD_VALUE;
2375 }
2376
2377 Mutex::Autolock _l(mLock);
2378
2379 for (size_t i = 0; i < mTracks.size(); ++i) {
2380 sp<Track> track = mTracks[i];
2381 if (event->triggerSession() == track->sessionId()) {
2382 (void) track->setSyncEvent(event);
2383 return NO_ERROR;
2384 }
2385 }
2386
2387 return NAME_NOT_FOUND;
2388}
2389
2390bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2391{
2392 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2393}
2394
2395void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2396 const Vector< sp<Track> >& tracksToRemove)
2397{
2398 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002399 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002400 for (size_t i = 0 ; i < count ; i++) {
2401 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002402 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002403 AudioSystem::stopOutput(mId, track->streamType(),
2404 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002405#ifdef ADD_BATTERY_DATA
2406 // to track the speaker usage
2407 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2408#endif
2409 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002410 AudioSystem::releaseOutput(mId, track->streamType(),
2411 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002412 }
Eric Laurent81784c32012-11-19 14:55:58 -08002413 }
2414 }
2415 }
Eric Laurent81784c32012-11-19 14:55:58 -08002416}
2417
2418void AudioFlinger::PlaybackThread::checkSilentMode_l()
2419{
2420 if (!mMasterMute) {
2421 char value[PROPERTY_VALUE_MAX];
2422 if (property_get("ro.audio.silent", value, "0") > 0) {
2423 char *endptr;
2424 unsigned long ul = strtoul(value, &endptr, 0);
2425 if (*endptr == '\0' && ul != 0) {
2426 ALOGD("Silence is golden");
2427 // The setprop command will not allow a property to be changed after
2428 // the first time it is set, so we don't have to worry about un-muting.
2429 setMasterMute_l(true);
2430 }
2431 }
2432 }
2433}
2434
2435// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002436ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002437{
2438 // FIXME rewrite to reduce number of system calls
2439 mLastWriteTime = systemTime();
2440 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002441 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002442 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002443
2444 // If an NBAIO sink is present, use it to write the normal mixer's submix
2445 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002446
Andy Hung010a1a12014-03-13 13:57:33 -07002447 const size_t count = mBytesRemaining / mFrameSize;
2448
Simon Wilson2d590962012-11-29 15:18:50 -08002449 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002450 // update the setpoint when AudioFlinger::mScreenState changes
2451 uint32_t screenState = AudioFlinger::mScreenState;
2452 if (screenState != mScreenState) {
2453 mScreenState = screenState;
2454 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2455 if (pipe != NULL) {
2456 pipe->setAvgFrames((mScreenState & 1) ?
2457 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2458 }
2459 }
Andy Hung010a1a12014-03-13 13:57:33 -07002460 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002461 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002462 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002463 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002464 } else {
2465 bytesWritten = framesWritten;
2466 }
Glenn Kastenefaa7ab2014-08-20 08:48:54 -07002467 mLatchDValid = false;
Glenn Kasten767094d2013-08-23 13:51:43 -07002468 status_t status = mNormalSink->getTimestamp(mLatchD.mTimestamp);
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002469 if (status == NO_ERROR) {
2470 size_t totalFramesWritten = mNormalSink->framesWritten();
2471 if (totalFramesWritten >= mLatchD.mTimestamp.mPosition) {
2472 mLatchD.mUnpresentedFrames = totalFramesWritten - mLatchD.mTimestamp.mPosition;
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002473 // mLatchD.mFramesReleased is set immediately before D is clocked into Q
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002474 mLatchDValid = true;
2475 }
2476 }
Eric Laurent81784c32012-11-19 14:55:58 -08002477 // otherwise use the HAL / AudioStreamOut directly
2478 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002479 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002480
Eric Laurentbfb1b832013-01-07 09:53:42 -08002481 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002482 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2483 mWriteAckSequence += 2;
2484 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002485 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002486 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002487 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002488 // FIXME We should have an implementation of timestamps for direct output threads.
2489 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002490 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002491 if (mUseAsyncWrite &&
2492 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2493 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002494 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002495 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002496 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002497 }
Eric Laurent81784c32012-11-19 14:55:58 -08002498 }
2499
Eric Laurent81784c32012-11-19 14:55:58 -08002500 mNumWrites++;
2501 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002502 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002503 return bytesWritten;
2504}
2505
2506void AudioFlinger::PlaybackThread::threadLoop_drain()
2507{
2508 if (mOutput->stream->drain) {
2509 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2510 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002511 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2512 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002513 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002514 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002515 }
2516 mOutput->stream->drain(mOutput->stream,
2517 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
2518 : AUDIO_DRAIN_ALL);
2519 }
2520}
2521
2522void AudioFlinger::PlaybackThread::threadLoop_exit()
2523{
Eric Laurent275e8e92014-11-30 15:14:47 -08002524 {
2525 Mutex::Autolock _l(mLock);
2526 for (size_t i = 0; i < mTracks.size(); i++) {
2527 sp<Track> track = mTracks[i];
2528 track->invalidate();
2529 }
2530 }
Eric Laurent81784c32012-11-19 14:55:58 -08002531}
2532
2533/*
2534The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002535 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002536 - mActiveSleepTimeUs from activeSleepTimeUs()
2537 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent113efbb2016-01-08 17:16:42 -08002538 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
2539 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08002540 - maxPeriod from frame count and sample rate (MIXER only)
2541
2542The parameters that affect these derived values are:
2543 - frame count
2544 - frame size
2545 - sample rate
2546 - device type: A2DP or not
2547 - device latency
2548 - format: PCM or not
2549 - active sleep time
2550 - idle sleep time
2551*/
2552
2553void AudioFlinger::PlaybackThread::cacheParameters_l()
2554{
Andy Hung25c2dac2014-02-27 14:56:00 -08002555 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002556 mActiveSleepTimeUs = activeSleepTimeUs();
2557 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent113efbb2016-01-08 17:16:42 -08002558
2559 // make sure standby delay is not too short when connected to an A2DP sink to avoid
2560 // truncating audio when going to standby.
2561 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
2562 if ((mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != 0) {
2563 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
2564 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
2565 }
2566 }
Eric Laurent81784c32012-11-19 14:55:58 -08002567}
2568
2569void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2570{
Glenn Kasten7c027242012-12-26 14:43:16 -08002571 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurent81784c32012-11-19 14:55:58 -08002572 this, streamType, mTracks.size());
2573 Mutex::Autolock _l(mLock);
2574
2575 size_t size = mTracks.size();
2576 for (size_t i = 0; i < size; i++) {
2577 sp<Track> t = mTracks[i];
2578 if (t->streamType() == streamType) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002579 t->invalidate();
Eric Laurent81784c32012-11-19 14:55:58 -08002580 }
2581 }
2582}
2583
2584status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2585{
2586 int session = chain->sessionId();
Andy Hung010a1a12014-03-13 13:57:33 -07002587 int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled
2588 ? mEffectBuffer : mSinkBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002589 bool ownsBuffer = false;
2590
2591 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
2592 if (session > 0) {
2593 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002594 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002595 if (mType != DIRECT) {
2596 size_t numSamples = mNormalFrameCount * mChannelCount;
2597 buffer = new int16_t[numSamples];
2598 memset(buffer, 0, numSamples * sizeof(int16_t));
2599 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2600 ownsBuffer = true;
2601 }
2602
2603 // Attach all tracks with same session ID to this chain.
2604 for (size_t i = 0; i < mTracks.size(); ++i) {
2605 sp<Track> track = mTracks[i];
2606 if (session == track->sessionId()) {
2607 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2608 buffer);
2609 track->setMainBuffer(buffer);
2610 chain->incTrackCnt();
2611 }
2612 }
2613
2614 // indicate all active tracks in the chain
2615 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2616 sp<Track> track = mActiveTracks[i].promote();
2617 if (track == 0) {
2618 continue;
2619 }
2620 if (session == track->sessionId()) {
2621 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2622 chain->incActiveTrackCnt();
2623 }
2624 }
2625 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002626 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08002627 chain->setInBuffer(buffer, ownsBuffer);
Andy Hung010a1a12014-03-13 13:57:33 -07002628 chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled
2629 ? mEffectBuffer : mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002630 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
2631 // chains list in order to be processed last as it contains output stage effects
2632 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2633 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
2634 // after track specific effects and before output stage
2635 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
2636 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
2637 // Effect chain for other sessions are inserted at beginning of effect
2638 // chains list to be processed before output mix effects. Relative order between other
2639 // sessions is not important
2640 size_t size = mEffectChains.size();
2641 size_t i = 0;
2642 for (i = 0; i < size; i++) {
2643 if (mEffectChains[i]->sessionId() < session) {
2644 break;
2645 }
2646 }
2647 mEffectChains.insertAt(chain, i);
2648 checkSuspendOnAddEffectChain_l(chain);
2649
2650 return NO_ERROR;
2651}
2652
2653size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2654{
2655 int session = chain->sessionId();
2656
2657 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2658
2659 for (size_t i = 0; i < mEffectChains.size(); i++) {
2660 if (chain == mEffectChains[i]) {
2661 mEffectChains.removeAt(i);
2662 // detach all active tracks from the chain
2663 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2664 sp<Track> track = mActiveTracks[i].promote();
2665 if (track == 0) {
2666 continue;
2667 }
2668 if (session == track->sessionId()) {
2669 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2670 chain.get(), session);
2671 chain->decActiveTrackCnt();
2672 }
2673 }
2674
2675 // detach all tracks with same session ID from this chain
2676 for (size_t i = 0; i < mTracks.size(); ++i) {
2677 sp<Track> track = mTracks[i];
2678 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002679 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002680 chain->decTrackCnt();
2681 }
2682 }
2683 break;
2684 }
2685 }
2686 return mEffectChains.size();
2687}
2688
2689status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2690 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2691{
2692 Mutex::Autolock _l(mLock);
2693 return attachAuxEffect_l(track, EffectId);
2694}
2695
2696status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2697 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2698{
2699 status_t status = NO_ERROR;
2700
2701 if (EffectId == 0) {
2702 track->setAuxBuffer(0, NULL);
2703 } else {
2704 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2705 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2706 if (effect != 0) {
2707 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2708 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2709 } else {
2710 status = INVALID_OPERATION;
2711 }
2712 } else {
2713 status = BAD_VALUE;
2714 }
2715 }
2716 return status;
2717}
2718
2719void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2720{
2721 for (size_t i = 0; i < mTracks.size(); ++i) {
2722 sp<Track> track = mTracks[i];
2723 if (track->auxEffectId() == effectId) {
2724 attachAuxEffect_l(track, 0);
2725 }
2726 }
2727}
2728
2729bool AudioFlinger::PlaybackThread::threadLoop()
2730{
2731 Vector< sp<Track> > tracksToRemove;
2732
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002733 mStandbyTimeNs = systemTime();
Eric Laurent81784c32012-11-19 14:55:58 -08002734
2735 // MIXER
2736 nsecs_t lastWarning = 0;
2737
2738 // DUPLICATING
2739 // FIXME could this be made local to while loop?
2740 writeFrames = 0;
2741
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002742 int lastGeneration = 0;
2743
Eric Laurent81784c32012-11-19 14:55:58 -08002744 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002745 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08002746
2747 if (mType == MIXER) {
2748 sleepTimeShift = 0;
2749 }
2750
2751 CpuStats cpuStats;
2752 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2753
2754 acquireWakeLock();
2755
Glenn Kasten9e58b552013-01-18 15:09:48 -08002756 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2757 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2758 // and then that string will be logged at the next convenient opportunity.
2759 const char *logString = NULL;
2760
Eric Laurent664539d2013-09-23 18:24:31 -07002761 checkSilentMode_l();
2762
Eric Laurent81784c32012-11-19 14:55:58 -08002763 while (!exitPending())
2764 {
2765 cpuStats.sample(myName);
2766
2767 Vector< sp<EffectChain> > effectChains;
2768
Eric Laurent81784c32012-11-19 14:55:58 -08002769 { // scope for mLock
2770
2771 Mutex::Autolock _l(mLock);
2772
Eric Laurent021cf962014-05-13 10:18:14 -07002773 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07002774
Glenn Kasten9e58b552013-01-18 15:09:48 -08002775 if (logString != NULL) {
2776 mNBLogWriter->logTimestamp();
2777 mNBLogWriter->log(logString);
2778 logString = NULL;
2779 }
2780
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002781 // Gather the framesReleased counters for all active tracks,
2782 // and latch them atomically with the timestamp.
2783 // FIXME We're using raw pointers as indices. A unique track ID would be a better index.
2784 mLatchD.mFramesReleased.clear();
2785 size_t size = mActiveTracks.size();
2786 for (size_t i = 0; i < size; i++) {
2787 sp<Track> t = mActiveTracks[i].promote();
2788 if (t != 0) {
2789 mLatchD.mFramesReleased.add(t.get(),
2790 t->mAudioTrackServerProxy->framesReleased());
2791 }
2792 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002793 if (mLatchDValid) {
2794 mLatchQ = mLatchD;
2795 mLatchDValid = false;
2796 mLatchQValid = true;
2797 }
2798
Eric Laurent81784c32012-11-19 14:55:58 -08002799 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002800 if (mSignalPending) {
2801 // A signal was raised while we were unlocked
2802 mSignalPending = false;
2803 } else if (waitingAsyncCallback_l()) {
2804 if (exitPending()) {
2805 break;
2806 }
Marco Nelissen078538c2015-05-12 09:17:57 -07002807 bool released = false;
2808 // The following works around a bug in the offload driver. Ideally we would release
2809 // the wake lock every time, but that causes the last offload buffer(s) to be
2810 // dropped while the device is on battery, so we need to hold a wake lock during
2811 // the drain phase.
2812 if (mBytesRemaining && !(mDrainSequence & 1)) {
2813 releaseWakeLock_l();
2814 released = true;
2815 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002816 mWakeLockUids.clear();
2817 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002818 ALOGV("wait async completion");
2819 mWaitWorkCV.wait(mLock);
2820 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07002821 if (released) {
2822 acquireWakeLock_l();
2823 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002824 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
2825 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002826
2827 continue;
2828 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002829 if ((!mActiveTracks.size() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08002830 isSuspended()) {
2831 // put audio hardware into standby after short delay
2832 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002833
2834 threadLoop_standby();
2835
2836 mStandby = true;
2837 }
2838
2839 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2840 // we're about to wait, flush the binder command buffer
2841 IPCThreadState::self()->flushCommands();
2842
2843 clearOutputTracks();
2844
2845 if (exitPending()) {
2846 break;
2847 }
2848
2849 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002850 mWakeLockUids.clear();
2851 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002852 // wait until we have something to do...
2853 ALOGV("%s going to sleep", myName.string());
2854 mWaitWorkCV.wait(mLock);
2855 ALOGV("%s waking up", myName.string());
2856 acquireWakeLock_l();
2857
2858 mMixerStatus = MIXER_IDLE;
2859 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2860 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002861 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002862 checkSilentMode_l();
2863
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002864 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
2865 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08002866 if (mType == MIXER) {
2867 sleepTimeShift = 0;
2868 }
2869
2870 continue;
2871 }
2872 }
Eric Laurent81784c32012-11-19 14:55:58 -08002873 // mMixerStatusIgnoringFastTracks is also updated internally
2874 mMixerStatus = prepareTracks_l(&tracksToRemove);
2875
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002876 // compare with previously applied list
2877 if (lastGeneration != mActiveTracksGeneration) {
2878 // update wakelock
2879 updateWakeLockUids_l(mWakeLockUids);
2880 lastGeneration = mActiveTracksGeneration;
2881 }
2882
Eric Laurent81784c32012-11-19 14:55:58 -08002883 // prevent any changes in effect chain list and in each effect chain
2884 // during mixing and effect process as the audio buffers could be deleted
2885 // or modified if an effect is created or deleted
2886 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002887 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08002888
Eric Laurentbfb1b832013-01-07 09:53:42 -08002889 if (mBytesRemaining == 0) {
2890 mCurrentWriteLength = 0;
2891 if (mMixerStatus == MIXER_TRACKS_READY) {
2892 // threadLoop_mix() sets mCurrentWriteLength
2893 threadLoop_mix();
2894 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
2895 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002896 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08002897 // must be written to HAL
2898 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002899 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08002900 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002901 }
2902 }
Andy Hung98ef9782014-03-04 14:46:50 -08002903 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002904 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08002905 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
2906 // or mSinkBuffer (if there are no effects).
2907 //
2908 // This is done pre-effects computation; if effects change to
2909 // support higher precision, this needs to move.
2910 //
2911 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002912 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08002913 if (mMixerBufferValid) {
2914 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
2915 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
2916
2917 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
2918 mNormalFrameCount * mChannelCount);
2919 }
2920
Eric Laurentbfb1b832013-01-07 09:53:42 -08002921 mBytesRemaining = mCurrentWriteLength;
2922 if (isSuspended()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002923 mSleepTimeUs = suspendSleepTimeUs();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002924 // simulate write to HAL when suspended
Andy Hung25c2dac2014-02-27 14:56:00 -08002925 mBytesWritten += mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002926 mBytesRemaining = 0;
2927 }
Eric Laurent81784c32012-11-19 14:55:58 -08002928
Eric Laurentbfb1b832013-01-07 09:53:42 -08002929 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002930 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002931 for (size_t i = 0; i < effectChains.size(); i ++) {
2932 effectChains[i]->process_l();
2933 }
Eric Laurent81784c32012-11-19 14:55:58 -08002934 }
2935 }
Eric Laurent59fe0102013-09-27 18:48:26 -07002936 // Process effect chains for offloaded thread even if no audio
2937 // was read from audio track: process only updates effect state
2938 // and thus does have to be synchronized with audio writes but may have
2939 // to be called while waiting for async write callback
2940 if (mType == OFFLOAD) {
2941 for (size_t i = 0; i < effectChains.size(); i ++) {
2942 effectChains[i]->process_l();
2943 }
2944 }
Eric Laurent81784c32012-11-19 14:55:58 -08002945
Andy Hung98ef9782014-03-04 14:46:50 -08002946 // Only if the Effects buffer is enabled and there is data in the
2947 // Effects buffer (buffer valid), we need to
2948 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002949 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08002950 if (mEffectBufferValid) {
2951 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
2952 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
2953 mNormalFrameCount * mChannelCount);
2954 }
2955
Eric Laurent81784c32012-11-19 14:55:58 -08002956 // enable changes in effect chain
2957 unlockEffectChains(effectChains);
2958
Eric Laurentbfb1b832013-01-07 09:53:42 -08002959 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002960 // mSleepTimeUs == 0 means we must write to audio hardware
2961 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07002962 ssize_t ret = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002963 if (mBytesRemaining) {
Andy Hung08fb1742015-05-31 23:22:10 -07002964 ret = threadLoop_write();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002965 if (ret < 0) {
2966 mBytesRemaining = 0;
2967 } else {
2968 mBytesWritten += ret;
2969 mBytesRemaining -= ret;
2970 }
2971 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
2972 (mMixerStatus == MIXER_DRAIN_ALL)) {
2973 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08002974 }
Andy Hung08fb1742015-05-31 23:22:10 -07002975 if (mType == MIXER && !mStandby) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07002976 // write blocked detection
2977 nsecs_t now = systemTime();
2978 nsecs_t delta = now - mLastWriteTime;
Andy Hung08fb1742015-05-31 23:22:10 -07002979 if (delta > maxPeriod) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07002980 mNumDelayedWrites++;
2981 if ((now - lastWarning) > kWarningThrottleNs) {
2982 ATRACE_NAME("underrun");
2983 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2984 ns2ms(delta), mNumDelayedWrites, this);
2985 lastWarning = now;
2986 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002987 }
Andy Hung08fb1742015-05-31 23:22:10 -07002988
2989 if (mThreadThrottle
2990 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
2991 && ret > 0) { // we wrote something
2992 // Limit MixerThread data processing to no more than twice the
2993 // expected processing rate.
2994 //
2995 // This helps prevent underruns with NuPlayer and other applications
2996 // which may set up buffers that are close to the minimum size, or use
2997 // deep buffers, and rely on a double-buffering sleep strategy to fill.
2998 //
2999 // The throttle smooths out sudden large data drains from the device,
3000 // e.g. when it comes out of standby, which often causes problems with
3001 // (1) mixer threads without a fast mixer (which has its own warm-up)
3002 // (2) minimum buffer sized tracks (even if the track is full,
3003 // the app won't fill fast enough to handle the sudden draw).
3004
3005 const int32_t deltaMs = delta / 1000000;
3006 const int32_t throttleMs = mHalfBufferMs - deltaMs;
3007 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
3008 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003009 // notify of throttle start on verbose log
3010 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3011 "mixer(%p) throttle begin:"
3012 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003013 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07003014 mThreadThrottleTimeMs += throttleMs;
3015 } else {
3016 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3017 if (diff > 0) {
3018 // notify of throttle end on debug log
3019 ALOGD("mixer(%p) throttle end: throttle time(%u)", this, diff);
3020 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3021 }
Andy Hung08fb1742015-05-31 23:22:10 -07003022 }
3023 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003024 }
Eric Laurent81784c32012-11-19 14:55:58 -08003025
Eric Laurentbfb1b832013-01-07 09:53:42 -08003026 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003027 ATRACE_BEGIN("sleep");
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003028 usleep(mSleepTimeUs);
Glenn Kastene7754022014-10-31 12:11:26 -07003029 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003030 }
Eric Laurent81784c32012-11-19 14:55:58 -08003031 }
3032
3033 // Finally let go of removed track(s), without the lock held
3034 // since we can't guarantee the destructors won't acquire that
3035 // same lock. This will also mutate and push a new fast mixer state.
3036 threadLoop_removeTracks(tracksToRemove);
3037 tracksToRemove.clear();
3038
3039 // FIXME I don't understand the need for this here;
3040 // it was in the original code but maybe the
3041 // assignment in saveOutputTracks() makes this unnecessary?
3042 clearOutputTracks();
3043
3044 // Effect chains will be actually deleted here if they were removed from
3045 // mEffectChains list during mixing or effects processing
3046 effectChains.clear();
3047
3048 // FIXME Note that the above .clear() is no longer necessary since effectChains
3049 // is now local to this block, but will keep it for now (at least until merge done).
3050 }
3051
Eric Laurentbfb1b832013-01-07 09:53:42 -08003052 threadLoop_exit();
3053
Eric Laurentcf817a22014-08-04 20:36:31 -07003054 if (!mStandby) {
3055 threadLoop_standby();
3056 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003057 }
3058
3059 releaseWakeLock();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003060 mWakeLockUids.clear();
3061 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08003062
3063 ALOGV("Thread %p type %d exiting", this, mType);
3064 return false;
3065}
3066
Eric Laurentbfb1b832013-01-07 09:53:42 -08003067// removeTracks_l() must be called with ThreadBase::mLock held
3068void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3069{
3070 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07003071 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003072 for (size_t i=0 ; i<count ; i++) {
3073 const sp<Track>& track = tracksToRemove.itemAt(i);
3074 mActiveTracks.remove(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003075 mWakeLockUids.remove(track->uid());
3076 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003077 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
3078 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3079 if (chain != 0) {
3080 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
3081 track->sessionId());
3082 chain->decActiveTrackCnt();
3083 }
3084 if (track->isTerminated()) {
3085 removeTrack_l(track);
3086 }
3087 }
3088 }
3089
3090}
Eric Laurent81784c32012-11-19 14:55:58 -08003091
Eric Laurentaccc1472013-09-20 09:36:34 -07003092status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3093{
3094 if (mNormalSink != 0) {
3095 return mNormalSink->getTimestamp(timestamp);
3096 }
Andy Hung9a1c8892014-12-03 11:37:42 -08003097 if ((mType == OFFLOAD || mType == DIRECT)
3098 && mOutput != NULL && mOutput->stream->get_presentation_position) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003099 uint64_t position64;
Phil Burk062e67a2015-02-11 13:40:50 -08003100 int ret = mOutput->getPresentationPosition(&position64, &timestamp.mTime);
Eric Laurentaccc1472013-09-20 09:36:34 -07003101 if (ret == 0) {
3102 timestamp.mPosition = (uint32_t)position64;
3103 return NO_ERROR;
3104 }
3105 }
3106 return INVALID_OPERATION;
3107}
Eric Laurent1c333e22014-05-20 10:48:17 -07003108
Eric Laurent054d9d32015-04-24 08:48:48 -07003109status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
3110 audio_patch_handle_t *handle)
3111{
3112 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3113 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3114 if (mFastMixer != 0) {
3115 FastMixerStateQueue *sq = mFastMixer->sq();
3116 FastMixerState *state = sq->begin();
3117 if (!(state->mCommand & FastMixerState::IDLE)) {
3118 previousCommand = state->mCommand;
3119 state->mCommand = FastMixerState::HOT_IDLE;
3120 sq->end();
3121 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3122 } else {
3123 sq->end(false /*didModify*/);
3124 }
3125 }
3126 status_t status = PlaybackThread::createAudioPatch_l(patch, handle);
3127
3128 if (!(previousCommand & FastMixerState::IDLE)) {
3129 ALOG_ASSERT(mFastMixer != 0);
3130 FastMixerStateQueue *sq = mFastMixer->sq();
3131 FastMixerState *state = sq->begin();
3132 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3133 state->mCommand = previousCommand;
3134 sq->end();
3135 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3136 }
3137
3138 return status;
3139}
3140
Eric Laurent1c333e22014-05-20 10:48:17 -07003141status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3142 audio_patch_handle_t *handle)
3143{
3144 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003145
3146 // store new device and send to effects
3147 audio_devices_t type = AUDIO_DEVICE_NONE;
3148 for (unsigned int i = 0; i < patch->num_sinks; i++) {
3149 type |= patch->sinks[i].ext.device.type;
3150 }
3151
3152#ifdef ADD_BATTERY_DATA
3153 // when changing the audio output device, call addBatteryData to notify
3154 // the change
3155 if (mOutDevice != type) {
3156 uint32_t params = 0;
3157 // check whether speaker is on
3158 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3159 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003160 }
3161
Eric Laurent054d9d32015-04-24 08:48:48 -07003162 audio_devices_t deviceWithoutSpeaker
3163 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3164 // check if any other device (except speaker) is on
3165 if (type & deviceWithoutSpeaker) {
3166 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3167 }
3168
3169 if (params != 0) {
3170 addBatteryData(params);
3171 }
3172 }
3173#endif
3174
3175 for (size_t i = 0; i < mEffectChains.size(); i++) {
3176 mEffectChains[i]->setDevice_l(type);
3177 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003178
3179 // mPrevOutDevice is the latest device set by createAudioPatch_l(). It is not set when
3180 // the thread is created so that the first patch creation triggers an ioConfigChanged callback
3181 bool configChanged = mPrevOutDevice != type;
Eric Laurent054d9d32015-04-24 08:48:48 -07003182 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003183 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003184
3185 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003186 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
3187 status = hwDevice->create_audio_patch(hwDevice,
3188 patch->num_sources,
3189 patch->sources,
3190 patch->num_sinks,
3191 patch->sinks,
3192 handle);
3193 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003194 char *address;
3195 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3196 //FIXME: we only support address on first sink with HAL version < 3.0
3197 address = audio_device_address_to_parameter(
3198 patch->sinks[0].ext.device.type,
3199 patch->sinks[0].ext.device.address);
3200 } else {
3201 address = (char *)calloc(1, 1);
3202 }
3203 AudioParameter param = AudioParameter(String8(address));
3204 free(address);
3205 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), (int)type);
3206 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3207 param.toString().string());
3208 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003209 }
Eric Laurente8726fe2015-06-26 09:39:24 -07003210 if (configChanged) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003211 mPrevOutDevice = type;
Eric Laurente8726fe2015-06-26 09:39:24 -07003212 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
3213 }
Eric Laurent1c333e22014-05-20 10:48:17 -07003214 return status;
3215}
3216
Eric Laurent054d9d32015-04-24 08:48:48 -07003217status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3218{
3219 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3220 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3221 if (mFastMixer != 0) {
3222 FastMixerStateQueue *sq = mFastMixer->sq();
3223 FastMixerState *state = sq->begin();
3224 if (!(state->mCommand & FastMixerState::IDLE)) {
3225 previousCommand = state->mCommand;
3226 state->mCommand = FastMixerState::HOT_IDLE;
3227 sq->end();
3228 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3229 } else {
3230 sq->end(false /*didModify*/);
3231 }
3232 }
3233
3234 status_t status = PlaybackThread::releaseAudioPatch_l(handle);
3235
3236 if (!(previousCommand & FastMixerState::IDLE)) {
3237 ALOG_ASSERT(mFastMixer != 0);
3238 FastMixerStateQueue *sq = mFastMixer->sq();
3239 FastMixerState *state = sq->begin();
3240 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3241 state->mCommand = previousCommand;
3242 sq->end();
3243 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3244 }
3245
3246 return status;
3247}
3248
Eric Laurent1c333e22014-05-20 10:48:17 -07003249status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3250{
3251 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003252
3253 mOutDevice = AUDIO_DEVICE_NONE;
3254
Eric Laurent1c333e22014-05-20 10:48:17 -07003255 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
3256 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
3257 status = hwDevice->release_audio_patch(hwDevice, handle);
3258 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003259 AudioParameter param;
3260 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
3261 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3262 param.toString().string());
Eric Laurent1c333e22014-05-20 10:48:17 -07003263 }
3264 return status;
3265}
3266
Eric Laurent83b88082014-06-20 18:31:16 -07003267void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3268{
3269 Mutex::Autolock _l(mLock);
3270 mTracks.add(track);
3271}
3272
3273void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3274{
3275 Mutex::Autolock _l(mLock);
3276 destroyTrack_l(track);
3277}
3278
3279void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
3280{
3281 ThreadBase::getAudioPortConfig(config);
3282 config->role = AUDIO_PORT_ROLE_SOURCE;
3283 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3284 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
3285}
3286
Eric Laurent81784c32012-11-19 14:55:58 -08003287// ----------------------------------------------------------------------------
3288
3289AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurent72e3f392015-05-20 14:43:50 -07003290 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
3291 : PlaybackThread(audioFlinger, output, id, device, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08003292 // mAudioMixer below
3293 // mFastMixer below
3294 mFastMixerFutex(0)
3295 // mOutputSink below
3296 // mPipeSink below
3297 // mNormalSink below
3298{
3299 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07003300 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, "
Eric Laurent81784c32012-11-19 14:55:58 -08003301 "mFrameCount=%d, mNormalFrameCount=%d",
3302 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3303 mNormalFrameCount);
3304 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3305
Andy Hungfbfc3952015-01-15 13:33:51 -08003306 if (type == DUPLICATING) {
3307 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3308 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3309 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3310 return;
3311 }
Eric Laurent81784c32012-11-19 14:55:58 -08003312 // create an NBAIO sink for the HAL output stream, and negotiate
3313 mOutputSink = new AudioStreamOutSink(output->stream);
3314 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003315 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Eric Laurent81784c32012-11-19 14:55:58 -08003316 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
3317 ALOG_ASSERT(index == 0);
3318
3319 // initialize fast mixer depending on configuration
3320 bool initFastMixer;
3321 switch (kUseFastMixer) {
3322 case FastMixer_Never:
3323 initFastMixer = false;
3324 break;
3325 case FastMixer_Always:
3326 initFastMixer = true;
3327 break;
3328 case FastMixer_Static:
3329 case FastMixer_Dynamic:
3330 initFastMixer = mFrameCount < mNormalFrameCount;
3331 break;
3332 }
3333 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003334 audio_format_t fastMixerFormat;
3335 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3336 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3337 } else {
3338 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3339 }
3340 if (mFormat != fastMixerFormat) {
3341 // change our Sink format to accept our intermediate precision
3342 mFormat = fastMixerFormat;
3343 free(mSinkBuffer);
3344 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3345 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3346 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3347 }
Eric Laurent81784c32012-11-19 14:55:58 -08003348
3349 // create a MonoPipe to connect our submix to FastMixer
3350 NBAIO_Format format = mOutputSink->format();
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003351 NBAIO_Format origformat = format;
Andy Hung1258c1a2014-05-23 21:22:17 -07003352 // adjust format to match that of the Fast Mixer
Glenn Kasten97b7b752014-09-28 13:04:24 -07003353 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003354 format.mFormat = fastMixerFormat;
3355 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3356
Eric Laurent81784c32012-11-19 14:55:58 -08003357 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3358 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3359 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3360 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3361 const NBAIO_Format offers[1] = {format};
3362 size_t numCounterOffers = 0;
3363 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
3364 ALOG_ASSERT(index == 0);
3365 monoPipe->setAvgFrames((mScreenState & 1) ?
3366 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3367 mPipeSink = monoPipe;
3368
Glenn Kasten46909e72013-02-26 09:20:22 -08003369#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08003370 if (mTeeSinkOutputEnabled) {
3371 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003372 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
3373 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08003374 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003375 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003376 ALOG_ASSERT(index == 0);
3377 mTeeSink = teeSink;
3378 PipeReader *teeSource = new PipeReader(*teeSink);
3379 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003380 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003381 ALOG_ASSERT(index == 0);
3382 mTeeSource = teeSource;
3383 }
Glenn Kasten46909e72013-02-26 09:20:22 -08003384#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003385
3386 // create fast mixer and configure it initially with just one fast track for our submix
3387 mFastMixer = new FastMixer();
3388 FastMixerStateQueue *sq = mFastMixer->sq();
3389#ifdef STATE_QUEUE_DUMP
3390 sq->setObserverDump(&mStateQueueObserverDump);
3391 sq->setMutatorDump(&mStateQueueMutatorDump);
3392#endif
3393 FastMixerState *state = sq->begin();
3394 FastTrack *fastTrack = &state->mFastTracks[0];
3395 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3396 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3397 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003398 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3399 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003400 fastTrack->mGeneration++;
3401 state->mFastTracksGen++;
3402 state->mTrackMask = 1;
3403 // fast mixer will use the HAL output sink
3404 state->mOutputSink = mOutputSink.get();
3405 state->mOutputSinkGen++;
3406 state->mFrameCount = mFrameCount;
3407 state->mCommand = FastMixerState::COLD_IDLE;
3408 // already done in constructor initialization list
3409 //mFastMixerFutex = 0;
3410 state->mColdFutexAddr = &mFastMixerFutex;
3411 state->mColdGen++;
3412 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08003413#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003414 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08003415#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08003416 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3417 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003418 sq->end();
3419 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3420
3421 // start the fast mixer
3422 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3423 pid_t tid = mFastMixer->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003424 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003425
3426#ifdef AUDIO_WATCHDOG
3427 // create and start the watchdog
3428 mAudioWatchdog = new AudioWatchdog();
3429 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3430 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3431 tid = mAudioWatchdog->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003432 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003433#endif
3434
Eric Laurent81784c32012-11-19 14:55:58 -08003435 }
3436
3437 switch (kUseFastMixer) {
3438 case FastMixer_Never:
3439 case FastMixer_Dynamic:
3440 mNormalSink = mOutputSink;
3441 break;
3442 case FastMixer_Always:
3443 mNormalSink = mPipeSink;
3444 break;
3445 case FastMixer_Static:
3446 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3447 break;
3448 }
3449}
3450
3451AudioFlinger::MixerThread::~MixerThread()
3452{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003453 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003454 FastMixerStateQueue *sq = mFastMixer->sq();
3455 FastMixerState *state = sq->begin();
3456 if (state->mCommand == FastMixerState::COLD_IDLE) {
3457 int32_t old = android_atomic_inc(&mFastMixerFutex);
3458 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003459 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003460 }
3461 }
3462 state->mCommand = FastMixerState::EXIT;
3463 sq->end();
3464 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3465 mFastMixer->join();
3466 // Though the fast mixer thread has exited, it's state queue is still valid.
3467 // We'll use that extract the final state which contains one remaining fast track
3468 // corresponding to our sub-mix.
3469 state = sq->begin();
3470 ALOG_ASSERT(state->mTrackMask == 1);
3471 FastTrack *fastTrack = &state->mFastTracks[0];
3472 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3473 delete fastTrack->mBufferProvider;
3474 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003475 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003476#ifdef AUDIO_WATCHDOG
3477 if (mAudioWatchdog != 0) {
3478 mAudioWatchdog->requestExit();
3479 mAudioWatchdog->requestExitAndWait();
3480 mAudioWatchdog.clear();
3481 }
3482#endif
3483 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003484 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003485 delete mAudioMixer;
3486}
3487
3488
3489uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3490{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003491 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003492 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3493 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3494 }
3495 return latency;
3496}
3497
3498
3499void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3500{
3501 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3502}
3503
Eric Laurentbfb1b832013-01-07 09:53:42 -08003504ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003505{
3506 // FIXME we should only do one push per cycle; confirm this is true
3507 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003508 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003509 FastMixerStateQueue *sq = mFastMixer->sq();
3510 FastMixerState *state = sq->begin();
3511 if (state->mCommand != FastMixerState::MIX_WRITE &&
3512 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3513 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07003514
3515 // FIXME workaround for first HAL write being CPU bound on some devices
3516 ATRACE_BEGIN("write");
3517 mOutput->write((char *)mSinkBuffer, 0);
3518 ATRACE_END();
3519
Eric Laurent81784c32012-11-19 14:55:58 -08003520 int32_t old = android_atomic_inc(&mFastMixerFutex);
3521 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003522 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003523 }
3524#ifdef AUDIO_WATCHDOG
3525 if (mAudioWatchdog != 0) {
3526 mAudioWatchdog->resume();
3527 }
3528#endif
3529 }
3530 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08003531#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003532 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08003533 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08003534#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003535 sq->end();
3536 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3537 if (kUseFastMixer == FastMixer_Dynamic) {
3538 mNormalSink = mPipeSink;
3539 }
3540 } else {
3541 sq->end(false /*didModify*/);
3542 }
3543 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003544 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003545}
3546
3547void AudioFlinger::MixerThread::threadLoop_standby()
3548{
3549 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003550 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003551 FastMixerStateQueue *sq = mFastMixer->sq();
3552 FastMixerState *state = sq->begin();
3553 if (!(state->mCommand & FastMixerState::IDLE)) {
3554 state->mCommand = FastMixerState::COLD_IDLE;
3555 state->mColdFutexAddr = &mFastMixerFutex;
3556 state->mColdGen++;
3557 mFastMixerFutex = 0;
3558 sq->end();
3559 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3560 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3561 if (kUseFastMixer == FastMixer_Dynamic) {
3562 mNormalSink = mOutputSink;
3563 }
3564#ifdef AUDIO_WATCHDOG
3565 if (mAudioWatchdog != 0) {
3566 mAudioWatchdog->pause();
3567 }
3568#endif
3569 } else {
3570 sq->end(false /*didModify*/);
3571 }
3572 }
3573 PlaybackThread::threadLoop_standby();
3574}
3575
Eric Laurentbfb1b832013-01-07 09:53:42 -08003576bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3577{
3578 return false;
3579}
3580
3581bool AudioFlinger::PlaybackThread::shouldStandby_l()
3582{
3583 return !mStandby;
3584}
3585
3586bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3587{
3588 Mutex::Autolock _l(mLock);
3589 return waitingAsyncCallback_l();
3590}
3591
Eric Laurent81784c32012-11-19 14:55:58 -08003592// shared by MIXER and DIRECT, overridden by DUPLICATING
3593void AudioFlinger::PlaybackThread::threadLoop_standby()
3594{
3595 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08003596 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003597 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003598 // discard any pending drain or write ack by incrementing sequence
3599 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3600 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003601 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003602 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3603 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003604 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003605 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003606}
3607
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003608void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3609{
3610 ALOGV("signal playback thread");
3611 broadcast_l();
3612}
3613
Eric Laurent81784c32012-11-19 14:55:58 -08003614void AudioFlinger::MixerThread::threadLoop_mix()
3615{
3616 // obtain the presentation timestamp of the next output buffer
3617 int64_t pts;
3618 status_t status = INVALID_OPERATION;
3619
3620 if (mNormalSink != 0) {
3621 status = mNormalSink->getNextWriteTimestamp(&pts);
3622 } else {
3623 status = mOutputSink->getNextWriteTimestamp(&pts);
3624 }
3625
3626 if (status != NO_ERROR) {
3627 pts = AudioBufferProvider::kInvalidPTS;
3628 }
3629
3630 // mix buffers...
3631 mAudioMixer->process(pts);
Andy Hung25c2dac2014-02-27 14:56:00 -08003632 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003633 // increase sleep time progressively when application underrun condition clears.
3634 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3635 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3636 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003637 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003638 sleepTimeShift--;
3639 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003640 mSleepTimeUs = 0;
3641 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08003642 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003643
Eric Laurent81784c32012-11-19 14:55:58 -08003644}
3645
3646void AudioFlinger::MixerThread::threadLoop_sleepTime()
3647{
3648 // If no tracks are ready, sleep once for the duration of an output
3649 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003650 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003651 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003652 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
3653 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
3654 mSleepTimeUs = kMinThreadSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003655 }
3656 // reduce sleep time in case of consecutive application underruns to avoid
3657 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3658 // duration we would end up writing less data than needed by the audio HAL if
3659 // the condition persists.
3660 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3661 sleepTimeShift++;
3662 }
3663 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003664 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003665 }
3666 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003667 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3668 // before effects processing or output.
3669 if (mMixerBufferValid) {
3670 memset(mMixerBuffer, 0, mMixerBufferSize);
3671 } else {
3672 memset(mSinkBuffer, 0, mSinkBufferSize);
3673 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003674 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003675 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3676 "anticipated start");
3677 }
3678 // TODO add standby time extension fct of effect tail
3679}
3680
3681// prepareTracks_l() must be called with ThreadBase::mLock held
3682AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3683 Vector< sp<Track> > *tracksToRemove)
3684{
3685
3686 mixer_state mixerStatus = MIXER_IDLE;
3687 // find out which tracks need to be processed
3688 size_t count = mActiveTracks.size();
3689 size_t mixedTracks = 0;
3690 size_t tracksWithEffect = 0;
3691 // counts only _active_ fast tracks
3692 size_t fastTracks = 0;
3693 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
3694
3695 float masterVolume = mMasterVolume;
3696 bool masterMute = mMasterMute;
3697
3698 if (masterMute) {
3699 masterVolume = 0;
3700 }
3701 // Delegate master volume control to effect in output mix effect chain if needed
3702 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3703 if (chain != 0) {
3704 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
3705 chain->setVolume_l(&v, &v);
3706 masterVolume = (float)((v + (1 << 23)) >> 24);
3707 chain.clear();
3708 }
3709
3710 // prepare a new state to push
3711 FastMixerStateQueue *sq = NULL;
3712 FastMixerState *state = NULL;
3713 bool didModify = false;
3714 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003715 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003716 sq = mFastMixer->sq();
3717 state = sq->begin();
3718 }
3719
Andy Hung69aed5f2014-02-25 17:24:40 -08003720 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08003721 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08003722
Eric Laurent81784c32012-11-19 14:55:58 -08003723 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003724 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003725 if (t == 0) {
3726 continue;
3727 }
3728
3729 // this const just means the local variable doesn't change
3730 Track* const track = t.get();
3731
3732 // process fast tracks
3733 if (track->isFastTrack()) {
3734
3735 // It's theoretically possible (though unlikely) for a fast track to be created
3736 // and then removed within the same normal mix cycle. This is not a problem, as
3737 // the track never becomes active so it's fast mixer slot is never touched.
3738 // The converse, of removing an (active) track and then creating a new track
3739 // at the identical fast mixer slot within the same normal mix cycle,
3740 // is impossible because the slot isn't marked available until the end of each cycle.
3741 int j = track->mFastIndex;
3742 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
3743 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
3744 FastTrack *fastTrack = &state->mFastTracks[j];
3745
3746 // Determine whether the track is currently in underrun condition,
3747 // and whether it had a recent underrun.
3748 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
3749 FastTrackUnderruns underruns = ftDump->mUnderruns;
3750 uint32_t recentFull = (underruns.mBitFields.mFull -
3751 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
3752 uint32_t recentPartial = (underruns.mBitFields.mPartial -
3753 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
3754 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
3755 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
3756 uint32_t recentUnderruns = recentPartial + recentEmpty;
3757 track->mObservedUnderruns = underruns;
3758 // don't count underruns that occur while stopping or pausing
3759 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07003760 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
3761 recentUnderruns > 0) {
3762 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
3763 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003764 }
3765
3766 // This is similar to the state machine for normal tracks,
3767 // with a few modifications for fast tracks.
3768 bool isActive = true;
3769 switch (track->mState) {
3770 case TrackBase::STOPPING_1:
3771 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08003772 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003773 track->mState = TrackBase::STOPPING_2;
3774 }
3775 break;
3776 case TrackBase::PAUSING:
3777 // ramp down is not yet implemented
3778 track->setPaused();
3779 break;
3780 case TrackBase::RESUMING:
3781 // ramp up is not yet implemented
3782 track->mState = TrackBase::ACTIVE;
3783 break;
3784 case TrackBase::ACTIVE:
3785 if (recentFull > 0 || recentPartial > 0) {
3786 // track has provided at least some frames recently: reset retry count
3787 track->mRetryCount = kMaxTrackRetries;
3788 }
3789 if (recentUnderruns == 0) {
3790 // no recent underruns: stay active
3791 break;
3792 }
3793 // there has recently been an underrun of some kind
3794 if (track->sharedBuffer() == 0) {
3795 // were any of the recent underruns "empty" (no frames available)?
3796 if (recentEmpty == 0) {
3797 // no, then ignore the partial underruns as they are allowed indefinitely
3798 break;
3799 }
3800 // there has recently been an "empty" underrun: decrement the retry counter
3801 if (--(track->mRetryCount) > 0) {
3802 break;
3803 }
3804 // indicate to client process that the track was disabled because of underrun;
3805 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003806 android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003807 // remove from active list, but state remains ACTIVE [confusing but true]
3808 isActive = false;
3809 break;
3810 }
3811 // fall through
3812 case TrackBase::STOPPING_2:
3813 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003814 case TrackBase::STOPPED:
3815 case TrackBase::FLUSHED: // flush() while active
3816 // Check for presentation complete if track is inactive
3817 // We have consumed all the buffers of this track.
3818 // This would be incomplete if we auto-paused on underrun
3819 {
3820 size_t audioHALFrames =
3821 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3822 size_t framesWritten = mBytesWritten / mFrameSize;
3823 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
3824 // track stays in active list until presentation is complete
3825 break;
3826 }
3827 }
3828 if (track->isStopping_2()) {
3829 track->mState = TrackBase::STOPPED;
3830 }
3831 if (track->isStopped()) {
3832 // Can't reset directly, as fast mixer is still polling this track
3833 // track->reset();
3834 // So instead mark this track as needing to be reset after push with ack
3835 resetMask |= 1 << i;
3836 }
3837 isActive = false;
3838 break;
3839 case TrackBase::IDLE:
3840 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08003841 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08003842 }
3843
3844 if (isActive) {
3845 // was it previously inactive?
3846 if (!(state->mTrackMask & (1 << j))) {
3847 ExtendedAudioBufferProvider *eabp = track;
3848 VolumeProvider *vp = track;
3849 fastTrack->mBufferProvider = eabp;
3850 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08003851 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003852 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08003853 fastTrack->mGeneration++;
3854 state->mTrackMask |= 1 << j;
3855 didModify = true;
3856 // no acknowledgement required for newly active tracks
3857 }
3858 // cache the combined master volume and stream type volume for fast mixer; this
3859 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08003860 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08003861 ++fastTracks;
3862 } else {
3863 // was it previously active?
3864 if (state->mTrackMask & (1 << j)) {
3865 fastTrack->mBufferProvider = NULL;
3866 fastTrack->mGeneration++;
3867 state->mTrackMask &= ~(1 << j);
3868 didModify = true;
3869 // If any fast tracks were removed, we must wait for acknowledgement
3870 // because we're about to decrement the last sp<> on those tracks.
3871 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3872 } else {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003873 LOG_ALWAYS_FATAL("fast track %d should have been active", j);
Eric Laurent81784c32012-11-19 14:55:58 -08003874 }
3875 tracksToRemove->add(track);
3876 // Avoids a misleading display in dumpsys
3877 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
3878 }
3879 continue;
3880 }
3881
3882 { // local variable scope to avoid goto warning
3883
3884 audio_track_cblk_t* cblk = track->cblk();
3885
3886 // The first time a track is added we wait
3887 // for all its buffers to be filled before processing it
3888 int name = track->name();
3889 // make sure that we have enough frames to mix one full buffer.
3890 // enforce this condition only once to enable draining the buffer in case the client
3891 // app does not call stop() and relies on underrun to stop:
3892 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
3893 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003894 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07003895 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07003896 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07003897
3898 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07003899 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07003900 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
3901 // add frames already consumed but not yet released by the resampler
3902 // because mAudioTrackServerProxy->framesReady() will include these frames
3903 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
3904
Eric Laurent81784c32012-11-19 14:55:58 -08003905 uint32_t minFrames = 1;
3906 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
3907 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003908 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08003909 }
Eric Laurent13e4c962013-12-20 17:36:01 -08003910
3911 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07003912 if (ATRACE_ENABLED()) {
3913 // I wish we had formatted trace names
3914 char traceName[16];
3915 strcpy(traceName, "nRdy");
3916 int name = track->name();
3917 if (AudioMixer::TRACK0 <= name &&
3918 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
3919 name -= AudioMixer::TRACK0;
3920 traceName[4] = (name / 10) + '0';
3921 traceName[5] = (name % 10) + '0';
3922 } else {
3923 traceName[4] = '?';
3924 traceName[5] = '?';
3925 }
3926 traceName[6] = '\0';
3927 ATRACE_INT(traceName, framesReady);
3928 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003929 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08003930 !track->isPaused() && !track->isTerminated())
3931 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003932 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003933
3934 mixedTracks++;
3935
Andy Hung69aed5f2014-02-25 17:24:40 -08003936 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
3937 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08003938 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08003939 if (track->mainBuffer() != mSinkBuffer &&
3940 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08003941 if (mEffectBufferEnabled) {
3942 mEffectBufferValid = true; // Later can set directly.
3943 }
Eric Laurent81784c32012-11-19 14:55:58 -08003944 chain = getEffectChain_l(track->sessionId());
3945 // Delegate volume control to effect in track effect chain if needed
3946 if (chain != 0) {
3947 tracksWithEffect++;
3948 } else {
3949 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
3950 "session %d",
3951 name, track->sessionId());
3952 }
3953 }
3954
3955
3956 int param = AudioMixer::VOLUME;
3957 if (track->mFillingUpStatus == Track::FS_FILLED) {
3958 // no ramp for the first volume setting
3959 track->mFillingUpStatus = Track::FS_ACTIVE;
3960 if (track->mState == TrackBase::RESUMING) {
3961 track->mState = TrackBase::ACTIVE;
3962 param = AudioMixer::RAMP_VOLUME;
3963 }
3964 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003965 // FIXME should not make a decision based on mServer
3966 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003967 // If the track is stopped before the first frame was mixed,
3968 // do not apply ramp
3969 param = AudioMixer::RAMP_VOLUME;
3970 }
3971
3972 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07003973 uint32_t vl, vr; // in U8.24 integer format
3974 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08003975 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07003976 vl = vr = 0;
3977 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08003978 if (track->isPausing()) {
3979 track->setPaused();
3980 }
3981 } else {
3982
3983 // read original volumes with volume control
3984 float typeVolume = mStreamTypes[track->streamType()].volume;
3985 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003986 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07003987 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07003988 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
3989 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08003990 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07003991 if (vlf > GAIN_FLOAT_UNITY) {
3992 ALOGV("Track left volume out of range: %.3g", vlf);
3993 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003994 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07003995 if (vrf > GAIN_FLOAT_UNITY) {
3996 ALOGV("Track right volume out of range: %.3g", vrf);
3997 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003998 }
3999 // now apply the master volume and stream type volume
Andy Hung6be49402014-05-30 10:42:03 -07004000 vlf *= v;
4001 vrf *= v;
Eric Laurent81784c32012-11-19 14:55:58 -08004002 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07004003 // then derive vl and vr as U8.24 versions for the effect chain
4004 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
4005 vl = (uint32_t) (scaleto8_24 * vlf);
4006 vr = (uint32_t) (scaleto8_24 * vrf);
4007 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08004008 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08004009 // send level comes from shared memory and so may be corrupt
4010 if (sendLevel > MAX_GAIN_INT) {
4011 ALOGV("Track send level out of range: %04X", sendLevel);
4012 sendLevel = MAX_GAIN_INT;
4013 }
Andy Hung6be49402014-05-30 10:42:03 -07004014 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
4015 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08004016 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004017
Eric Laurent81784c32012-11-19 14:55:58 -08004018 // Delegate volume control to effect in track effect chain if needed
4019 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
4020 // Do not ramp volume if volume is controlled by effect
4021 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08004022 // Update remaining floating point volume levels
4023 vlf = (float)vl / (1 << 24);
4024 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08004025 track->mHasVolumeController = true;
4026 } else {
4027 // force no volume ramp when volume controller was just disabled or removed
4028 // from effect chain to avoid volume spike
4029 if (track->mHasVolumeController) {
4030 param = AudioMixer::VOLUME;
4031 }
4032 track->mHasVolumeController = false;
4033 }
4034
Eric Laurent81784c32012-11-19 14:55:58 -08004035 // XXX: these things DON'T need to be done each time
4036 mAudioMixer->setBufferProvider(name, track);
4037 mAudioMixer->enable(name);
4038
Andy Hung6be49402014-05-30 10:42:03 -07004039 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
4040 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
4041 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08004042 mAudioMixer->setParameter(
4043 name,
4044 AudioMixer::TRACK,
4045 AudioMixer::FORMAT, (void *)track->format());
4046 mAudioMixer->setParameter(
4047 name,
4048 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004049 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07004050 mAudioMixer->setParameter(
4051 name,
4052 AudioMixer::TRACK,
4053 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08004054 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07004055 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004056 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08004057 if (reqSampleRate == 0) {
4058 reqSampleRate = mSampleRate;
4059 } else if (reqSampleRate > maxSampleRate) {
4060 reqSampleRate = maxSampleRate;
4061 }
Eric Laurent81784c32012-11-19 14:55:58 -08004062 mAudioMixer->setParameter(
4063 name,
4064 AudioMixer::RESAMPLE,
4065 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004066 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004067
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004068 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004069 mAudioMixer->setParameter(
4070 name,
4071 AudioMixer::TIMESTRETCH,
4072 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004073 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004074
Andy Hung69aed5f2014-02-25 17:24:40 -08004075 /*
4076 * Select the appropriate output buffer for the track.
4077 *
Andy Hung98ef9782014-03-04 14:46:50 -08004078 * Tracks with effects go into their own effects chain buffer
4079 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08004080 *
4081 * Other tracks can use mMixerBuffer for higher precision
4082 * channel accumulation. If this buffer is enabled
4083 * (mMixerBufferEnabled true), then selected tracks will accumulate
4084 * into it.
4085 *
4086 */
4087 if (mMixerBufferEnabled
4088 && (track->mainBuffer() == mSinkBuffer
4089 || track->mainBuffer() == mMixerBuffer)) {
4090 mAudioMixer->setParameter(
4091 name,
4092 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004093 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08004094 mAudioMixer->setParameter(
4095 name,
4096 AudioMixer::TRACK,
4097 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
4098 // TODO: override track->mainBuffer()?
4099 mMixerBufferValid = true;
4100 } else {
4101 mAudioMixer->setParameter(
4102 name,
4103 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004104 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08004105 mAudioMixer->setParameter(
4106 name,
4107 AudioMixer::TRACK,
4108 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
4109 }
Eric Laurent81784c32012-11-19 14:55:58 -08004110 mAudioMixer->setParameter(
4111 name,
4112 AudioMixer::TRACK,
4113 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
4114
4115 // reset retry count
4116 track->mRetryCount = kMaxTrackRetries;
4117
4118 // If one track is ready, set the mixer ready if:
4119 // - the mixer was not ready during previous round OR
4120 // - no other track is not ready
4121 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
4122 mixerStatus != MIXER_TRACKS_ENABLED) {
4123 mixerStatus = MIXER_TRACKS_READY;
4124 }
4125 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004126 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hung08fb1742015-05-31 23:22:10 -07004127 ALOGV("track(%p) underrun, framesReady(%zu) < framesDesired(%zd)",
4128 track, framesReady, desiredFrames);
Glenn Kasten82aaf942013-07-17 16:05:07 -07004129 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004130 }
Eric Laurent81784c32012-11-19 14:55:58 -08004131 // clear effect chain input buffer if an active track underruns to avoid sending
4132 // previous audio buffer again to effects
4133 chain = getEffectChain_l(track->sessionId());
4134 if (chain != 0) {
4135 chain->clearInputBuffer();
4136 }
4137
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004138 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004139 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
4140 track->isStopped() || track->isPaused()) {
4141 // We have consumed all the buffers of this track.
4142 // Remove it from the list of active tracks.
4143 // TODO: use actual buffer filling status instead of latency when available from
4144 // audio HAL
4145 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
4146 size_t framesWritten = mBytesWritten / mFrameSize;
4147 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
4148 if (track->isStopped()) {
4149 track->reset();
4150 }
4151 tracksToRemove->add(track);
4152 }
4153 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08004154 // No buffers for this track. Give it a few chances to
4155 // fill a buffer, then remove it from active list.
4156 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004157 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004158 tracksToRemove->add(track);
4159 // indicate to client process that the track was disabled because of underrun;
4160 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07004161 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08004162 // If one track is not ready, mark the mixer also not ready if:
4163 // - the mixer was ready during previous round OR
4164 // - no other track is ready
4165 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
4166 mixerStatus != MIXER_TRACKS_READY) {
4167 mixerStatus = MIXER_TRACKS_ENABLED;
4168 }
4169 }
4170 mAudioMixer->disable(name);
4171 }
4172
4173 } // local variable scope to avoid goto warning
4174track_is_ready: ;
4175
4176 }
4177
4178 // Push the new FastMixer state if necessary
4179 bool pauseAudioWatchdog = false;
4180 if (didModify) {
4181 state->mFastTracksGen++;
4182 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4183 if (kUseFastMixer == FastMixer_Dynamic &&
4184 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4185 state->mCommand = FastMixerState::COLD_IDLE;
4186 state->mColdFutexAddr = &mFastMixerFutex;
4187 state->mColdGen++;
4188 mFastMixerFutex = 0;
4189 if (kUseFastMixer == FastMixer_Dynamic) {
4190 mNormalSink = mOutputSink;
4191 }
4192 // If we go into cold idle, need to wait for acknowledgement
4193 // so that fast mixer stops doing I/O.
4194 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4195 pauseAudioWatchdog = true;
4196 }
Eric Laurent81784c32012-11-19 14:55:58 -08004197 }
4198 if (sq != NULL) {
4199 sq->end(didModify);
4200 sq->push(block);
4201 }
4202#ifdef AUDIO_WATCHDOG
4203 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4204 mAudioWatchdog->pause();
4205 }
4206#endif
4207
4208 // Now perform the deferred reset on fast tracks that have stopped
4209 while (resetMask != 0) {
4210 size_t i = __builtin_ctz(resetMask);
4211 ALOG_ASSERT(i < count);
4212 resetMask &= ~(1 << i);
4213 sp<Track> t = mActiveTracks[i].promote();
4214 if (t == 0) {
4215 continue;
4216 }
4217 Track* track = t.get();
4218 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
4219 track->reset();
4220 }
4221
4222 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004223 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004224
Eric Laurent97d547d2014-09-02 14:45:53 -07004225 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
4226 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07004227 }
4228
4229 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07004230 // as long as there are effects we should clear the effects buffer, to avoid
4231 // passing a non-clean buffer to the effect chain
4232 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07004233 }
Andy Hung69aed5f2014-02-25 17:24:40 -08004234 // sink or mix buffer must be cleared if all tracks are connected to an
4235 // effect chain as in this case the mixer will not write to the sink or mix buffer
4236 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08004237 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4238 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08004239 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08004240 if (mMixerBufferValid) {
4241 memset(mMixerBuffer, 0, mMixerBufferSize);
4242 // TODO: In testing, mSinkBuffer below need not be cleared because
4243 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
4244 // after mixing.
4245 //
4246 // To enforce this guarantee:
4247 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4248 // (mixedTracks == 0 && fastTracks > 0))
4249 // must imply MIXER_TRACKS_READY.
4250 // Later, we may clear buffers regardless, and skip much of this logic.
4251 }
Andy Hung98ef9782014-03-04 14:46:50 -08004252 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07004253 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004254 }
4255
4256 // if any fast tracks, then status is ready
4257 mMixerStatusIgnoringFastTracks = mixerStatus;
4258 if (fastTracks > 0) {
4259 mixerStatus = MIXER_TRACKS_READY;
4260 }
4261 return mixerStatus;
4262}
4263
4264// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07004265int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
4266 audio_format_t format, int sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08004267{
Andy Hunge8a1ced2014-05-09 15:02:21 -07004268 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08004269}
4270
4271// deleteTrackName_l() must be called with ThreadBase::mLock held
4272void AudioFlinger::MixerThread::deleteTrackName_l(int name)
4273{
4274 ALOGV("remove track (%d) and delete from mixer", name);
4275 mAudioMixer->deleteTrackName(name);
4276}
4277
Eric Laurent10351942014-05-08 18:49:52 -07004278// checkForNewParameter_l() must be called with ThreadBase::mLock held
4279bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
4280 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004281{
Eric Laurent81784c32012-11-19 14:55:58 -08004282 bool reconfig = false;
Eric Laurent113efbb2016-01-08 17:16:42 -08004283 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004284
Eric Laurent10351942014-05-08 18:49:52 -07004285 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004286
Eric Laurent10351942014-05-08 18:49:52 -07004287 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
4288 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004289 if (mFastMixer != 0) {
Eric Laurent10351942014-05-08 18:49:52 -07004290 FastMixerStateQueue *sq = mFastMixer->sq();
4291 FastMixerState *state = sq->begin();
4292 if (!(state->mCommand & FastMixerState::IDLE)) {
4293 previousCommand = state->mCommand;
4294 state->mCommand = FastMixerState::HOT_IDLE;
4295 sq->end();
4296 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
4297 } else {
4298 sq->end(false /*didModify*/);
Eric Laurent81784c32012-11-19 14:55:58 -08004299 }
Eric Laurent10351942014-05-08 18:49:52 -07004300 }
Eric Laurent81784c32012-11-19 14:55:58 -08004301
Eric Laurent10351942014-05-08 18:49:52 -07004302 AudioParameter param = AudioParameter(keyValuePair);
4303 int value;
4304 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4305 reconfig = true;
4306 }
4307 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004308 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004309 status = BAD_VALUE;
4310 } else {
4311 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08004312 reconfig = true;
4313 }
Eric Laurent10351942014-05-08 18:49:52 -07004314 }
4315 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004316 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004317 status = BAD_VALUE;
4318 } else {
4319 // no need to save value, since it's constant
4320 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004321 }
Eric Laurent10351942014-05-08 18:49:52 -07004322 }
4323 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4324 // do not accept frame count changes if tracks are open as the track buffer
4325 // size depends on frame count and correct behavior would not be guaranteed
4326 // if frame count is changed after track creation
4327 if (!mTracks.isEmpty()) {
4328 status = INVALID_OPERATION;
4329 } else {
4330 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004331 }
Eric Laurent10351942014-05-08 18:49:52 -07004332 }
4333 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004334#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07004335 // when changing the audio output device, call addBatteryData to notify
4336 // the change
4337 if (mOutDevice != value) {
4338 uint32_t params = 0;
4339 // check whether speaker is on
4340 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
4341 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08004342 }
Eric Laurent10351942014-05-08 18:49:52 -07004343
4344 audio_devices_t deviceWithoutSpeaker
4345 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
4346 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07004347 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07004348 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4349 }
4350
4351 if (params != 0) {
4352 addBatteryData(params);
4353 }
4354 }
Eric Laurent81784c32012-11-19 14:55:58 -08004355#endif
4356
Eric Laurent10351942014-05-08 18:49:52 -07004357 // forward device change to effects that have requested to be
4358 // aware of attached audio device.
4359 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent113efbb2016-01-08 17:16:42 -08004360 a2dpDeviceChanged =
4361 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07004362 mOutDevice = value;
4363 for (size_t i = 0; i < mEffectChains.size(); i++) {
4364 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08004365 }
4366 }
Eric Laurent10351942014-05-08 18:49:52 -07004367 }
Eric Laurent81784c32012-11-19 14:55:58 -08004368
Eric Laurent10351942014-05-08 18:49:52 -07004369 if (status == NO_ERROR) {
4370 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4371 keyValuePair.string());
4372 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004373 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004374 mStandby = true;
4375 mBytesWritten = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004376 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Eric Laurent10351942014-05-08 18:49:52 -07004377 keyValuePair.string());
Eric Laurent81784c32012-11-19 14:55:58 -08004378 }
Eric Laurent10351942014-05-08 18:49:52 -07004379 if (status == NO_ERROR && reconfig) {
4380 readOutputParameters_l();
4381 delete mAudioMixer;
4382 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4383 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07004384 int name = getTrackName_l(mTracks[i]->mChannelMask,
4385 mTracks[i]->mFormat, mTracks[i]->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07004386 if (name < 0) {
4387 break;
4388 }
4389 mTracks[i]->mName = name;
4390 }
Eric Laurent73e26b62015-04-27 16:55:58 -07004391 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004392 }
Eric Laurent81784c32012-11-19 14:55:58 -08004393 }
4394
4395 if (!(previousCommand & FastMixerState::IDLE)) {
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004396 ALOG_ASSERT(mFastMixer != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08004397 FastMixerStateQueue *sq = mFastMixer->sq();
4398 FastMixerState *state = sq->begin();
4399 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
4400 state->mCommand = previousCommand;
4401 sq->end();
4402 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4403 }
4404
Eric Laurent113efbb2016-01-08 17:16:42 -08004405 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08004406}
4407
4408
4409void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
4410{
4411 const size_t SIZE = 256;
4412 char buffer[SIZE];
4413 String8 result;
4414
4415 PlaybackThread::dumpInternals(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07004416 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Elliott Hughes87cebad2014-05-22 10:14:43 -07004417 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Eric Laurent81784c32012-11-19 14:55:58 -08004418
4419 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten4182c4e2013-07-15 14:45:07 -07004420 const FastMixerDumpState copy(mFastMixerDumpState);
Eric Laurent81784c32012-11-19 14:55:58 -08004421 copy.dump(fd);
4422
4423#ifdef STATE_QUEUE_DUMP
4424 // Similar for state queue
4425 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4426 observerCopy.dump(fd);
4427 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4428 mutatorCopy.dump(fd);
4429#endif
4430
Glenn Kasten46909e72013-02-26 09:20:22 -08004431#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08004432 // Write the tee output to a .wav file
4433 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08004434#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004435
4436#ifdef AUDIO_WATCHDOG
4437 if (mAudioWatchdog != 0) {
4438 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4439 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4440 wdCopy.dump(fd);
4441 }
4442#endif
4443}
4444
4445uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4446{
4447 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4448}
4449
4450uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4451{
4452 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4453}
4454
4455void AudioFlinger::MixerThread::cacheParameters_l()
4456{
4457 PlaybackThread::cacheParameters_l();
4458
4459 // FIXME: Relaxed timing because of a certain device that can't meet latency
4460 // Should be reduced to 2x after the vendor fixes the driver issue
4461 // increase threshold again due to low power audio mode. The way this warning
4462 // threshold is calculated and its usefulness should be reconsidered anyway.
4463 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4464}
4465
4466// ----------------------------------------------------------------------------
4467
4468AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07004469 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device, bool systemReady)
4470 : PlaybackThread(audioFlinger, output, id, device, DIRECT, systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08004471 // mLeftVolFloat, mRightVolFloat
4472{
4473}
4474
Eric Laurentbfb1b832013-01-07 09:53:42 -08004475AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4476 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07004477 ThreadBase::type_t type, bool systemReady)
4478 : PlaybackThread(audioFlinger, output, id, device, type, systemReady)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004479 // mLeftVolFloat, mRightVolFloat
4480{
4481}
4482
Eric Laurent81784c32012-11-19 14:55:58 -08004483AudioFlinger::DirectOutputThread::~DirectOutputThread()
4484{
4485}
4486
Eric Laurentbfb1b832013-01-07 09:53:42 -08004487void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
4488{
4489 audio_track_cblk_t* cblk = track->cblk();
4490 float left, right;
4491
4492 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4493 left = right = 0;
4494 } else {
4495 float typeVolume = mStreamTypes[track->streamType()].volume;
4496 float v = mMasterVolume * typeVolume;
4497 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004498 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4499 left = float_from_gain(gain_minifloat_unpack_left(vlr));
4500 if (left > GAIN_FLOAT_UNITY) {
4501 left = GAIN_FLOAT_UNITY;
4502 }
4503 left *= v;
4504 right = float_from_gain(gain_minifloat_unpack_right(vlr));
4505 if (right > GAIN_FLOAT_UNITY) {
4506 right = GAIN_FLOAT_UNITY;
4507 }
4508 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004509 }
4510
4511 if (lastTrack) {
4512 if (left != mLeftVolFloat || right != mRightVolFloat) {
4513 mLeftVolFloat = left;
4514 mRightVolFloat = right;
4515
4516 // Convert volumes from float to 8.24
4517 uint32_t vl = (uint32_t)(left * (1 << 24));
4518 uint32_t vr = (uint32_t)(right * (1 << 24));
4519
4520 // Delegate volume control to effect in track effect chain if needed
4521 // only one effect chain can be present on DirectOutputThread, so if
4522 // there is one, the track is connected to it
4523 if (!mEffectChains.isEmpty()) {
4524 mEffectChains[0]->setVolume_l(&vl, &vr);
4525 left = (float)vl / (1 << 24);
4526 right = (float)vr / (1 << 24);
4527 }
4528 if (mOutput->stream->set_volume) {
4529 mOutput->stream->set_volume(mOutput->stream, left, right);
4530 }
4531 }
4532 }
4533}
4534
Phil Burk43b4dcc2015-06-09 16:53:44 -07004535void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
4536{
4537 sp<Track> previousTrack = mPreviousTrack.promote();
4538 sp<Track> latestTrack = mLatestActiveTrack.promote();
4539
Eric Laurent0f0631e2015-07-06 18:01:25 -07004540 if (previousTrack != 0 && latestTrack != 0) {
4541 if (mType == DIRECT) {
4542 if (previousTrack.get() != latestTrack.get()) {
4543 mFlushPending = true;
4544 }
4545 } else /* mType == OFFLOAD */ {
4546 if (previousTrack->sessionId() != latestTrack->sessionId()) {
4547 mFlushPending = true;
4548 }
4549 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004550 }
4551 PlaybackThread::onAddNewTrack_l();
4552}
Eric Laurentbfb1b832013-01-07 09:53:42 -08004553
Eric Laurent81784c32012-11-19 14:55:58 -08004554AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4555 Vector< sp<Track> > *tracksToRemove
4556)
4557{
Eric Laurentd595b7c2013-04-03 17:27:56 -07004558 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08004559 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004560 bool doHwPause = false;
4561 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004562
4563 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07004564 for (size_t i = 0; i < count; i++) {
4565 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08004566 // The track died recently
4567 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004568 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08004569 }
4570
Phil Burk43b4dcc2015-06-09 16:53:44 -07004571 if (t->isInvalid()) {
4572 ALOGW("An invalidated track shouldn't be in active list");
4573 tracksToRemove->add(t);
4574 continue;
4575 }
4576
Eric Laurent81784c32012-11-19 14:55:58 -08004577 Track* const track = t.get();
4578 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07004579 // Only consider last track started for volume and mixer state control.
4580 // In theory an older track could underrun and restart after the new one starts
4581 // but as we only care about the transition phase between two tracks on a
4582 // direct output, it is not a problem to ignore the underrun case.
4583 sp<Track> l = mLatestActiveTrack.promote();
4584 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08004585
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004586 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004587 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004588 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004589 doHwPause = true;
4590 mHwPaused = true;
4591 }
4592 tracksToRemove->add(track);
4593 } else if (track->isFlushPending()) {
4594 track->flushAck();
4595 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004596 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004597 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004598 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004599 track->resumeAck();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004600 if (last && mHwPaused) {
4601 doHwResume = true;
4602 mHwPaused = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004603 }
4604 }
4605
Eric Laurent81784c32012-11-19 14:55:58 -08004606 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08004607 // for all its buffers to be filled before processing it.
4608 // Allow draining the buffer in case the client
4609 // app does not call stop() and relies on underrun to stop:
4610 // hence the test on (track->mRetryCount > 1).
4611 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07004612 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08004613 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08004614 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkca5e6142015-07-14 09:42:29 -07004615 && (track->mRetryCount > 1) && audio_is_linear_pcm(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004616 minFrames = mNormalFrameCount;
4617 } else {
4618 minFrames = 1;
4619 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004620
Eric Laurentab5cdba2014-06-09 17:22:27 -07004621 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4622 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08004623 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004624 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08004625
4626 if (track->mFillingUpStatus == Track::FS_FILLED) {
4627 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004628 // make sure processVolume_l() will apply new volume even if 0
4629 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004630 if (!mHwSupportsPause) {
4631 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08004632 }
4633 }
4634
4635 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004636 processVolume_l(track, last);
4637 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004638 sp<Track> previousTrack = mPreviousTrack.promote();
4639 if (previousTrack != 0) {
4640 if (track != previousTrack.get()) {
4641 // Flush any data still being written from last track
4642 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07004643 // Invalidate previous track to force a seek when resuming.
4644 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004645 }
4646 }
4647 mPreviousTrack = track;
4648
Eric Laurentd595b7c2013-04-03 17:27:56 -07004649 // reset retry count
4650 track->mRetryCount = kMaxTrackRetriesDirect;
4651 mActiveTrack = t;
4652 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07004653 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004654 doHwResume = true;
4655 mHwPaused = false;
4656 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004657 }
Eric Laurent81784c32012-11-19 14:55:58 -08004658 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004659 // clear effect chain input buffer if the last active track started underruns
4660 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07004661 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004662 mEffectChains[0]->clearInputBuffer();
4663 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004664 if (track->isStopping_1()) {
4665 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07004666 if (last && mHwPaused) {
4667 doHwResume = true;
4668 mHwPaused = false;
4669 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004670 }
4671 if ((track->sharedBuffer() != 0) || track->isStopped() ||
4672 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004673 // We have consumed all the buffers of this track.
4674 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07004675 size_t audioHALFrames;
4676 if (audio_is_linear_pcm(mFormat)) {
4677 audioHALFrames = (latency_l() * mSampleRate) / 1000;
4678 } else {
4679 audioHALFrames = 0;
4680 }
4681
Eric Laurent81784c32012-11-19 14:55:58 -08004682 size_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07004683 if (mStandby || !last ||
4684 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004685 if (track->isStopping_2()) {
4686 track->mState = TrackBase::STOPPED;
4687 }
Eric Laurent81784c32012-11-19 14:55:58 -08004688 if (track->isStopped()) {
4689 track->reset();
4690 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004691 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08004692 }
4693 } else {
4694 // No buffers for this track. Give it a few chances to
4695 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07004696 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08004697 if (--(track->mRetryCount) <= 0) {
4698 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07004699 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004700 // indicate to client process that the track was disabled because of underrun;
4701 // it will then automatically call start() when data is available
4702 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004703 } else if (last) {
Phil Burkca5e6142015-07-14 09:42:29 -07004704 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
4705 "minFrames = %u, mFormat = %#x",
4706 track->framesReady(), minFrames, mFormat);
Eric Laurent81784c32012-11-19 14:55:58 -08004707 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07004708 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004709 doHwPause = true;
4710 mHwPaused = true;
4711 }
Eric Laurent81784c32012-11-19 14:55:58 -08004712 }
4713 }
4714 }
4715 }
4716
Eric Laurentd1f69b02014-12-15 14:33:13 -08004717 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07004718 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004719 for (size_t i = 0; i < mTracks.size(); i++) {
4720 if (mTracks[i]->isFlushPending()) {
4721 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004722 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004723 }
4724 }
4725 }
4726
4727 // make sure the pause/flush/resume sequence is executed in the right order.
4728 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4729 // before flush and then resume HW. This can happen in case of pause/flush/resume
4730 // if resume is received before pause is executed.
4731 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07004732 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004733 mOutput->stream->pause(mOutput->stream);
4734 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004735 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004736 flushHw_l();
4737 }
4738 if (mHwSupportsPause && !mStandby && doHwResume) {
4739 mOutput->stream->resume(mOutput->stream);
4740 }
Eric Laurent81784c32012-11-19 14:55:58 -08004741 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004742 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004743
4744 return mixerStatus;
4745}
4746
4747void AudioFlinger::DirectOutputThread::threadLoop_mix()
4748{
Eric Laurent81784c32012-11-19 14:55:58 -08004749 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08004750 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004751 // output audio to hardware
4752 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07004753 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004754 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08004755 status_t status = mActiveTrack->getNextBuffer(&buffer);
4756 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08004757 memset(curBuf, 0, frameCount * mFrameSize);
4758 break;
4759 }
4760 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
4761 frameCount -= buffer.frameCount;
4762 curBuf += buffer.frameCount * mFrameSize;
4763 mActiveTrack->releaseBuffer(&buffer);
4764 }
Andy Hung2098f272014-02-27 14:00:06 -08004765 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004766 mSleepTimeUs = 0;
4767 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08004768 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004769}
4770
4771void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
4772{
Eric Laurentd1f69b02014-12-15 14:33:13 -08004773 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004774 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004775 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004776 return;
4777 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004778 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004779 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004780 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004781 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004782 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004783 }
4784 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08004785 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004786 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004787 }
4788}
4789
Eric Laurentd1f69b02014-12-15 14:33:13 -08004790void AudioFlinger::DirectOutputThread::threadLoop_exit()
4791{
4792 {
4793 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08004794 for (size_t i = 0; i < mTracks.size(); i++) {
4795 if (mTracks[i]->isFlushPending()) {
4796 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004797 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004798 }
4799 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004800 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004801 flushHw_l();
4802 }
4803 }
4804 PlaybackThread::threadLoop_exit();
4805}
4806
4807// must be called with thread mutex locked
4808bool AudioFlinger::DirectOutputThread::shouldStandby_l()
4809{
4810 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07004811 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004812
4813 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4814 // after a timeout and we will enter standby then.
4815 if (mTracks.size() > 0) {
4816 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07004817 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
4818 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004819 }
4820
Eric Laurent5cff4032015-05-26 13:49:58 -07004821 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08004822}
4823
Eric Laurent81784c32012-11-19 14:55:58 -08004824// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004825int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Andy Hunge8a1ced2014-05-09 15:02:21 -07004826 audio_format_t format __unused, int sessionId __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004827{
4828 return 0;
4829}
4830
4831// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004832void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004833{
4834}
4835
Eric Laurent10351942014-05-08 18:49:52 -07004836// checkForNewParameter_l() must be called with ThreadBase::mLock held
4837bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
4838 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004839{
4840 bool reconfig = false;
Eric Laurent113efbb2016-01-08 17:16:42 -08004841 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004842
Eric Laurent10351942014-05-08 18:49:52 -07004843 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004844
Eric Laurent10351942014-05-08 18:49:52 -07004845 AudioParameter param = AudioParameter(keyValuePair);
4846 int value;
4847 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4848 // forward device change to effects that have requested to be
4849 // aware of attached audio device.
4850 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent113efbb2016-01-08 17:16:42 -08004851 a2dpDeviceChanged =
4852 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07004853 mOutDevice = value;
4854 for (size_t i = 0; i < mEffectChains.size(); i++) {
4855 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07004856 }
4857 }
Eric Laurent81784c32012-11-19 14:55:58 -08004858 }
Eric Laurent10351942014-05-08 18:49:52 -07004859 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4860 // do not accept frame count changes if tracks are open as the track buffer
4861 // size depends on frame count and correct behavior would not be garantied
4862 // if frame count is changed after track creation
4863 if (!mTracks.isEmpty()) {
4864 status = INVALID_OPERATION;
4865 } else {
4866 reconfig = true;
4867 }
4868 }
4869 if (status == NO_ERROR) {
4870 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4871 keyValuePair.string());
4872 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004873 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004874 mStandby = true;
4875 mBytesWritten = 0;
4876 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4877 keyValuePair.string());
4878 }
4879 if (status == NO_ERROR && reconfig) {
4880 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07004881 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004882 }
4883 }
4884
Eric Laurent113efbb2016-01-08 17:16:42 -08004885 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08004886}
4887
4888uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
4889{
4890 uint32_t time;
4891 if (audio_is_linear_pcm(mFormat)) {
4892 time = PlaybackThread::activeSleepTimeUs();
4893 } else {
4894 time = 10000;
4895 }
4896 return time;
4897}
4898
4899uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
4900{
4901 uint32_t time;
4902 if (audio_is_linear_pcm(mFormat)) {
4903 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
4904 } else {
4905 time = 10000;
4906 }
4907 return time;
4908}
4909
4910uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
4911{
4912 uint32_t time;
4913 if (audio_is_linear_pcm(mFormat)) {
4914 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
4915 } else {
4916 time = 10000;
4917 }
4918 return time;
4919}
4920
4921void AudioFlinger::DirectOutputThread::cacheParameters_l()
4922{
4923 PlaybackThread::cacheParameters_l();
4924
4925 // use shorter standby delay as on normal output to release
4926 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07004927 // no delay on outputs with HW A/V sync
4928 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004929 mStandbyDelayNs = 0;
Eric Laurent5cff4032015-05-26 13:49:58 -07004930 } else if ((mType == OFFLOAD) && !audio_is_linear_pcm(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004931 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07004932 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004933 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07004934 }
Eric Laurent81784c32012-11-19 14:55:58 -08004935}
4936
Eric Laurente659ef42014-09-29 13:06:46 -07004937void AudioFlinger::DirectOutputThread::flushHw_l()
4938{
Phil Burk062e67a2015-02-11 13:40:50 -08004939 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08004940 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07004941 mFlushPending = false;
Eric Laurente659ef42014-09-29 13:06:46 -07004942}
4943
Eric Laurent81784c32012-11-19 14:55:58 -08004944// ----------------------------------------------------------------------------
4945
Eric Laurentbfb1b832013-01-07 09:53:42 -08004946AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07004947 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004948 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07004949 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07004950 mWriteAckSequence(0),
4951 mDrainSequence(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004952{
4953}
4954
4955AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
4956{
4957}
4958
4959void AudioFlinger::AsyncCallbackThread::onFirstRef()
4960{
4961 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
4962}
4963
4964bool AudioFlinger::AsyncCallbackThread::threadLoop()
4965{
4966 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004967 uint32_t writeAckSequence;
4968 uint32_t drainSequence;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004969
4970 {
4971 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08004972 while (!((mWriteAckSequence & 1) ||
4973 (mDrainSequence & 1) ||
4974 exitPending())) {
4975 mWaitWorkCV.wait(mLock);
4976 }
4977
Eric Laurentbfb1b832013-01-07 09:53:42 -08004978 if (exitPending()) {
4979 break;
4980 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004981 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
4982 mWriteAckSequence, mDrainSequence);
4983 writeAckSequence = mWriteAckSequence;
4984 mWriteAckSequence &= ~1;
4985 drainSequence = mDrainSequence;
4986 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004987 }
4988 {
Eric Laurent4de95592013-09-26 15:28:21 -07004989 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
4990 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004991 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004992 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004993 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004994 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004995 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004996 }
4997 }
4998 }
4999 }
5000 return false;
5001}
5002
5003void AudioFlinger::AsyncCallbackThread::exit()
5004{
5005 ALOGV("AsyncCallbackThread::exit");
5006 Mutex::Autolock _l(mLock);
5007 requestExit();
5008 mWaitWorkCV.broadcast();
5009}
5010
Eric Laurent3b4529e2013-09-05 18:09:19 -07005011void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005012{
5013 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005014 // bit 0 is cleared
5015 mWriteAckSequence = sequence << 1;
5016}
5017
5018void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
5019{
5020 Mutex::Autolock _l(mLock);
5021 // ignore unexpected callbacks
5022 if (mWriteAckSequence & 2) {
5023 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005024 mWaitWorkCV.signal();
5025 }
5026}
5027
Eric Laurent3b4529e2013-09-05 18:09:19 -07005028void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005029{
5030 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005031 // bit 0 is cleared
5032 mDrainSequence = sequence << 1;
5033}
5034
5035void AudioFlinger::AsyncCallbackThread::resetDraining()
5036{
5037 Mutex::Autolock _l(mLock);
5038 // ignore unexpected callbacks
5039 if (mDrainSequence & 2) {
5040 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005041 mWaitWorkCV.signal();
5042 }
5043}
5044
5045
5046// ----------------------------------------------------------------------------
5047AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07005048 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady)
5049 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady),
Eric Laurentd7e59222013-11-15 12:02:28 -08005050 mPausedBytesRemaining(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005051{
Eric Laurentfd477972013-10-25 18:10:40 -07005052 //FIXME: mStandby should be set to true by ThreadBase constructor
5053 mStandby = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005054}
5055
Eric Laurentbfb1b832013-01-07 09:53:42 -08005056void AudioFlinger::OffloadThread::threadLoop_exit()
5057{
5058 if (mFlushPending || mHwPaused) {
5059 // If a flush is pending or track was paused, just discard buffered data
5060 flushHw_l();
5061 } else {
5062 mMixerStatus = MIXER_DRAIN_ALL;
5063 threadLoop_drain();
5064 }
Uday Gupta56604aa2014-05-13 11:19:17 -07005065 if (mUseAsyncWrite) {
5066 ALOG_ASSERT(mCallbackThread != 0);
5067 mCallbackThread->exit();
5068 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005069 PlaybackThread::threadLoop_exit();
5070}
5071
5072AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
5073 Vector< sp<Track> > *tracksToRemove
5074)
5075{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005076 size_t count = mActiveTracks.size();
5077
5078 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07005079 bool doHwPause = false;
5080 bool doHwResume = false;
5081
Eric Laurentede6c3b2013-09-19 14:37:46 -07005082 ALOGV("OffloadThread::prepareTracks_l active tracks %d", count);
5083
Eric Laurentbfb1b832013-01-07 09:53:42 -08005084 // find out which tracks need to be processed
5085 for (size_t i = 0; i < count; i++) {
5086 sp<Track> t = mActiveTracks[i].promote();
5087 // The track died recently
5088 if (t == 0) {
5089 continue;
5090 }
5091 Track* const track = t.get();
5092 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07005093 // Only consider last track started for volume and mixer state control.
5094 // In theory an older track could underrun and restart after the new one starts
5095 // but as we only care about the transition phase between two tracks on a
5096 // direct output, it is not a problem to ignore the underrun case.
5097 sp<Track> l = mLatestActiveTrack.promote();
5098 bool last = l.get() == track;
5099
Haynes Mathew George7844f672014-01-15 12:32:55 -08005100 if (track->isInvalid()) {
5101 ALOGW("An invalidated track shouldn't be in active list");
5102 tracksToRemove->add(track);
5103 continue;
5104 }
5105
5106 if (track->mState == TrackBase::IDLE) {
5107 ALOGW("An idle track shouldn't be in active list");
5108 continue;
5109 }
5110
Eric Laurentbfb1b832013-01-07 09:53:42 -08005111 if (track->isPausing()) {
5112 track->setPaused();
5113 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07005114 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07005115 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005116 mHwPaused = true;
5117 }
5118 // If we were part way through writing the mixbuffer to
5119 // the HAL we must save this until we resume
5120 // BUG - this will be wrong if a different track is made active,
5121 // in that case we want to discard the pending data in the
5122 // mixbuffer and tell the client to present it again when the
5123 // track is resumed
5124 mPausedWriteLength = mCurrentWriteLength;
5125 mPausedBytesRemaining = mBytesRemaining;
5126 mBytesRemaining = 0; // stop writing
5127 }
5128 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08005129 } else if (track->isFlushPending()) {
5130 track->flushAck();
5131 if (last) {
5132 mFlushPending = true;
5133 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005134 } else if (track->isResumePending()){
5135 track->resumeAck();
5136 if (last) {
5137 if (mPausedBytesRemaining) {
5138 // Need to continue write that was interrupted
5139 mCurrentWriteLength = mPausedWriteLength;
5140 mBytesRemaining = mPausedBytesRemaining;
5141 mPausedBytesRemaining = 0;
5142 }
5143 if (mHwPaused) {
5144 doHwResume = true;
5145 mHwPaused = false;
5146 // threadLoop_mix() will handle the case that we need to
5147 // resume an interrupted write
5148 }
5149 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005150 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005151
5152 // Do not handle new data in this iteration even if track->framesReady()
5153 mixerStatus = MIXER_TRACKS_ENABLED;
5154 }
5155 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07005156 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005157 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005158 if (track->mFillingUpStatus == Track::FS_FILLED) {
5159 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07005160 // make sure processVolume_l() will apply new volume even if 0
5161 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005162 }
5163
5164 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08005165 sp<Track> previousTrack = mPreviousTrack.promote();
5166 if (previousTrack != 0) {
5167 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08005168 // Flush any data still being written from last track
5169 mBytesRemaining = 0;
5170 if (mPausedBytesRemaining) {
5171 // Last track was paused so we also need to flush saved
5172 // mixbuffer state and invalidate track so that it will
5173 // re-submit that unwritten data when it is next resumed
5174 mPausedBytesRemaining = 0;
5175 // Invalidate is a bit drastic - would be more efficient
5176 // to have a flag to tell client that some of the
5177 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08005178 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005179 }
5180 // flush data already sent to the DSP if changing audio session as audio
5181 // comes from a different source. Also invalidate previous track to force a
5182 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08005183 if (previousTrack->sessionId() != track->sessionId()) {
5184 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005185 }
5186 }
5187 }
5188 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005189 // reset retry count
5190 track->mRetryCount = kMaxTrackRetriesOffload;
5191 mActiveTrack = t;
5192 mixerStatus = MIXER_TRACKS_READY;
5193 }
5194 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005195 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005196 if (track->isStopping_1()) {
5197 // Hardware buffer can hold a large amount of audio so we must
5198 // wait for all current track's data to drain before we say
5199 // that the track is stopped.
5200 if (mBytesRemaining == 0) {
5201 // Only start draining when all data in mixbuffer
5202 // has been written
5203 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
5204 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005205 // do not drain if no data was ever sent to HAL (mStandby == true)
5206 if (last && !mStandby) {
Eric Laurent1b9f9b12013-11-12 19:10:17 -08005207 // do not modify drain sequence if we are already draining. This happens
5208 // when resuming from pause after drain.
5209 if ((mDrainSequence & 1) == 0) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005210 mSleepTimeUs = 0;
5211 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent1b9f9b12013-11-12 19:10:17 -08005212 mixerStatus = MIXER_DRAIN_TRACK;
5213 mDrainSequence += 2;
5214 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005215 if (mHwPaused) {
5216 // It is possible to move from PAUSED to STOPPING_1 without
5217 // a resume so we must ensure hardware is running
Eric Laurent1b9f9b12013-11-12 19:10:17 -08005218 doHwResume = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005219 mHwPaused = false;
5220 }
5221 }
5222 }
5223 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005224 // Drain has completed or we are in standby, signal presentation complete
5225 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005226 track->mState = TrackBase::STOPPED;
5227 size_t audioHALFrames =
5228 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
5229 size_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08005230 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005231 track->presentationComplete(framesWritten, audioHALFrames);
5232 track->reset();
5233 tracksToRemove->add(track);
5234 }
5235 } else {
5236 // No buffers for this track. Give it a few chances to
5237 // fill a buffer, then remove it from active list.
5238 if (--(track->mRetryCount) <= 0) {
5239 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
5240 track->name());
5241 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08005242 // indicate to client process that the track was disabled because of underrun;
5243 // it will then automatically call start() when data is available
5244 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005245 } else if (last){
5246 mixerStatus = MIXER_TRACKS_ENABLED;
5247 }
5248 }
5249 }
5250 // compute volume for this track
5251 processVolume_l(track, last);
5252 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005253
Eric Laurentea0fade2013-10-04 16:23:48 -07005254 // make sure the pause/flush/resume sequence is executed in the right order.
5255 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5256 // before flush and then resume HW. This can happen in case of pause/flush/resume
5257 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07005258 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurent972a1732013-09-04 09:42:59 -07005259 mOutput->stream->pause(mOutput->stream);
5260 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005261 if (mFlushPending) {
5262 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005263 }
Eric Laurentfd477972013-10-25 18:10:40 -07005264 if (!mStandby && doHwResume) {
Eric Laurent972a1732013-09-04 09:42:59 -07005265 mOutput->stream->resume(mOutput->stream);
5266 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005267
Eric Laurentbfb1b832013-01-07 09:53:42 -08005268 // remove all the tracks that need to be...
5269 removeTracks_l(*tracksToRemove);
5270
5271 return mixerStatus;
5272}
5273
Eric Laurentbfb1b832013-01-07 09:53:42 -08005274// must be called with thread mutex locked
5275bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
5276{
Eric Laurent3b4529e2013-09-05 18:09:19 -07005277 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
5278 mWriteAckSequence, mDrainSequence);
5279 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005280 return true;
5281 }
5282 return false;
5283}
5284
Eric Laurentbfb1b832013-01-07 09:53:42 -08005285bool AudioFlinger::OffloadThread::waitingAsyncCallback()
5286{
5287 Mutex::Autolock _l(mLock);
5288 return waitingAsyncCallback_l();
5289}
5290
5291void AudioFlinger::OffloadThread::flushHw_l()
5292{
Eric Laurente659ef42014-09-29 13:06:46 -07005293 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005294 // Flush anything still waiting in the mixbuffer
5295 mCurrentWriteLength = 0;
5296 mBytesRemaining = 0;
5297 mPausedWriteLength = 0;
5298 mPausedBytesRemaining = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08005299
Eric Laurentbfb1b832013-01-07 09:53:42 -08005300 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005301 // discard any pending drain or write ack by incrementing sequence
5302 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5303 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005304 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005305 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5306 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005307 }
5308}
5309
5310// ----------------------------------------------------------------------------
5311
Eric Laurent81784c32012-11-19 14:55:58 -08005312AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07005313 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08005314 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
Eric Laurent72e3f392015-05-20 14:43:50 -07005315 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08005316 mWaitTimeMs(UINT_MAX)
5317{
5318 addOutputTrack(mainThread);
5319}
5320
5321AudioFlinger::DuplicatingThread::~DuplicatingThread()
5322{
5323 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5324 mOutputTracks[i]->destroy();
5325 }
5326}
5327
5328void AudioFlinger::DuplicatingThread::threadLoop_mix()
5329{
5330 // mix buffers...
5331 if (outputsReady(outputTracks)) {
5332 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
5333 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08005334 if (mMixerBufferValid) {
5335 memset(mMixerBuffer, 0, mMixerBufferSize);
5336 } else {
5337 memset(mSinkBuffer, 0, mSinkBufferSize);
5338 }
Eric Laurent81784c32012-11-19 14:55:58 -08005339 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005340 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005341 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005342 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005343 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005344}
5345
5346void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
5347{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005348 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005349 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005350 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005351 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005352 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005353 }
5354 } else if (mBytesWritten != 0) {
5355 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5356 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005357 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005358 } else {
5359 // flush remaining overflow buffers in output tracks
5360 writeFrames = 0;
5361 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005362 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005363 }
5364}
5365
Eric Laurentbfb1b832013-01-07 09:53:42 -08005366ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005367{
5368 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08005369 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005370 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07005371 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08005372 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005373}
5374
5375void AudioFlinger::DuplicatingThread::threadLoop_standby()
5376{
5377 // DuplicatingThread implements standby by stopping all tracks
5378 for (size_t i = 0; i < outputTracks.size(); i++) {
5379 outputTracks[i]->stop();
5380 }
5381}
5382
5383void AudioFlinger::DuplicatingThread::saveOutputTracks()
5384{
5385 outputTracks = mOutputTracks;
5386}
5387
5388void AudioFlinger::DuplicatingThread::clearOutputTracks()
5389{
5390 outputTracks.clear();
5391}
5392
5393void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
5394{
5395 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08005396 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
5397 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
5398 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
5399 const size_t frameCount =
5400 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
5401 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
5402 // from different OutputTracks and their associated MixerThreads (e.g. one may
5403 // nearly empty and the other may be dropping data).
5404
5405 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08005406 this,
5407 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08005408 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08005409 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005410 frameCount,
5411 IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08005412 if (outputTrack->cblk() != NULL) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005413 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
Eric Laurent81784c32012-11-19 14:55:58 -08005414 mOutputTracks.add(outputTrack);
Andy Hungc25b84a2015-01-14 19:04:10 -08005415 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005416 updateWaitTime_l();
5417 }
5418}
5419
5420void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
5421{
5422 Mutex::Autolock _l(mLock);
5423 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5424 if (mOutputTracks[i]->thread() == thread) {
5425 mOutputTracks[i]->destroy();
5426 mOutputTracks.removeAt(i);
5427 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07005428 if (thread->getOutput() == mOutput) {
5429 mOutput = NULL;
5430 }
Eric Laurent81784c32012-11-19 14:55:58 -08005431 return;
5432 }
5433 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07005434 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005435}
5436
5437// caller must hold mLock
5438void AudioFlinger::DuplicatingThread::updateWaitTime_l()
5439{
5440 mWaitTimeMs = UINT_MAX;
5441 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5442 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
5443 if (strong != 0) {
5444 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
5445 if (waitTimeMs < mWaitTimeMs) {
5446 mWaitTimeMs = waitTimeMs;
5447 }
5448 }
5449 }
5450}
5451
5452
5453bool AudioFlinger::DuplicatingThread::outputsReady(
5454 const SortedVector< sp<OutputTrack> > &outputTracks)
5455{
5456 for (size_t i = 0; i < outputTracks.size(); i++) {
5457 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
5458 if (thread == 0) {
5459 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
5460 outputTracks[i].get());
5461 return false;
5462 }
5463 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5464 // see note at standby() declaration
5465 if (playbackThread->standby() && !playbackThread->isSuspended()) {
5466 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
5467 thread.get());
5468 return false;
5469 }
5470 }
5471 return true;
5472}
5473
5474uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
5475{
5476 return (mWaitTimeMs * 1000) / 2;
5477}
5478
5479void AudioFlinger::DuplicatingThread::cacheParameters_l()
5480{
5481 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
5482 updateWaitTime_l();
5483
5484 MixerThread::cacheParameters_l();
5485}
5486
5487// ----------------------------------------------------------------------------
5488// Record
5489// ----------------------------------------------------------------------------
5490
5491AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5492 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08005493 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08005494 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07005495 audio_devices_t inDevice,
5496 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08005497#ifdef TEE_SINK
5498 , const sp<NBAIO_Sink>& teeSink
5499#endif
5500 ) :
Eric Laurent72e3f392015-05-20 14:43:50 -07005501 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005502 mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005503 // mRsmpInFrames and mRsmpInFramesP2 are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005504 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08005505#ifdef TEE_SINK
5506 , mTeeSink(teeSink)
5507#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07005508 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
5509 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005510 // mFastCapture below
5511 , mFastCaptureFutex(0)
5512 // mInputSource
5513 // mPipeSink
5514 // mPipeSource
5515 , mPipeFramesP2(0)
5516 // mPipeMemory
5517 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005518 , mFastTrackAvail(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005519{
Glenn Kastend7dca052015-03-05 16:05:54 -08005520 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
5521 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08005522
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005523 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005524
5525 // create an NBAIO source for the HAL input stream, and negotiate
5526 mInputSource = new AudioStreamInSource(input->stream);
5527 size_t numCounterOffers = 0;
5528 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
5529 ssize_t index = mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
5530 ALOG_ASSERT(index == 0);
5531
5532 // initialize fast capture depending on configuration
5533 bool initFastCapture;
5534 switch (kUseFastCapture) {
5535 case FastCapture_Never:
5536 initFastCapture = false;
5537 break;
5538 case FastCapture_Always:
5539 initFastCapture = true;
5540 break;
5541 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07005542 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005543 break;
5544 // case FastCapture_Dynamic:
5545 }
5546
5547 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07005548 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005549 NBAIO_Format format = mInputSource->format();
Glenn Kasten49d00ad2014-07-21 11:22:03 -07005550 size_t pipeFramesP2 = roundup(mSampleRate / 25); // double-buffering of 20 ms each
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005551 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
5552 void *pipeBuffer;
5553 const sp<MemoryDealer> roHeap(readOnlyHeap());
5554 sp<IMemory> pipeMemory;
5555 if ((roHeap == 0) ||
5556 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
5557 (pipeBuffer = pipeMemory->pointer()) == NULL) {
5558 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
5559 goto failed;
5560 }
5561 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
5562 memset(pipeBuffer, 0, pipeSize);
5563 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
5564 const NBAIO_Format offers[1] = {format};
5565 size_t numCounterOffers = 0;
5566 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
5567 ALOG_ASSERT(index == 0);
5568 mPipeSink = pipe;
5569 PipeReader *pipeReader = new PipeReader(*pipe);
5570 numCounterOffers = 0;
5571 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
5572 ALOG_ASSERT(index == 0);
5573 mPipeSource = pipeReader;
5574 mPipeFramesP2 = pipeFramesP2;
5575 mPipeMemory = pipeMemory;
5576
5577 // create fast capture
5578 mFastCapture = new FastCapture();
5579 FastCaptureStateQueue *sq = mFastCapture->sq();
5580#ifdef STATE_QUEUE_DUMP
5581 // FIXME
5582#endif
5583 FastCaptureState *state = sq->begin();
5584 state->mCblk = NULL;
5585 state->mInputSource = mInputSource.get();
5586 state->mInputSourceGen++;
5587 state->mPipeSink = pipe;
5588 state->mPipeSinkGen++;
5589 state->mFrameCount = mFrameCount;
5590 state->mCommand = FastCaptureState::COLD_IDLE;
5591 // already done in constructor initialization list
5592 //mFastCaptureFutex = 0;
5593 state->mColdFutexAddr = &mFastCaptureFutex;
5594 state->mColdGen++;
5595 state->mDumpState = &mFastCaptureDumpState;
5596#ifdef TEE_SINK
5597 // FIXME
5598#endif
5599 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
5600 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
5601 sq->end();
5602 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5603
5604 // start the fast capture
5605 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
5606 pid_t tid = mFastCapture->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07005607 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005608#ifdef AUDIO_WATCHDOG
5609 // FIXME
5610#endif
5611
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005612 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005613 }
5614failed: ;
5615
5616 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08005617}
5618
Eric Laurent81784c32012-11-19 14:55:58 -08005619AudioFlinger::RecordThread::~RecordThread()
5620{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005621 if (mFastCapture != 0) {
5622 FastCaptureStateQueue *sq = mFastCapture->sq();
5623 FastCaptureState *state = sq->begin();
5624 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5625 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5626 if (old == -1) {
5627 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5628 }
5629 }
5630 state->mCommand = FastCaptureState::EXIT;
5631 sq->end();
5632 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5633 mFastCapture->join();
5634 mFastCapture.clear();
5635 }
5636 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07005637 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07005638 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08005639}
5640
5641void AudioFlinger::RecordThread::onFirstRef()
5642{
Glenn Kastend7dca052015-03-05 16:05:54 -08005643 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08005644}
5645
Eric Laurent81784c32012-11-19 14:55:58 -08005646bool AudioFlinger::RecordThread::threadLoop()
5647{
Eric Laurent81784c32012-11-19 14:55:58 -08005648 nsecs_t lastWarning = 0;
5649
5650 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08005651
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005652reacquire_wakelock:
5653 sp<RecordTrack> activeTrack;
Glenn Kasten2b806402013-11-20 16:37:38 -08005654 int activeTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005655 {
5656 Mutex::Autolock _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005657 size_t size = mActiveTracks.size();
5658 activeTracksGen = mActiveTracksGen;
5659 if (size > 0) {
5660 // FIXME an arbitrary choice
5661 activeTrack = mActiveTracks[0];
5662 acquireWakeLock_l(activeTrack->uid());
5663 if (size > 1) {
5664 SortedVector<int> tmp;
5665 for (size_t i = 0; i < size; i++) {
5666 tmp.add(mActiveTracks[i]->uid());
5667 }
5668 updateWakeLockUids_l(tmp);
5669 }
5670 } else {
5671 acquireWakeLock_l(-1);
5672 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005673 }
5674
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005675 // used to request a deferred sleep, to be executed later while mutex is unlocked
5676 uint32_t sleepUs = 0;
5677
5678 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005679 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005680 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07005681
Glenn Kasten5edadd42013-08-14 16:30:49 -07005682 // sleep with mutex unlocked
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005683 if (sleepUs > 0) {
Glenn Kastene7754022014-10-31 12:11:26 -07005684 ATRACE_BEGIN("sleep");
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005685 usleep(sleepUs);
Glenn Kastene7754022014-10-31 12:11:26 -07005686 ATRACE_END();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005687 sleepUs = 0;
Glenn Kasten5edadd42013-08-14 16:30:49 -07005688 }
5689
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005690 // activeTracks accumulates a copy of a subset of mActiveTracks
5691 Vector< sp<RecordTrack> > activeTracks;
5692
Glenn Kasten735f45f2014-08-18 15:51:59 -07005693 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005694 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07005695
Glenn Kasten735f45f2014-08-18 15:51:59 -07005696 // reference to a fast track which is about to be removed
5697 sp<RecordTrack> fastTrackToRemove;
5698
Eric Laurent81784c32012-11-19 14:55:58 -08005699 { // scope for mLock
5700 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08005701
Eric Laurent021cf962014-05-13 10:18:14 -07005702 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005703
Eric Laurent000a4192014-01-29 15:17:32 -08005704 // check exitPending here because checkForNewParameters_l() and
5705 // checkForNewParameters_l() can temporarily release mLock
5706 if (exitPending()) {
5707 break;
5708 }
5709
Glenn Kasten2b806402013-11-20 16:37:38 -08005710 // if no active track(s), then standby and release wakelock
5711 size_t size = mActiveTracks.size();
5712 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07005713 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005714 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08005715 releaseWakeLock_l();
5716 ALOGV("RecordThread: loop stopping");
5717 // go to sleep
5718 mWaitWorkCV.wait(mLock);
5719 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005720 goto reacquire_wakelock;
5721 }
5722
Glenn Kasten2b806402013-11-20 16:37:38 -08005723 if (mActiveTracksGen != activeTracksGen) {
5724 activeTracksGen = mActiveTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005725 SortedVector<int> tmp;
Glenn Kasten2b806402013-11-20 16:37:38 -08005726 for (size_t i = 0; i < size; i++) {
5727 tmp.add(mActiveTracks[i]->uid());
5728 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005729 updateWakeLockUids_l(tmp);
Eric Laurent81784c32012-11-19 14:55:58 -08005730 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005731
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005732 bool doBroadcast = false;
5733 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07005734
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005735 activeTrack = mActiveTracks[i];
5736 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07005737 if (activeTrack->isFastTrack()) {
5738 ALOG_ASSERT(fastTrackToRemove == 0);
5739 fastTrackToRemove = activeTrack;
5740 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005741 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08005742 mActiveTracks.remove(activeTrack);
5743 mActiveTracksGen++;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005744 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07005745 continue;
5746 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005747
5748 TrackBase::track_state activeTrackState = activeTrack->mState;
5749 switch (activeTrackState) {
5750
5751 case TrackBase::PAUSING:
5752 mActiveTracks.remove(activeTrack);
5753 mActiveTracksGen++;
5754 doBroadcast = true;
5755 size--;
5756 continue;
5757
5758 case TrackBase::STARTING_1:
5759 sleepUs = 10000;
5760 i++;
5761 continue;
5762
5763 case TrackBase::STARTING_2:
5764 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005765 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07005766 activeTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005767 break;
5768
5769 case TrackBase::ACTIVE:
5770 break;
5771
5772 case TrackBase::IDLE:
5773 i++;
5774 continue;
5775
5776 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08005777 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07005778 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005779
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005780 activeTracks.add(activeTrack);
5781 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07005782
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005783 if (activeTrack->isFastTrack()) {
5784 ALOG_ASSERT(!mFastTrackAvail);
5785 ALOG_ASSERT(fastTrack == 0);
5786 fastTrack = activeTrack;
5787 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005788 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005789 if (doBroadcast) {
5790 mStartStopCond.broadcast();
5791 }
5792
5793 // sleep if there are no active tracks to process
5794 if (activeTracks.size() == 0) {
5795 if (sleepUs == 0) {
5796 sleepUs = kRecordThreadSleepUs;
5797 }
5798 continue;
5799 }
5800 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07005801
Eric Laurent81784c32012-11-19 14:55:58 -08005802 lockEffectChains_l(effectChains);
5803 }
5804
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005805 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07005806
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005807 size_t size = effectChains.size();
5808 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005809 // thread mutex is not locked, but effect chain is locked
5810 effectChains[i]->process_l();
5811 }
5812
Glenn Kasten735f45f2014-08-18 15:51:59 -07005813 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005814 if (mFastCapture != 0) {
5815 FastCaptureStateQueue *sq = mFastCapture->sq();
5816 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07005817 bool didModify = false;
5818 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005819 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
5820 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
5821 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5822 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5823 if (old == -1) {
5824 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5825 }
5826 }
5827 state->mCommand = FastCaptureState::READ_WRITE;
5828#if 0 // FIXME
5829 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08005830 FastThreadDumpState::kSamplingNforLowRamDevice :
5831 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005832#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07005833 didModify = true;
5834 }
5835 audio_track_cblk_t *cblkOld = state->mCblk;
5836 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
5837 if (cblkNew != cblkOld) {
5838 state->mCblk = cblkNew;
5839 // block until acked if removing a fast track
5840 if (cblkOld != NULL) {
5841 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
5842 }
5843 didModify = true;
5844 }
5845 sq->end(didModify);
5846 if (didModify) {
5847 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005848#if 0
5849 if (kUseFastCapture == FastCapture_Dynamic) {
5850 mNormalSource = mPipeSource;
5851 }
5852#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005853 }
5854 }
5855
Glenn Kasten735f45f2014-08-18 15:51:59 -07005856 // now run the fast track destructor with thread mutex unlocked
5857 fastTrackToRemove.clear();
5858
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005859 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
5860 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
5861 // slow, then this RecordThread will overrun by not calling HAL read often enough.
5862 // If destination is non-contiguous, first read past the nominal end of buffer, then
5863 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005864
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005865 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005866 ssize_t framesRead;
5867
5868 // If an NBAIO source is present, use it to read the normal capture's data
5869 if (mPipeSource != 0) {
5870 size_t framesToRead = mBufferSize / mFrameSize;
Andy Hung57446612015-04-19 23:56:46 -07005871 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005872 framesToRead, AudioBufferProvider::kInvalidPTS);
5873 if (framesRead == 0) {
5874 // since pipe is non-blocking, simulate blocking input
5875 sleepUs = (framesToRead * 1000000LL) / mSampleRate;
5876 }
5877 // otherwise use the HAL / AudioStreamIn directly
5878 } else {
5879 ssize_t bytesRead = mInput->stream->read(mInput->stream,
Andy Hung57446612015-04-19 23:56:46 -07005880 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005881 if (bytesRead < 0) {
5882 framesRead = bytesRead;
5883 } else {
5884 framesRead = bytesRead / mFrameSize;
5885 }
5886 }
5887
5888 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
5889 ALOGE("read failed: framesRead=%d", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005890 // Force input into standby so that it tries to recover at next read attempt
5891 inputStandBy();
5892 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005893 }
5894 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005895 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005896 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005897 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005898
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005899 if (mTeeSink != 0) {
Andy Hung57446612015-04-19 23:56:46 -07005900 (void) mTeeSink->write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005901 }
5902 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005903 {
5904 size_t part1 = mRsmpInFramesP2 - rear;
5905 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07005906 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005907 (framesRead - part1) * mFrameSize);
5908 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005909 }
5910 rear = mRsmpInRear += framesRead;
5911
5912 size = activeTracks.size();
5913 // loop over each active track
5914 for (size_t i = 0; i < size; i++) {
5915 activeTrack = activeTracks[i];
5916
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005917 // skip fast tracks, as those are handled directly by FastCapture
5918 if (activeTrack->isFastTrack()) {
5919 continue;
5920 }
5921
Andy Hung73c02e42015-03-29 01:13:58 -07005922 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07005923 // TODO: Update the activeTrack buffer converter in case of reconfigure.
5924
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005925 enum {
5926 OVERRUN_UNKNOWN,
5927 OVERRUN_TRUE,
5928 OVERRUN_FALSE
5929 } overrun = OVERRUN_UNKNOWN;
5930
5931 // loop over getNextBuffer to handle circular sink
5932 for (;;) {
5933
5934 activeTrack->mSink.frameCount = ~0;
5935 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
5936 size_t framesOut = activeTrack->mSink.frameCount;
5937 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
5938
Andy Hung73c02e42015-03-29 01:13:58 -07005939 // check available frames and handle overrun conditions
5940 // if the record track isn't draining fast enough.
5941 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005942 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07005943 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
5944 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005945 overrun = OVERRUN_TRUE;
5946 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005947 if (framesOut == 0 || framesIn == 0) {
5948 break;
5949 }
5950
Andy Hung6770c6f2015-04-07 13:43:36 -07005951 // Don't allow framesOut to be larger than what is possible with resampling
5952 // from framesIn.
5953 // This isn't strictly necessary but helps limit buffer resizing in
5954 // RecordBufferConverter. TODO: remove when no longer needed.
5955 framesOut = min(framesOut,
5956 destinationFramesPossible(
5957 framesIn, mSampleRate, activeTrack->mSampleRate));
Andy Hung97a893e2015-03-29 01:03:07 -07005958 // process frames from the RecordThread buffer provider to the RecordTrack buffer
5959 framesOut = activeTrack->mRecordBufferConverter->convert(
5960 activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005961
5962 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
5963 overrun = OVERRUN_FALSE;
5964 }
5965
5966 if (activeTrack->mFramesToDrop == 0) {
5967 if (framesOut > 0) {
5968 activeTrack->mSink.frameCount = framesOut;
5969 activeTrack->releaseBuffer(&activeTrack->mSink);
5970 }
5971 } else {
5972 // FIXME could do a partial drop of framesOut
5973 if (activeTrack->mFramesToDrop > 0) {
5974 activeTrack->mFramesToDrop -= framesOut;
5975 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005976 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005977 }
5978 } else {
5979 activeTrack->mFramesToDrop += framesOut;
5980 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
5981 activeTrack->mSyncStartEvent->isCancelled()) {
5982 ALOGW("Synced record %s, session %d, trigger session %d",
5983 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
5984 activeTrack->sessionId(),
5985 (activeTrack->mSyncStartEvent != 0) ?
5986 activeTrack->mSyncStartEvent->triggerSession() : 0);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005987 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005988 }
5989 }
5990 }
5991
5992 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005993 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005994 }
5995 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005996
5997 switch (overrun) {
5998 case OVERRUN_TRUE:
5999 // client isn't retrieving buffers fast enough
6000 if (!activeTrack->setOverflow()) {
6001 nsecs_t now = systemTime();
6002 // FIXME should lastWarning per track?
6003 if ((now - lastWarning) > kWarningThrottleNs) {
6004 ALOGW("RecordThread: buffer overflow");
6005 lastWarning = now;
6006 }
6007 }
6008 break;
6009 case OVERRUN_FALSE:
6010 activeTrack->clearOverflow();
6011 break;
6012 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006013 break;
6014 }
6015
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006016 }
6017
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006018unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08006019 // enable changes in effect chain
6020 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006021 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08006022 }
6023
Glenn Kasten93e471f2013-08-19 08:40:07 -07006024 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08006025
6026 {
6027 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07006028 for (size_t i = 0; i < mTracks.size(); i++) {
6029 sp<RecordTrack> track = mTracks[i];
6030 track->invalidate();
6031 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006032 mActiveTracks.clear();
6033 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08006034 mStartStopCond.broadcast();
6035 }
6036
6037 releaseWakeLock();
6038
6039 ALOGV("RecordThread %p exiting", this);
6040 return false;
6041}
6042
Glenn Kasten93e471f2013-08-19 08:40:07 -07006043void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08006044{
6045 if (!mStandby) {
6046 inputStandBy();
6047 mStandby = true;
6048 }
6049}
6050
6051void AudioFlinger::RecordThread::inputStandBy()
6052{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006053 // Idle the fast capture if it's currently running
6054 if (mFastCapture != 0) {
6055 FastCaptureStateQueue *sq = mFastCapture->sq();
6056 FastCaptureState *state = sq->begin();
6057 if (!(state->mCommand & FastCaptureState::IDLE)) {
6058 state->mCommand = FastCaptureState::COLD_IDLE;
6059 state->mColdFutexAddr = &mFastCaptureFutex;
6060 state->mColdGen++;
6061 mFastCaptureFutex = 0;
6062 sq->end();
6063 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
6064 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
6065#if 0
6066 if (kUseFastCapture == FastCapture_Dynamic) {
6067 // FIXME
6068 }
6069#endif
6070#ifdef AUDIO_WATCHDOG
6071 // FIXME
6072#endif
6073 } else {
6074 sq->end(false /*didModify*/);
6075 }
6076 }
Eric Laurent81784c32012-11-19 14:55:58 -08006077 mInput->stream->common.standby(&mInput->stream->common);
6078}
6079
Glenn Kasten05997e22014-03-13 15:08:33 -07006080// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07006081sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08006082 const sp<AudioFlinger::Client>& client,
6083 uint32_t sampleRate,
6084 audio_format_t format,
6085 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08006086 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08006087 int sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07006088 size_t *notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08006089 int uid,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07006090 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08006091 pid_t tid,
6092 status_t *status)
6093{
Glenn Kasten74935e42013-12-19 08:56:45 -08006094 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08006095 sp<RecordTrack> track;
6096 status_t lStatus;
6097
Glenn Kasten90e58b12013-07-31 16:16:02 -07006098 // client expresses a preference for FAST, but we get the final say
6099 if (*flags & IAudioFlinger::TRACK_FAST) {
6100 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07006101 // we formerly checked for a callback handler (non-0 tid),
6102 // but that is no longer required for TRANSFER_OBTAIN mode
6103 //
Glenn Kasten74105912014-07-03 12:28:53 -07006104 // frame count is not specified, or is exactly the pipe depth
6105 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006106 // PCM data
6107 audio_is_linear_pcm(format) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006108 // native format
6109 (format == mFormat) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006110 // native channel mask
6111 (channelMask == mChannelMask) &&
6112 // native hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07006113 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006114 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006115 hasFastCapture() &&
6116 // there are sufficient fast track slots available
6117 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07006118 ) {
Glenn Kasten74105912014-07-03 12:28:53 -07006119 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%u mFrameCount=%u",
Glenn Kasten90e58b12013-07-31 16:16:02 -07006120 frameCount, mFrameCount);
6121 } else {
Glenn Kasten74105912014-07-03 12:28:53 -07006122 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%u mFrameCount=%u mPipeFramesP2=%u "
6123 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006124 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Glenn Kasten74105912014-07-03 12:28:53 -07006125 frameCount, mFrameCount, mPipeFramesP2,
6126 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
6127 hasFastCapture(), tid, mFastTrackAvail);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006128 *flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kasten74105912014-07-03 12:28:53 -07006129 }
6130 }
6131
6132 // compute track buffer size in frames, and suggest the notification frame count
6133 if (*flags & IAudioFlinger::TRACK_FAST) {
6134 // fast track: frame count is exactly the pipe depth
6135 frameCount = mPipeFramesP2;
6136 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
6137 *notificationFrames = mFrameCount;
6138 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006139 // not fast track: max notification period is resampled equivalent of one HAL buffer time
6140 // or 20 ms if there is a fast capture
6141 // TODO This could be a roundupRatio inline, and const
6142 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
6143 * sampleRate + mSampleRate - 1) / mSampleRate;
6144 // minimum number of notification periods is at least kMinNotifications,
6145 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
6146 static const size_t kMinNotifications = 3;
6147 static const uint32_t kMinMs = 30;
6148 // TODO This could be a roundupRatio inline
6149 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
6150 // TODO This could be a roundupRatio inline
6151 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
6152 maxNotificationFrames;
6153 const size_t minFrameCount = maxNotificationFrames *
6154 max(kMinNotifications, minNotificationsByMs);
6155 frameCount = max(frameCount, minFrameCount);
6156 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
6157 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07006158 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07006159 }
Glenn Kasten74935e42013-12-19 08:56:45 -08006160 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07006161
Glenn Kasten15e57982013-09-24 11:52:37 -07006162 lStatus = initCheck();
6163 if (lStatus != NO_ERROR) {
6164 ALOGE("createRecordTrack_l() audio driver not initialized");
6165 goto Exit;
6166 }
Eric Laurent81784c32012-11-19 14:55:58 -08006167
6168 { // scope for mLock
6169 Mutex::Autolock _l(mLock);
6170
6171 track = new RecordTrack(this, client, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07006172 format, channelMask, frameCount, NULL, sessionId, uid,
6173 *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08006174
Glenn Kasten03003332013-08-06 15:40:54 -07006175 lStatus = track->initCheck();
6176 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07006177 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08006178 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08006179 goto Exit;
6180 }
6181 mTracks.add(track);
6182
6183 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6184 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6185 mAudioFlinger->btNrecIsOff();
6186 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6187 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006188
6189 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
6190 pid_t callingPid = IPCThreadState::self()->getCallingPid();
6191 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
6192 // so ask activity manager to do this on our behalf
6193 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
6194 }
Eric Laurent81784c32012-11-19 14:55:58 -08006195 }
Glenn Kasten05997e22014-03-13 15:08:33 -07006196
Eric Laurent81784c32012-11-19 14:55:58 -08006197 lStatus = NO_ERROR;
6198
6199Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07006200 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08006201 return track;
6202}
6203
6204status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
6205 AudioSystem::sync_event_t event,
6206 int triggerSession)
6207{
6208 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
6209 sp<ThreadBase> strongMe = this;
6210 status_t status = NO_ERROR;
6211
6212 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006213 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006214 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006215 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08006216 triggerSession,
6217 recordTrack->sessionId(),
6218 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006219 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08006220 // Sync event can be cancelled by the trigger session if the track is not in a
6221 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006222 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006223 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006224 } else {
6225 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006226 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006227 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08006228 }
6229 }
6230
6231 {
Glenn Kasten47c20702013-08-13 15:37:35 -07006232 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08006233 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006234 if (mActiveTracks.indexOf(recordTrack) >= 0) {
6235 if (recordTrack->mState == TrackBase::PAUSING) {
6236 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006237 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006238 } else {
6239 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08006240 }
6241 return status;
6242 }
6243
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006244 // TODO consider other ways of handling this, such as changing the state to :STARTING and
6245 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
6246 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006247 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08006248 mActiveTracks.add(recordTrack);
6249 mActiveTracksGen++;
Eric Laurent83b88082014-06-20 18:31:16 -07006250 status_t status = NO_ERROR;
6251 if (recordTrack->isExternalTrack()) {
6252 mLock.unlock();
Eric Laurent4dc68062014-07-28 17:26:49 -07006253 status = AudioSystem::startInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006254 mLock.lock();
6255 // FIXME should verify that recordTrack is still in mActiveTracks
6256 if (status != NO_ERROR) {
6257 mActiveTracks.remove(recordTrack);
6258 mActiveTracksGen++;
6259 recordTrack->clearSyncStartEvent();
6260 ALOGV("RecordThread::start error %d", status);
6261 return status;
6262 }
Eric Laurent81784c32012-11-19 14:55:58 -08006263 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006264 // Catch up with current buffer indices if thread is already running.
6265 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
6266 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
6267 // see previously buffered data before it called start(), but with greater risk of overrun.
6268
Andy Hung73c02e42015-03-29 01:13:58 -07006269 recordTrack->mResamplerBufferProvider->reset();
Andy Hung97a893e2015-03-29 01:03:07 -07006270 // clear any converter state as new data will be discontinuous
6271 recordTrack->mRecordBufferConverter->reset();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006272 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08006273 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08006274 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08006275 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006276 ALOGV("Record failed to start");
6277 status = BAD_VALUE;
6278 goto startError;
6279 }
Eric Laurent81784c32012-11-19 14:55:58 -08006280 return status;
6281 }
Glenn Kasten7c027242012-12-26 14:43:16 -08006282
Eric Laurent81784c32012-11-19 14:55:58 -08006283startError:
Eric Laurent83b88082014-06-20 18:31:16 -07006284 if (recordTrack->isExternalTrack()) {
Eric Laurent4dc68062014-07-28 17:26:49 -07006285 AudioSystem::stopInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006286 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006287 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006288 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08006289 return status;
6290}
6291
Eric Laurent81784c32012-11-19 14:55:58 -08006292void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6293{
6294 sp<SyncEvent> strongEvent = event.promote();
6295
6296 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08006297 sp<RefBase> ptr = strongEvent->cookie().promote();
6298 if (ptr != 0) {
6299 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
6300 recordTrack->handleSyncStartEvent(strongEvent);
6301 }
Eric Laurent81784c32012-11-19 14:55:58 -08006302 }
6303}
6304
Glenn Kastena8356f62013-07-25 14:37:52 -07006305bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08006306 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07006307 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006308 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08006309 return false;
6310 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006311 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08006312 recordTrack->mState = TrackBase::PAUSING;
6313 // do not wait for mStartStopCond if exiting
6314 if (exitPending()) {
6315 return true;
6316 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006317 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08006318 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006319 // if we have been restarted, recordTrack is in mActiveTracks here
6320 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006321 ALOGV("Record stopped OK");
6322 return true;
6323 }
6324 return false;
6325}
6326
Glenn Kasten0f11b512014-01-31 16:18:54 -08006327bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08006328{
6329 return false;
6330}
6331
Glenn Kasten0f11b512014-01-31 16:18:54 -08006332status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006333{
6334#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
6335 if (!isValidSyncEvent(event)) {
6336 return BAD_VALUE;
6337 }
6338
6339 int eventSession = event->triggerSession();
6340 status_t ret = NAME_NOT_FOUND;
6341
6342 Mutex::Autolock _l(mLock);
6343
6344 for (size_t i = 0; i < mTracks.size(); i++) {
6345 sp<RecordTrack> track = mTracks[i];
6346 if (eventSession == track->sessionId()) {
6347 (void) track->setSyncEvent(event);
6348 ret = NO_ERROR;
6349 }
6350 }
6351 return ret;
6352#else
6353 return BAD_VALUE;
6354#endif
6355}
6356
6357// destroyTrack_l() must be called with ThreadBase::mLock held
6358void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6359{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006360 track->terminate();
6361 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08006362 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08006363 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006364 removeTrack_l(track);
6365 }
6366}
6367
6368void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6369{
6370 mTracks.remove(track);
6371 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006372 if (track->isFastTrack()) {
6373 ALOG_ASSERT(!mFastTrackAvail);
6374 mFastTrackAvail = true;
6375 }
Eric Laurent81784c32012-11-19 14:55:58 -08006376}
6377
6378void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6379{
6380 dumpInternals(fd, args);
6381 dumpTracks(fd, args);
6382 dumpEffectChains(fd, args);
6383}
6384
6385void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6386{
Elliott Hughes87cebad2014-05-22 10:14:43 -07006387 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08006388
Glenn Kasten44182c22015-03-05 17:12:23 -08006389 dumpBase(fd, args);
6390
6391 if (mActiveTracks.size() == 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006392 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006393 }
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006394 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006395 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08006396
6397 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
6398 const FastCaptureDumpState copy(mFastCaptureDumpState);
6399 copy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006400}
6401
Glenn Kasten0f11b512014-01-31 16:18:54 -08006402void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006403{
6404 const size_t SIZE = 256;
6405 char buffer[SIZE];
6406 String8 result;
6407
Marco Nelissenb2208842014-02-07 14:00:50 -08006408 size_t numtracks = mTracks.size();
6409 size_t numactive = mActiveTracks.size();
6410 size_t numactiveseen = 0;
Elliott Hughes87cebad2014-05-22 10:14:43 -07006411 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08006412 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006413 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08006414 RecordTrack::appendDumpHeader(result);
6415 for (size_t i = 0; i < numtracks ; ++i) {
6416 sp<RecordTrack> track = mTracks[i];
6417 if (track != 0) {
6418 bool active = mActiveTracks.indexOf(track) >= 0;
6419 if (active) {
6420 numactiveseen++;
6421 }
6422 track->dump(buffer, SIZE, active);
6423 result.append(buffer);
6424 }
Eric Laurent81784c32012-11-19 14:55:58 -08006425 }
Marco Nelissenb2208842014-02-07 14:00:50 -08006426 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006427 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006428 }
6429
Marco Nelissenb2208842014-02-07 14:00:50 -08006430 if (numactiveseen != numactive) {
6431 snprintf(buffer, SIZE, " The following tracks are in the active list but"
6432 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006433 result.append(buffer);
6434 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08006435 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08006436 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08006437 if (mTracks.indexOf(track) < 0) {
6438 track->dump(buffer, SIZE, true);
6439 result.append(buffer);
6440 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006441 }
Eric Laurent81784c32012-11-19 14:55:58 -08006442
6443 }
6444 write(fd, result.string(), result.size());
6445}
6446
Andy Hung73c02e42015-03-29 01:13:58 -07006447
6448void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
6449{
6450 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6451 RecordThread *recordThread = (RecordThread *) threadBase.get();
6452 mRsmpInFront = recordThread->mRsmpInRear;
6453 mRsmpInUnrel = 0;
6454}
6455
6456void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
6457 size_t *framesAvailable, bool *hasOverrun)
6458{
6459 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6460 RecordThread *recordThread = (RecordThread *) threadBase.get();
6461 const int32_t rear = recordThread->mRsmpInRear;
6462 const int32_t front = mRsmpInFront;
6463 const ssize_t filled = rear - front;
6464
6465 size_t framesIn;
6466 bool overrun = false;
6467 if (filled < 0) {
6468 // should not happen, but treat like a massive overrun and re-sync
6469 framesIn = 0;
6470 mRsmpInFront = rear;
6471 overrun = true;
6472 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
6473 framesIn = (size_t) filled;
6474 } else {
6475 // client is not keeping up with server, but give it latest data
6476 framesIn = recordThread->mRsmpInFrames;
6477 mRsmpInFront = /* front = */ rear - framesIn;
6478 overrun = true;
6479 }
6480 if (framesAvailable != NULL) {
6481 *framesAvailable = framesIn;
6482 }
6483 if (hasOverrun != NULL) {
6484 *hasOverrun = overrun;
6485 }
6486}
6487
Eric Laurent81784c32012-11-19 14:55:58 -08006488// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006489status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
6490 AudioBufferProvider::Buffer* buffer, int64_t pts __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006491{
Andy Hung73c02e42015-03-29 01:13:58 -07006492 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006493 if (threadBase == 0) {
6494 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006495 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006496 return NOT_ENOUGH_DATA;
6497 }
6498 RecordThread *recordThread = (RecordThread *) threadBase.get();
6499 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07006500 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07006501 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006502 // FIXME should not be P2 (don't want to increase latency)
6503 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006504 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07006505 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006506 front &= recordThread->mRsmpInFramesP2 - 1;
6507 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07006508 if (part1 > (size_t) filled) {
6509 part1 = filled;
6510 }
6511 size_t ask = buffer->frameCount;
6512 ALOG_ASSERT(ask > 0);
6513 if (part1 > ask) {
6514 part1 = ask;
6515 }
6516 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07006517 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07006518 buffer->raw = NULL;
6519 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07006520 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07006521 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08006522 }
6523
Andy Hung57446612015-04-19 23:56:46 -07006524 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07006525 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07006526 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08006527 return NO_ERROR;
6528}
6529
6530// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006531void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
6532 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006533{
Glenn Kasten85948432013-08-19 12:09:05 -07006534 size_t stepCount = buffer->frameCount;
6535 if (stepCount == 0) {
6536 return;
6537 }
Andy Hung73c02e42015-03-29 01:13:58 -07006538 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
6539 mRsmpInUnrel -= stepCount;
6540 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07006541 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006542 buffer->frameCount = 0;
6543}
6544
Andy Hung97a893e2015-03-29 01:03:07 -07006545AudioFlinger::RecordThread::RecordBufferConverter::RecordBufferConverter(
6546 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6547 uint32_t srcSampleRate,
6548 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6549 uint32_t dstSampleRate) :
6550 mSrcChannelMask(AUDIO_CHANNEL_INVALID), // updateParameters will set following vars
6551 // mSrcFormat
6552 // mSrcSampleRate
6553 // mDstChannelMask
6554 // mDstFormat
6555 // mDstSampleRate
6556 // mSrcChannelCount
6557 // mDstChannelCount
6558 // mDstFrameSize
6559 mBuf(NULL), mBufFrames(0), mBufFrameSize(0),
Andy Hungd330ee42015-04-20 13:23:41 -07006560 mResampler(NULL),
6561 mIsLegacyDownmix(false),
6562 mIsLegacyUpmix(false),
6563 mRequiresFloat(false),
6564 mInputConverterProvider(NULL)
Andy Hung97a893e2015-03-29 01:03:07 -07006565{
6566 (void)updateParameters(srcChannelMask, srcFormat, srcSampleRate,
6567 dstChannelMask, dstFormat, dstSampleRate);
6568}
6569
6570AudioFlinger::RecordThread::RecordBufferConverter::~RecordBufferConverter() {
6571 free(mBuf);
6572 delete mResampler;
Andy Hungd330ee42015-04-20 13:23:41 -07006573 delete mInputConverterProvider;
Andy Hung97a893e2015-03-29 01:03:07 -07006574}
6575
6576size_t AudioFlinger::RecordThread::RecordBufferConverter::convert(void *dst,
6577 AudioBufferProvider *provider, size_t frames)
6578{
Andy Hungd330ee42015-04-20 13:23:41 -07006579 if (mInputConverterProvider != NULL) {
6580 mInputConverterProvider->setBufferProvider(provider);
6581 provider = mInputConverterProvider;
6582 }
6583
6584 if (mResampler == NULL) {
Andy Hung97a893e2015-03-29 01:03:07 -07006585 ALOGVV("NO RESAMPLING sampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6586 mSrcSampleRate, mSrcFormat, mDstFormat);
6587
6588 AudioBufferProvider::Buffer buffer;
6589 for (size_t i = frames; i > 0; ) {
6590 buffer.frameCount = i;
6591 status_t status = provider->getNextBuffer(&buffer, 0);
6592 if (status != OK || buffer.frameCount == 0) {
6593 frames -= i; // cannot fill request.
6594 break;
6595 }
Andy Hungd330ee42015-04-20 13:23:41 -07006596 // format convert to destination buffer
6597 convertNoResampler(dst, buffer.raw, buffer.frameCount);
Andy Hung97a893e2015-03-29 01:03:07 -07006598
6599 dst = (int8_t*)dst + buffer.frameCount * mDstFrameSize;
6600 i -= buffer.frameCount;
6601 provider->releaseBuffer(&buffer);
6602 }
6603 } else {
6604 ALOGVV("RESAMPLING mSrcSampleRate:%u mDstSampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6605 mSrcSampleRate, mDstSampleRate, mSrcFormat, mDstFormat);
6606
Andy Hungd330ee42015-04-20 13:23:41 -07006607 // reallocate buffer if needed
6608 if (mBufFrameSize != 0 && mBufFrames < frames) {
6609 free(mBuf);
6610 mBufFrames = frames;
6611 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
6612 }
Andy Hung97a893e2015-03-29 01:03:07 -07006613 // resampler accumulates, but we only have one source track
Andy Hungd330ee42015-04-20 13:23:41 -07006614 memset(mBuf, 0, frames * mBufFrameSize);
6615 frames = mResampler->resample((int32_t*)mBuf, frames, provider);
6616 // format convert to destination buffer
6617 convertResampler(dst, mBuf, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006618 }
6619 return frames;
6620}
6621
6622status_t AudioFlinger::RecordThread::RecordBufferConverter::updateParameters(
6623 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6624 uint32_t srcSampleRate,
6625 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6626 uint32_t dstSampleRate)
6627{
6628 // quick evaluation if there is any change.
6629 if (mSrcFormat == srcFormat
6630 && mSrcChannelMask == srcChannelMask
6631 && mSrcSampleRate == srcSampleRate
6632 && mDstFormat == dstFormat
6633 && mDstChannelMask == dstChannelMask
6634 && mDstSampleRate == dstSampleRate) {
6635 return NO_ERROR;
6636 }
6637
Andy Hungdb4c0312015-05-06 08:46:52 -07006638 ALOGV("RecordBufferConverter updateParameters srcMask:%#x dstMask:%#x"
6639 " srcFormat:%#x dstFormat:%#x srcRate:%u dstRate:%u",
6640 srcChannelMask, dstChannelMask, srcFormat, dstFormat, srcSampleRate, dstSampleRate);
Andy Hung97a893e2015-03-29 01:03:07 -07006641 const bool valid =
6642 audio_is_input_channel(srcChannelMask)
6643 && audio_is_input_channel(dstChannelMask)
6644 && audio_is_valid_format(srcFormat) && audio_is_linear_pcm(srcFormat)
6645 && audio_is_valid_format(dstFormat) && audio_is_linear_pcm(dstFormat)
6646 && (srcSampleRate <= dstSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX)
6647 ; // no upsampling checks for now
6648 if (!valid) {
6649 return BAD_VALUE;
6650 }
6651
6652 mSrcFormat = srcFormat;
6653 mSrcChannelMask = srcChannelMask;
6654 mSrcSampleRate = srcSampleRate;
6655 mDstFormat = dstFormat;
6656 mDstChannelMask = dstChannelMask;
6657 mDstSampleRate = dstSampleRate;
6658
6659 // compute derived parameters
6660 mSrcChannelCount = audio_channel_count_from_in_mask(srcChannelMask);
6661 mDstChannelCount = audio_channel_count_from_in_mask(dstChannelMask);
6662 mDstFrameSize = mDstChannelCount * audio_bytes_per_sample(mDstFormat);
6663
Andy Hungd330ee42015-04-20 13:23:41 -07006664 // do we need to resample?
6665 delete mResampler;
6666 mResampler = NULL;
6667 if (mSrcSampleRate != mDstSampleRate) {
6668 mResampler = AudioResampler::create(AUDIO_FORMAT_PCM_FLOAT,
6669 mSrcChannelCount, mDstSampleRate);
6670 mResampler->setSampleRate(mSrcSampleRate);
6671 mResampler->setVolume(AudioMixer::UNITY_GAIN_FLOAT, AudioMixer::UNITY_GAIN_FLOAT);
6672 }
6673
6674 // are we running legacy channel conversion modes?
6675 mIsLegacyDownmix = (mSrcChannelMask == AUDIO_CHANNEL_IN_STEREO
6676 || mSrcChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK)
6677 && mDstChannelMask == AUDIO_CHANNEL_IN_MONO;
6678 mIsLegacyUpmix = mSrcChannelMask == AUDIO_CHANNEL_IN_MONO
6679 && (mDstChannelMask == AUDIO_CHANNEL_IN_STEREO
6680 || mDstChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK);
6681
6682 // do we need to process in float?
6683 mRequiresFloat = mResampler != NULL || mIsLegacyDownmix || mIsLegacyUpmix;
6684
6685 // do we need a staging buffer to convert for destination (we can still optimize this)?
6686 // we use mBufFrameSize > 0 to indicate both frame size as well as buffer necessity
6687 if (mResampler != NULL) {
6688 mBufFrameSize = max(mSrcChannelCount, FCC_2)
6689 * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
Andy Hunga97630b2015-07-22 23:27:24 -07006690 } else if (mIsLegacyUpmix || mIsLegacyDownmix) { // legacy modes always float
Andy Hungd330ee42015-04-20 13:23:41 -07006691 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
6692 } else if (mSrcChannelMask != mDstChannelMask && mDstFormat != mSrcFormat) {
Andy Hung97a893e2015-03-29 01:03:07 -07006693 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(mSrcFormat);
6694 } else {
6695 mBufFrameSize = 0;
6696 }
6697 mBufFrames = 0; // force the buffer to be resized.
6698
Andy Hungd330ee42015-04-20 13:23:41 -07006699 // do we need an input converter buffer provider to give us float?
6700 delete mInputConverterProvider;
6701 mInputConverterProvider = NULL;
6702 if (mRequiresFloat && mSrcFormat != AUDIO_FORMAT_PCM_FLOAT) {
6703 mInputConverterProvider = new ReformatBufferProvider(
6704 audio_channel_count_from_in_mask(mSrcChannelMask),
6705 mSrcFormat,
6706 AUDIO_FORMAT_PCM_FLOAT,
6707 256 /* provider buffer frame count */);
6708 }
6709
6710 // do we need a remixer to do channel mask conversion
6711 if (!mIsLegacyDownmix && !mIsLegacyUpmix && mSrcChannelMask != mDstChannelMask) {
6712 (void) memcpy_by_index_array_initialization_from_channel_mask(
6713 mIdxAry, ARRAY_SIZE(mIdxAry), mDstChannelMask, mSrcChannelMask);
Andy Hung97a893e2015-03-29 01:03:07 -07006714 }
6715 return NO_ERROR;
6716}
6717
Andy Hungd330ee42015-04-20 13:23:41 -07006718void AudioFlinger::RecordThread::RecordBufferConverter::convertNoResampler(
6719 void *dst, const void *src, size_t frames)
Andy Hung97a893e2015-03-29 01:03:07 -07006720{
Andy Hungd330ee42015-04-20 13:23:41 -07006721 // src is native type unless there is legacy upmix or downmix, whereupon it is float.
Andy Hung97a893e2015-03-29 01:03:07 -07006722 if (mBufFrameSize != 0 && mBufFrames < frames) {
6723 free(mBuf);
6724 mBufFrames = frames;
6725 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
6726 }
Andy Hungd330ee42015-04-20 13:23:41 -07006727 // do we need to do legacy upmix and downmix?
6728 if (mIsLegacyUpmix || mIsLegacyDownmix) {
Andy Hung97a893e2015-03-29 01:03:07 -07006729 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07006730 if (mIsLegacyUpmix) {
6731 upmix_to_stereo_float_from_mono_float((float *)dstBuf,
6732 (const float *)src, frames);
6733 } else /*mIsLegacyDownmix */ {
6734 downmix_to_mono_float_from_stereo_float((float *)dstBuf,
6735 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006736 }
Andy Hungd330ee42015-04-20 13:23:41 -07006737 if (mBuf != NULL) {
6738 memcpy_by_audio_format(dst, mDstFormat, mBuf, AUDIO_FORMAT_PCM_FLOAT,
6739 frames * mDstChannelCount);
6740 }
6741 return;
6742 }
6743 // do we need to do channel mask conversion?
6744 if (mSrcChannelMask != mDstChannelMask) {
Andy Hung97a893e2015-03-29 01:03:07 -07006745 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07006746 memcpy_by_index_array(dstBuf, mDstChannelCount,
6747 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mSrcFormat), frames);
6748 if (dstBuf == dst) {
6749 return; // format is the same
6750 }
6751 }
6752 // convert to destination buffer
6753 const void *convertBuf = mBuf != NULL ? mBuf : src;
6754 memcpy_by_audio_format(dst, mDstFormat, convertBuf, mSrcFormat,
6755 frames * mDstChannelCount);
6756}
6757
6758void AudioFlinger::RecordThread::RecordBufferConverter::convertResampler(
6759 void *dst, /*not-a-const*/ void *src, size_t frames)
6760{
6761 // src buffer format is ALWAYS float when entering this routine
6762 if (mIsLegacyUpmix) {
6763 ; // mono to stereo already handled by resampler
6764 } else if (mIsLegacyDownmix
6765 || (mSrcChannelMask == mDstChannelMask && mSrcChannelCount == 1)) {
6766 // the resampler outputs stereo for mono input channel (a feature?)
6767 // must convert to mono
6768 downmix_to_mono_float_from_stereo_float((float *)src,
6769 (const float *)src, frames);
6770 } else if (mSrcChannelMask != mDstChannelMask) {
6771 // convert to mono channel again for channel mask conversion (could be skipped
6772 // with further optimization).
Andy Hung97a893e2015-03-29 01:03:07 -07006773 if (mSrcChannelCount == 1) {
Andy Hungd330ee42015-04-20 13:23:41 -07006774 downmix_to_mono_float_from_stereo_float((float *)src,
6775 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006776 }
Andy Hungd330ee42015-04-20 13:23:41 -07006777 // convert to destination format (in place, OK as float is larger than other types)
6778 if (mDstFormat != AUDIO_FORMAT_PCM_FLOAT) {
6779 memcpy_by_audio_format(src, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
6780 frames * mSrcChannelCount);
6781 }
6782 // channel convert and save to dst
6783 memcpy_by_index_array(dst, mDstChannelCount,
6784 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mDstFormat), frames);
6785 return;
Andy Hung97a893e2015-03-29 01:03:07 -07006786 }
Andy Hungd330ee42015-04-20 13:23:41 -07006787 // convert to destination format and save to dst
6788 memcpy_by_audio_format(dst, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
6789 frames * mDstChannelCount);
Andy Hung97a893e2015-03-29 01:03:07 -07006790}
6791
Eric Laurent10351942014-05-08 18:49:52 -07006792bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
6793 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006794{
6795 bool reconfig = false;
6796
Eric Laurent10351942014-05-08 18:49:52 -07006797 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006798
Eric Laurent10351942014-05-08 18:49:52 -07006799 audio_format_t reqFormat = mFormat;
6800 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07006801 // 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 -07006802 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
6803
6804 AudioParameter param = AudioParameter(keyValuePair);
6805 int value;
6806 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
6807 // channel count change can be requested. Do we mandate the first client defines the
6808 // HAL sampling rate and channel count or do we allow changes on the fly?
6809 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6810 samplingRate = value;
6811 reconfig = true;
6812 }
6813 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07006814 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07006815 status = BAD_VALUE;
6816 } else {
6817 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08006818 reconfig = true;
6819 }
Eric Laurent10351942014-05-08 18:49:52 -07006820 }
6821 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
6822 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07006823 if (!audio_is_input_channel(mask) ||
6824 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07006825 status = BAD_VALUE;
6826 } else {
6827 channelMask = mask;
6828 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006829 }
Eric Laurent10351942014-05-08 18:49:52 -07006830 }
6831 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6832 // do not accept frame count changes if tracks are open as the track buffer
6833 // size depends on frame count and correct behavior would not be guaranteed
6834 // if frame count is changed after track creation
6835 if (mActiveTracks.size() > 0) {
6836 status = INVALID_OPERATION;
6837 } else {
6838 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006839 }
Eric Laurent10351942014-05-08 18:49:52 -07006840 }
6841 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6842 // forward device change to effects that have requested to be
6843 // aware of attached audio device.
6844 for (size_t i = 0; i < mEffectChains.size(); i++) {
6845 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08006846 }
Eric Laurent81784c32012-11-19 14:55:58 -08006847
Eric Laurent10351942014-05-08 18:49:52 -07006848 // store input device and output device but do not forward output device to audio HAL.
6849 // Note that status is ignored by the caller for output device
6850 // (see AudioFlinger::setParameters()
6851 if (audio_is_output_devices(value)) {
6852 mOutDevice = value;
6853 status = BAD_VALUE;
6854 } else {
6855 mInDevice = value;
Eric Laurente8726fe2015-06-26 09:39:24 -07006856 if (value != AUDIO_DEVICE_NONE) {
6857 mPrevInDevice = value;
6858 }
Eric Laurent10351942014-05-08 18:49:52 -07006859 // disable AEC and NS if the device is a BT SCO headset supporting those
6860 // pre processings
6861 if (mTracks.size() > 0) {
6862 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6863 mAudioFlinger->btNrecIsOff();
6864 for (size_t i = 0; i < mTracks.size(); i++) {
6865 sp<RecordTrack> track = mTracks[i];
6866 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
6867 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08006868 }
6869 }
6870 }
Eric Laurent10351942014-05-08 18:49:52 -07006871 }
6872 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
6873 mAudioSource != (audio_source_t)value) {
6874 // forward device change to effects that have requested to be
6875 // aware of attached audio device.
6876 for (size_t i = 0; i < mEffectChains.size(); i++) {
6877 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08006878 }
Eric Laurent10351942014-05-08 18:49:52 -07006879 mAudioSource = (audio_source_t)value;
6880 }
Glenn Kastene198c362013-08-13 09:13:36 -07006881
Eric Laurent10351942014-05-08 18:49:52 -07006882 if (status == NO_ERROR) {
6883 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6884 keyValuePair.string());
6885 if (status == INVALID_OPERATION) {
6886 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006887 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6888 keyValuePair.string());
Eric Laurent10351942014-05-08 18:49:52 -07006889 }
6890 if (reconfig) {
6891 if (status == BAD_VALUE &&
Andy Hung97a893e2015-03-29 01:03:07 -07006892 audio_is_linear_pcm(mInput->stream->common.get_format(&mInput->stream->common)) &&
6893 audio_is_linear_pcm(reqFormat) &&
Eric Laurent10351942014-05-08 18:49:52 -07006894 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
Andy Hung97a893e2015-03-29 01:03:07 -07006895 <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate)) &&
Andy Hunge5412692014-05-16 11:25:07 -07006896 audio_channel_count_from_in_mask(
Andy Hungd1abb8f2015-05-05 23:42:34 -07006897 mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07006898 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006899 }
Eric Laurent10351942014-05-08 18:49:52 -07006900 if (status == NO_ERROR) {
6901 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07006902 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08006903 }
6904 }
Eric Laurent81784c32012-11-19 14:55:58 -08006905 }
Eric Laurent10351942014-05-08 18:49:52 -07006906
Eric Laurent81784c32012-11-19 14:55:58 -08006907 return reconfig;
6908}
6909
6910String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6911{
Eric Laurent81784c32012-11-19 14:55:58 -08006912 Mutex::Autolock _l(mLock);
6913 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07006914 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08006915 }
6916
Glenn Kastend8ea6992013-07-16 14:17:15 -07006917 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
6918 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08006919 free(s);
6920 return out_s8;
6921}
6922
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07006923void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07006924 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
6925
6926 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08006927
6928 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07006929 case AUDIO_INPUT_OPENED:
6930 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07006931 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07006932 desc->mChannelMask = mChannelMask;
6933 desc->mSamplingRate = mSampleRate;
6934 desc->mFormat = mFormat;
6935 desc->mFrameCount = mFrameCount;
6936 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006937 break;
6938
Eric Laurent73e26b62015-04-27 16:55:58 -07006939 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08006940 default:
6941 break;
6942 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07006943 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08006944}
6945
Glenn Kastendeca2ae2014-02-07 10:25:56 -08006946void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006947{
Eric Laurent81784c32012-11-19 14:55:58 -08006948 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
6949 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Andy Hunge5412692014-05-16 11:25:07 -07006950 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Andy Hungd330ee42015-04-20 13:23:41 -07006951 if (mChannelCount > FCC_8) {
6952 ALOGE("HAL channel count %d > %d", mChannelCount, FCC_8);
6953 }
Andy Hung463be252014-07-10 16:56:07 -07006954 mHALFormat = mInput->stream->common.get_format(&mInput->stream->common);
6955 mFormat = mHALFormat;
Andy Hungd330ee42015-04-20 13:23:41 -07006956 if (!audio_is_linear_pcm(mFormat)) {
6957 ALOGE("HAL format %#x is not linear pcm", mFormat);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07006958 }
Eric Laurent665470b2014-07-03 16:37:08 -07006959 mFrameSize = audio_stream_in_frame_size(mInput->stream);
Glenn Kasten548efc92012-11-29 08:48:51 -08006960 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
6961 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006962 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08006963 // 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 -07006964 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08006965 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006966 // A larger value should allow more old data to be read after a track calls start(),
6967 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07006968 //
6969 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08006970 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07006971 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07006972 free(mRsmpInBuffer);
Andy Hung4c6e77f2015-09-21 12:44:54 -07006973 mRsmpInBuffer = NULL;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006974
6975 // TODO optimize audio capture buffer sizes ...
6976 // Here we calculate the size of the sliding buffer used as a source
6977 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
6978 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
6979 // be better to have it derived from the pipe depth in the long term.
6980 // The current value is higher than necessary. However it should not add to latency.
6981
Glenn Kasten85948432013-08-19 12:09:05 -07006982 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Andy Hung4c6e77f2015-09-21 12:44:54 -07006983 size_t bufferSize = (mRsmpInFramesP2 + mFrameCount - 1) * mFrameSize;
6984 (void)posix_memalign(&mRsmpInBuffer, 32, bufferSize);
6985 memset(mRsmpInBuffer, 0, bufferSize); // if posix_memalign fails, will segv here.
Eric Laurent81784c32012-11-19 14:55:58 -08006986
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006987 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
6988 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08006989}
6990
Glenn Kasten5f972c02014-01-13 09:59:31 -08006991uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08006992{
6993 Mutex::Autolock _l(mLock);
6994 if (initCheck() != NO_ERROR) {
6995 return 0;
6996 }
6997
6998 return mInput->stream->get_input_frames_lost(mInput->stream);
6999}
7000
7001uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
7002{
7003 Mutex::Autolock _l(mLock);
7004 uint32_t result = 0;
7005 if (getEffectChain_l(sessionId) != 0) {
7006 result = EFFECT_SESSION;
7007 }
7008
7009 for (size_t i = 0; i < mTracks.size(); ++i) {
7010 if (sessionId == mTracks[i]->sessionId()) {
7011 result |= TRACK_SESSION;
7012 break;
7013 }
7014 }
7015
7016 return result;
7017}
7018
7019KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
7020{
7021 KeyedVector<int, bool> ids;
7022 Mutex::Autolock _l(mLock);
7023 for (size_t j = 0; j < mTracks.size(); ++j) {
7024 sp<RecordThread::RecordTrack> track = mTracks[j];
7025 int sessionId = track->sessionId();
7026 if (ids.indexOfKey(sessionId) < 0) {
7027 ids.add(sessionId, true);
7028 }
7029 }
7030 return ids;
7031}
7032
7033AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
7034{
7035 Mutex::Autolock _l(mLock);
7036 AudioStreamIn *input = mInput;
7037 mInput = NULL;
7038 return input;
7039}
7040
7041// this method must always be called either with ThreadBase mLock held or inside the thread loop
7042audio_stream_t* AudioFlinger::RecordThread::stream() const
7043{
7044 if (mInput == NULL) {
7045 return NULL;
7046 }
7047 return &mInput->stream->common;
7048}
7049
7050status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7051{
7052 // only one chain per input thread
7053 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07007054 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08007055 return INVALID_OPERATION;
7056 }
7057 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07007058 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08007059 chain->setInBuffer(NULL);
7060 chain->setOutBuffer(NULL);
7061
7062 checkSuspendOnAddEffectChain_l(chain);
7063
Eric Laurent1b928682014-10-02 19:41:47 -07007064 // make sure enabled pre processing effects state is communicated to the HAL as we
7065 // just moved them to a new input stream.
7066 chain->syncHalEffectsState();
7067
Eric Laurent81784c32012-11-19 14:55:58 -08007068 mEffectChains.add(chain);
7069
7070 return NO_ERROR;
7071}
7072
7073size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7074{
7075 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
7076 ALOGW_IF(mEffectChains.size() != 1,
7077 "removeEffectChain_l() %p invalid chain size %d on thread %p",
7078 chain.get(), mEffectChains.size(), this);
7079 if (mEffectChains.size() == 1) {
7080 mEffectChains.removeAt(0);
7081 }
7082 return 0;
7083}
7084
Eric Laurent1c333e22014-05-20 10:48:17 -07007085status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
7086 audio_patch_handle_t *handle)
7087{
7088 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007089
7090 // store new device and send to effects
7091 mInDevice = patch->sources[0].ext.device.type;
Eric Laurent296fb132015-05-01 11:38:42 -07007092 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07007093 for (size_t i = 0; i < mEffectChains.size(); i++) {
7094 mEffectChains[i]->setDevice_l(mInDevice);
7095 }
7096
7097 // disable AEC and NS if the device is a BT SCO headset supporting those
7098 // pre processings
7099 if (mTracks.size() > 0) {
7100 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7101 mAudioFlinger->btNrecIsOff();
7102 for (size_t i = 0; i < mTracks.size(); i++) {
7103 sp<RecordTrack> track = mTracks[i];
7104 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7105 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
7106 }
7107 }
7108
7109 // store new source and send to effects
7110 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7111 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07007112 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07007113 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07007114 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007115 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007116
Eric Laurent054d9d32015-04-24 08:48:48 -07007117 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007118 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
7119 status = hwDevice->create_audio_patch(hwDevice,
7120 patch->num_sources,
7121 patch->sources,
7122 patch->num_sinks,
7123 patch->sinks,
7124 handle);
7125 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007126 char *address;
7127 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
7128 address = audio_device_address_to_parameter(
7129 patch->sources[0].ext.device.type,
7130 patch->sources[0].ext.device.address);
7131 } else {
7132 address = (char *)calloc(1, 1);
7133 }
7134 AudioParameter param = AudioParameter(String8(address));
7135 free(address);
7136 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING),
7137 (int)patch->sources[0].ext.device.type);
7138 param.addInt(String8(AUDIO_PARAMETER_STREAM_INPUT_SOURCE),
7139 (int)patch->sinks[0].ext.mix.usecase.source);
7140 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7141 param.toString().string());
7142 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07007143 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007144
Eric Laurente8726fe2015-06-26 09:39:24 -07007145 if (mInDevice != mPrevInDevice) {
7146 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
7147 mPrevInDevice = mInDevice;
7148 }
Eric Laurent296fb132015-05-01 11:38:42 -07007149
Eric Laurent1c333e22014-05-20 10:48:17 -07007150 return status;
7151}
7152
7153status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
7154{
7155 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007156
7157 mInDevice = AUDIO_DEVICE_NONE;
7158
Eric Laurent1c333e22014-05-20 10:48:17 -07007159 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
7160 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
7161 status = hwDevice->release_audio_patch(hwDevice, handle);
7162 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007163 AudioParameter param;
7164 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
7165 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7166 param.toString().string());
Eric Laurent1c333e22014-05-20 10:48:17 -07007167 }
7168 return status;
7169}
7170
Eric Laurent83b88082014-06-20 18:31:16 -07007171void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
7172{
7173 Mutex::Autolock _l(mLock);
7174 mTracks.add(record);
7175}
7176
7177void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
7178{
7179 Mutex::Autolock _l(mLock);
7180 destroyTrack_l(record);
7181}
7182
7183void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
7184{
7185 ThreadBase::getAudioPortConfig(config);
7186 config->role = AUDIO_PORT_ROLE_SINK;
7187 config->ext.mix.hw_module = mInput->audioHwDev->handle();
7188 config->ext.mix.usecase.source = mAudioSource;
7189}
Eric Laurent1c333e22014-05-20 10:48:17 -07007190
Glenn Kasten63238ef2015-03-02 15:50:29 -08007191} // namespace android