blob: 602a0cfa3e90313ebfffd263dd6fe624ed4be4f2 [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",
Glenn Kasten937c3472015-09-28 10:21:06 -0700447 AUDIO_INPUT_FLAG_RAW, "RAW",
448 AUDIO_INPUT_FLAG_SYNC, "SYNC",
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800449 AUDIO_INPUT_FLAG_NONE, "NONE", // must be last
450 };
451 String8 result;
452 audio_input_flags_t allFlags = AUDIO_INPUT_FLAG_NONE;
453 const mapping *entry;
454 for (entry = mappings; entry->mFlag != AUDIO_INPUT_FLAG_NONE; entry++) {
455 allFlags = (audio_input_flags_t) (allFlags | entry->mFlag);
456 if (flags & entry->mFlag) {
457 if (!result.isEmpty()) {
458 result.append("|");
459 }
460 result.append(entry->mString);
461 }
462 }
463 if (flags & ~allFlags) {
464 if (!result.isEmpty()) {
465 result.append("|");
466 }
467 result.appendFormat("0x%X", flags & ~allFlags);
468 }
469 if (result.isEmpty()) {
470 result.append(entry->mString);
471 }
472 return result;
473}
474
475String8 outputFlagsToString(audio_output_flags_t flags)
Glenn Kasten97b7b752014-09-28 13:04:24 -0700476{
477 static const struct mapping {
478 audio_output_flags_t mFlag;
479 const char * mString;
480 } mappings[] = {
481 AUDIO_OUTPUT_FLAG_DIRECT, "DIRECT",
482 AUDIO_OUTPUT_FLAG_PRIMARY, "PRIMARY",
483 AUDIO_OUTPUT_FLAG_FAST, "FAST",
484 AUDIO_OUTPUT_FLAG_DEEP_BUFFER, "DEEP_BUFFER",
Glenn Kastendfb0e112015-02-18 14:33:39 -0800485 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD, "COMPRESS_OFFLOAD",
Glenn Kasten97b7b752014-09-28 13:04:24 -0700486 AUDIO_OUTPUT_FLAG_NON_BLOCKING, "NON_BLOCKING",
487 AUDIO_OUTPUT_FLAG_HW_AV_SYNC, "HW_AV_SYNC",
Glenn Kasten937c3472015-09-28 10:21:06 -0700488 AUDIO_OUTPUT_FLAG_RAW, "RAW",
489 AUDIO_OUTPUT_FLAG_SYNC, "SYNC",
490 AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO, "IEC958_NONAUDIO",
Glenn Kasten97b7b752014-09-28 13:04:24 -0700491 AUDIO_OUTPUT_FLAG_NONE, "NONE", // must be last
492 };
493 String8 result;
494 audio_output_flags_t allFlags = AUDIO_OUTPUT_FLAG_NONE;
495 const mapping *entry;
496 for (entry = mappings; entry->mFlag != AUDIO_OUTPUT_FLAG_NONE; entry++) {
497 allFlags = (audio_output_flags_t) (allFlags | entry->mFlag);
498 if (flags & entry->mFlag) {
499 if (!result.isEmpty()) {
500 result.append("|");
501 }
502 result.append(entry->mString);
503 }
504 }
505 if (flags & ~allFlags) {
506 if (!result.isEmpty()) {
507 result.append("|");
508 }
509 result.appendFormat("0x%X", flags & ~allFlags);
510 }
511 if (result.isEmpty()) {
512 result.append(entry->mString);
513 }
514 return result;
515}
516
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800517const char *sourceToString(audio_source_t source)
518{
519 switch (source) {
520 case AUDIO_SOURCE_DEFAULT: return "default";
521 case AUDIO_SOURCE_MIC: return "mic";
522 case AUDIO_SOURCE_VOICE_UPLINK: return "voice uplink";
523 case AUDIO_SOURCE_VOICE_DOWNLINK: return "voice downlink";
524 case AUDIO_SOURCE_VOICE_CALL: return "voice call";
525 case AUDIO_SOURCE_CAMCORDER: return "camcorder";
526 case AUDIO_SOURCE_VOICE_RECOGNITION: return "voice recognition";
527 case AUDIO_SOURCE_VOICE_COMMUNICATION: return "voice communication";
528 case AUDIO_SOURCE_REMOTE_SUBMIX: return "remote submix";
529 case AUDIO_SOURCE_FM_TUNER: return "FM tuner";
530 case AUDIO_SOURCE_HOTWORD: return "hotword";
531 default: return "unknown";
532 }
533}
534
Eric Laurent81784c32012-11-19 14:55:58 -0800535AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -0700536 audio_devices_t outDevice, audio_devices_t inDevice, type_t type, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -0800537 : Thread(false /*canCallJava*/),
538 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700539 mAudioFlinger(audioFlinger),
Glenn Kasten70949c42013-08-06 07:40:12 -0700540 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800541 // are set by PlaybackThread::readOutputParameters_l() or
542 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700543 //FIXME: mStandby should be true here. Is this some kind of hack?
Eric Laurent81784c32012-11-19 14:55:58 -0800544 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700545 mPrevOutDevice(AUDIO_DEVICE_NONE), mPrevInDevice(AUDIO_DEVICE_NONE),
546 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Eric Laurent81784c32012-11-19 14:55:58 -0800547 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700548 mDeathRecipient(new PMDeathRecipient(this)),
549 mSystemReady(systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -0800550{
Eric Laurent296fb132015-05-01 11:38:42 -0700551 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800552}
553
554AudioFlinger::ThreadBase::~ThreadBase()
555{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700556 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700557 mConfigEvents.clear();
558
Eric Laurent81784c32012-11-19 14:55:58 -0800559 // do not lock the mutex in destructor
560 releaseWakeLock_l();
561 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800562 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800563 binder->unlinkToDeath(mDeathRecipient);
564 }
565}
566
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700567status_t AudioFlinger::ThreadBase::readyToRun()
568{
569 status_t status = initCheck();
570 if (status == NO_ERROR) {
571 ALOGI("AudioFlinger's thread %p ready to run", this);
572 } else {
573 ALOGE("No working audio driver found.");
574 }
575 return status;
576}
577
Eric Laurent81784c32012-11-19 14:55:58 -0800578void AudioFlinger::ThreadBase::exit()
579{
580 ALOGV("ThreadBase::exit");
581 // do any cleanup required for exit to succeed
582 preExit();
583 {
584 // This lock prevents the following race in thread (uniprocessor for illustration):
585 // if (!exitPending()) {
586 // // context switch from here to exit()
587 // // exit() calls requestExit(), what exitPending() observes
588 // // exit() calls signal(), which is dropped since no waiters
589 // // context switch back from exit() to here
590 // mWaitWorkCV.wait(...);
591 // // now thread is hung
592 // }
593 AutoMutex lock(mLock);
594 requestExit();
595 mWaitWorkCV.broadcast();
596 }
597 // When Thread::requestExitAndWait is made virtual and this method is renamed to
598 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
599 requestExitAndWait();
600}
601
602status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
603{
604 status_t status;
605
606 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
607 Mutex::Autolock _l(mLock);
608
Eric Laurent10351942014-05-08 18:49:52 -0700609 return sendSetParameterConfigEvent_l(keyValuePairs);
610}
611
612// sendConfigEvent_l() must be called with ThreadBase::mLock held
613// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
614status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
615{
616 status_t status = NO_ERROR;
617
Eric Laurent72e3f392015-05-20 14:43:50 -0700618 if (event->mRequiresSystemReady && !mSystemReady) {
619 event->mWaitStatus = false;
620 mPendingConfigEvents.add(event);
621 return status;
622 }
Eric Laurent10351942014-05-08 18:49:52 -0700623 mConfigEvents.add(event);
624 ALOGV("sendConfigEvent_l() num events %d event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800625 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700626 mLock.unlock();
627 {
628 Mutex::Autolock _l(event->mLock);
629 while (event->mWaitStatus) {
630 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
631 event->mStatus = TIMED_OUT;
632 event->mWaitStatus = false;
633 }
634 }
635 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800636 }
Eric Laurent10351942014-05-08 18:49:52 -0700637 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800638 return status;
639}
640
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700641void AudioFlinger::ThreadBase::sendIoConfigEvent(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800642{
643 Mutex::Autolock _l(mLock);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700644 sendIoConfigEvent_l(event, pid);
Eric Laurent81784c32012-11-19 14:55:58 -0800645}
646
647// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700648void AudioFlinger::ThreadBase::sendIoConfigEvent_l(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800649{
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700650 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid);
Eric Laurent10351942014-05-08 18:49:52 -0700651 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800652}
653
Eric Laurent72e3f392015-05-20 14:43:50 -0700654void AudioFlinger::ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio)
655{
656 Mutex::Autolock _l(mLock);
657 sendPrioConfigEvent_l(pid, tid, prio);
658}
659
Eric Laurent81784c32012-11-19 14:55:58 -0800660// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
661void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
662{
Eric Laurent10351942014-05-08 18:49:52 -0700663 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio);
664 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800665}
666
Eric Laurent10351942014-05-08 18:49:52 -0700667// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
668status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800669{
Eric Laurent10351942014-05-08 18:49:52 -0700670 sp<ConfigEvent> configEvent = (ConfigEvent *)new SetParameterConfigEvent(keyValuePair);
671 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700672}
673
Eric Laurent1c333e22014-05-20 10:48:17 -0700674status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
675 const struct audio_patch *patch,
676 audio_patch_handle_t *handle)
677{
678 Mutex::Autolock _l(mLock);
679 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
680 status_t status = sendConfigEvent_l(configEvent);
681 if (status == NO_ERROR) {
682 CreateAudioPatchConfigEventData *data =
683 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
684 *handle = data->mHandle;
685 }
686 return status;
687}
688
689status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
690 const audio_patch_handle_t handle)
691{
692 Mutex::Autolock _l(mLock);
693 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
694 return sendConfigEvent_l(configEvent);
695}
696
697
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700698// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700699void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700700{
Eric Laurent10351942014-05-08 18:49:52 -0700701 bool configChanged = false;
702
Eric Laurent81784c32012-11-19 14:55:58 -0800703 while (!mConfigEvents.isEmpty()) {
Eric Laurent10351942014-05-08 18:49:52 -0700704 ALOGV("processConfigEvents_l() remaining events %d", mConfigEvents.size());
705 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800706 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700707 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700708 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700709 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
710 // FIXME Need to understand why this has to be done asynchronously
711 int err = requestPriority(data->mPid, data->mTid, data->mPrio,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700712 true /*asynchronous*/);
713 if (err != 0) {
714 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700715 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700716 }
717 } break;
718 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700719 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700720 ioConfigChanged(data->mEvent, data->mPid);
Eric Laurent10351942014-05-08 18:49:52 -0700721 } break;
722 case CFG_EVENT_SET_PARAMETER: {
723 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
724 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
725 configChanged = true;
Glenn Kastend5418eb2013-08-14 13:11:06 -0700726 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700727 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700728 case CFG_EVENT_CREATE_AUDIO_PATCH: {
729 CreateAudioPatchConfigEventData *data =
730 (CreateAudioPatchConfigEventData *)event->mData.get();
731 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
732 } break;
733 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
734 ReleaseAudioPatchConfigEventData *data =
735 (ReleaseAudioPatchConfigEventData *)event->mData.get();
736 event->mStatus = releaseAudioPatch_l(data->mHandle);
737 } break;
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700738 default:
Eric Laurent10351942014-05-08 18:49:52 -0700739 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700740 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800741 }
Eric Laurent10351942014-05-08 18:49:52 -0700742 {
743 Mutex::Autolock _l(event->mLock);
744 if (event->mWaitStatus) {
745 event->mWaitStatus = false;
746 event->mCond.signal();
747 }
748 }
749 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
750 }
751
752 if (configChanged) {
753 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800754 }
Eric Laurent81784c32012-11-19 14:55:58 -0800755}
756
Marco Nelissenb2208842014-02-07 14:00:50 -0800757String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
758 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700759 const audio_channel_representation_t representation =
760 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700761
762 switch (representation) {
763 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
764 if (output) {
765 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
766 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
767 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
768 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
769 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
770 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
771 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
772 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
773 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
774 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
775 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
776 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
777 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
778 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
779 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
780 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
781 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
782 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
783 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
784 } else {
785 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
786 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
787 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
788 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
789 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
790 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
791 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
792 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
793 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
794 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
795 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
796 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
797 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
798 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
799 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
800 }
801 const int len = s.length();
802 if (len > 2) {
803 char *str = s.lockBuffer(len); // needed?
804 s.unlockBuffer(len - 2); // remove trailing ", "
805 }
806 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800807 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700808 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
809 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
810 return s;
811 default:
812 s.appendFormat("unknown mask, representation:%d bits:%#x",
813 representation, audio_channel_mask_get_bits(mask));
814 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800815 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800816}
817
Glenn Kasten0f11b512014-01-31 16:18:54 -0800818void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800819{
820 const size_t SIZE = 256;
821 char buffer[SIZE];
822 String8 result;
823
824 bool locked = AudioFlinger::dumpTryLock(mLock);
825 if (!locked) {
Glenn Kasten97b7b752014-09-28 13:04:24 -0700826 dprintf(fd, "thread %p may be deadlocked\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -0800827 }
828
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800829 dprintf(fd, " Thread name: %s\n", mThreadName);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700830 dprintf(fd, " I/O handle: %d\n", mId);
831 dprintf(fd, " TID: %d\n", getTid());
832 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700833 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700834 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700835 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat));
Elliott Hughes87cebad2014-05-22 10:14:43 -0700836 dprintf(fd, " HAL buffer size: %u bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700837 dprintf(fd, " Channel count: %u\n", mChannelCount);
838 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800839 channelMaskToString(mChannelMask, mType != RECORD).string());
Glenn Kastenf87c2f52015-08-21 08:03:57 -0700840 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat, formatToString(mFormat));
841 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700842 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800843 size_t numConfig = mConfigEvents.size();
844 if (numConfig) {
845 for (size_t i = 0; i < numConfig; i++) {
846 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700847 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800848 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700849 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800850 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700851 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800852 }
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800853 dprintf(fd, " Output device: %#x (%s)\n", mOutDevice, devicesToString(mOutDevice).string());
854 dprintf(fd, " Input device: %#x (%s)\n", mInDevice, devicesToString(mInDevice).string());
855 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, sourceToString(mAudioSource));
Eric Laurent81784c32012-11-19 14:55:58 -0800856
857 if (locked) {
858 mLock.unlock();
859 }
860}
861
862void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
863{
864 const size_t SIZE = 256;
865 char buffer[SIZE];
866 String8 result;
867
Marco Nelissenb2208842014-02-07 14:00:50 -0800868 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000869 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800870 write(fd, buffer, strlen(buffer));
871
Marco Nelissenb2208842014-02-07 14:00:50 -0800872 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800873 sp<EffectChain> chain = mEffectChains[i];
874 if (chain != 0) {
875 chain->dump(fd, args);
876 }
877 }
878}
879
Marco Nelissene14a5d62013-10-03 08:51:24 -0700880void AudioFlinger::ThreadBase::acquireWakeLock(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800881{
882 Mutex::Autolock _l(mLock);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700883 acquireWakeLock_l(uid);
Eric Laurent81784c32012-11-19 14:55:58 -0800884}
885
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100886String16 AudioFlinger::ThreadBase::getWakeLockTag()
887{
888 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -0800889 case MIXER:
890 return String16("AudioMix");
891 case DIRECT:
892 return String16("AudioDirectOut");
893 case DUPLICATING:
894 return String16("AudioDup");
895 case RECORD:
896 return String16("AudioIn");
897 case OFFLOAD:
898 return String16("AudioOffload");
899 default:
900 ALOG_ASSERT(false);
901 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100902 }
903}
904
Marco Nelissene14a5d62013-10-03 08:51:24 -0700905void AudioFlinger::ThreadBase::acquireWakeLock_l(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800906{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800907 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800908 if (mPowerManager != 0) {
909 sp<IBinder> binder = new BBinder();
Marco Nelissene14a5d62013-10-03 08:51:24 -0700910 status_t status;
911 if (uid >= 0) {
Eric Laurent547789d2013-10-04 11:46:55 -0700912 status = mPowerManager->acquireWakeLockWithUid(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700913 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100914 getWakeLockTag(),
Marco Nelissene14a5d62013-10-03 08:51:24 -0700915 String16("media"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700916 uid,
917 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700918 } else {
Eric Laurent547789d2013-10-04 11:46:55 -0700919 status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700920 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100921 getWakeLockTag(),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700922 String16("media"),
923 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700924 }
Eric Laurent81784c32012-11-19 14:55:58 -0800925 if (status == NO_ERROR) {
926 mWakeLockToken = binder;
927 }
Glenn Kastend7dca052015-03-05 16:05:54 -0800928 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Eric Laurent81784c32012-11-19 14:55:58 -0800929 }
930}
931
932void AudioFlinger::ThreadBase::releaseWakeLock()
933{
934 Mutex::Autolock _l(mLock);
935 releaseWakeLock_l();
936}
937
938void AudioFlinger::ThreadBase::releaseWakeLock_l()
939{
940 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800941 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -0800942 if (mPowerManager != 0) {
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700943 mPowerManager->releaseWakeLock(mWakeLockToken, 0,
944 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800945 }
946 mWakeLockToken.clear();
947 }
948}
949
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800950void AudioFlinger::ThreadBase::updateWakeLockUids(const SortedVector<int> &uids) {
951 Mutex::Autolock _l(mLock);
952 updateWakeLockUids_l(uids);
953}
954
955void AudioFlinger::ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -0700956 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800957 // use checkService() to avoid blocking if power service is not up yet
958 sp<IBinder> binder =
959 defaultServiceManager()->checkService(String16("power"));
960 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800961 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800962 } else {
963 mPowerManager = interface_cast<IPowerManager>(binder);
964 binder->linkToDeath(mDeathRecipient);
965 }
966 }
967}
968
969void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<int> &uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800970 getPowerManager_l();
971 if (mWakeLockToken == NULL) {
972 ALOGE("no wake lock to update!");
973 return;
974 }
975 if (mPowerManager != 0) {
976 sp<IBinder> binder = new BBinder();
977 status_t status;
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700978 status = mPowerManager->updateWakeLockUids(mWakeLockToken, uids.size(), uids.array(),
979 true /* FIXME force oneway contrary to .aidl */);
Glenn Kastend7dca052015-03-05 16:05:54 -0800980 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800981 }
982}
983
Eric Laurent81784c32012-11-19 14:55:58 -0800984void AudioFlinger::ThreadBase::clearPowerManager()
985{
986 Mutex::Autolock _l(mLock);
987 releaseWakeLock_l();
988 mPowerManager.clear();
989}
990
Glenn Kasten0f11b512014-01-31 16:18:54 -0800991void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800992{
993 sp<ThreadBase> thread = mThread.promote();
994 if (thread != 0) {
995 thread->clearPowerManager();
996 }
997 ALOGW("power manager service died !!!");
998}
999
1000void AudioFlinger::ThreadBase::setEffectSuspended(
1001 const effect_uuid_t *type, bool suspend, int sessionId)
1002{
1003 Mutex::Autolock _l(mLock);
1004 setEffectSuspended_l(type, suspend, sessionId);
1005}
1006
1007void AudioFlinger::ThreadBase::setEffectSuspended_l(
1008 const effect_uuid_t *type, bool suspend, int sessionId)
1009{
1010 sp<EffectChain> chain = getEffectChain_l(sessionId);
1011 if (chain != 0) {
1012 if (type != NULL) {
1013 chain->setEffectSuspended_l(type, suspend);
1014 } else {
1015 chain->setEffectSuspendedAll_l(suspend);
1016 }
1017 }
1018
1019 updateSuspendedSessions_l(type, suspend, sessionId);
1020}
1021
1022void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1023{
1024 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1025 if (index < 0) {
1026 return;
1027 }
1028
1029 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1030 mSuspendedSessions.valueAt(index);
1031
1032 for (size_t i = 0; i < sessionEffects.size(); i++) {
1033 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
1034 for (int j = 0; j < desc->mRefCount; j++) {
1035 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1036 chain->setEffectSuspendedAll_l(true);
1037 } else {
1038 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1039 desc->mType.timeLow);
1040 chain->setEffectSuspended_l(&desc->mType, true);
1041 }
1042 }
1043 }
1044}
1045
1046void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1047 bool suspend,
1048 int sessionId)
1049{
1050 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1051
1052 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1053
1054 if (suspend) {
1055 if (index >= 0) {
1056 sessionEffects = mSuspendedSessions.valueAt(index);
1057 } else {
1058 mSuspendedSessions.add(sessionId, sessionEffects);
1059 }
1060 } else {
1061 if (index < 0) {
1062 return;
1063 }
1064 sessionEffects = mSuspendedSessions.valueAt(index);
1065 }
1066
1067
1068 int key = EffectChain::kKeyForSuspendAll;
1069 if (type != NULL) {
1070 key = type->timeLow;
1071 }
1072 index = sessionEffects.indexOfKey(key);
1073
1074 sp<SuspendedSessionDesc> desc;
1075 if (suspend) {
1076 if (index >= 0) {
1077 desc = sessionEffects.valueAt(index);
1078 } else {
1079 desc = new SuspendedSessionDesc();
1080 if (type != NULL) {
1081 desc->mType = *type;
1082 }
1083 sessionEffects.add(key, desc);
1084 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1085 }
1086 desc->mRefCount++;
1087 } else {
1088 if (index < 0) {
1089 return;
1090 }
1091 desc = sessionEffects.valueAt(index);
1092 if (--desc->mRefCount == 0) {
1093 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1094 sessionEffects.removeItemsAt(index);
1095 if (sessionEffects.isEmpty()) {
1096 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1097 sessionId);
1098 mSuspendedSessions.removeItem(sessionId);
1099 }
1100 }
1101 }
1102 if (!sessionEffects.isEmpty()) {
1103 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1104 }
1105}
1106
1107void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1108 bool enabled,
1109 int sessionId)
1110{
1111 Mutex::Autolock _l(mLock);
1112 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1113}
1114
1115void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1116 bool enabled,
1117 int sessionId)
1118{
1119 if (mType != RECORD) {
1120 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1121 // another session. This gives the priority to well behaved effect control panels
1122 // and applications not using global effects.
1123 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1124 // global effects
1125 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
1126 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1127 }
1128 }
1129
1130 sp<EffectChain> chain = getEffectChain_l(sessionId);
1131 if (chain != 0) {
1132 chain->checkSuspendOnEffectEnabled(effect, enabled);
1133 }
1134}
1135
1136// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1137sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1138 const sp<AudioFlinger::Client>& client,
1139 const sp<IEffectClient>& effectClient,
1140 int32_t priority,
1141 int sessionId,
1142 effect_descriptor_t *desc,
1143 int *enabled,
Glenn Kasten9156ef32013-08-06 15:39:08 -07001144 status_t *status)
Eric Laurent81784c32012-11-19 14:55:58 -08001145{
1146 sp<EffectModule> effect;
1147 sp<EffectHandle> handle;
1148 status_t lStatus;
1149 sp<EffectChain> chain;
1150 bool chainCreated = false;
1151 bool effectCreated = false;
1152 bool effectRegistered = false;
1153
1154 lStatus = initCheck();
1155 if (lStatus != NO_ERROR) {
1156 ALOGW("createEffect_l() Audio driver not initialized.");
1157 goto Exit;
1158 }
1159
Andy Hung98ef9782014-03-04 14:46:50 -08001160 // Reject any effect on Direct output threads for now, since the format of
1161 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1162 if (mType == DIRECT) {
1163 ALOGW("createEffect_l() Cannot add effect %s on Direct output type thread %s",
Glenn Kastend7dca052015-03-05 16:05:54 -08001164 desc->name, mThreadName);
Andy Hung98ef9782014-03-04 14:46:50 -08001165 lStatus = BAD_VALUE;
1166 goto Exit;
1167 }
1168
Andy Hung389cfdb2014-08-07 17:49:53 -07001169 // Reject any effect on mixer or duplicating multichannel sinks.
Andy Hung9a592762014-07-21 21:56:01 -07001170 // TODO: fix both format and multichannel issues with effects.
Andy Hung389cfdb2014-08-07 17:49:53 -07001171 if ((mType == MIXER || mType == DUPLICATING) && mChannelCount != FCC_2) {
1172 ALOGW("createEffect_l() Cannot add effect %s for multichannel(%d) %s threads",
1173 desc->name, mChannelCount, mType == MIXER ? "MIXER" : "DUPLICATING");
Andy Hung9a592762014-07-21 21:56:01 -07001174 lStatus = BAD_VALUE;
1175 goto Exit;
1176 }
1177
Eric Laurent5baf2af2013-09-12 17:37:00 -07001178 // Allow global effects only on offloaded and mixer threads
1179 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1180 switch (mType) {
1181 case MIXER:
1182 case OFFLOAD:
1183 break;
1184 case DIRECT:
1185 case DUPLICATING:
1186 case RECORD:
1187 default:
Glenn Kastend7dca052015-03-05 16:05:54 -08001188 ALOGW("createEffect_l() Cannot add global effect %s on thread %s",
1189 desc->name, mThreadName);
Eric Laurent5baf2af2013-09-12 17:37:00 -07001190 lStatus = BAD_VALUE;
1191 goto Exit;
1192 }
Eric Laurent81784c32012-11-19 14:55:58 -08001193 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07001194
Eric Laurent81784c32012-11-19 14:55:58 -08001195 // Only Pre processor effects are allowed on input threads and only on input threads
1196 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
1197 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
1198 desc->name, desc->flags, mType);
1199 lStatus = BAD_VALUE;
1200 goto Exit;
1201 }
1202
1203 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1204
1205 { // scope for mLock
1206 Mutex::Autolock _l(mLock);
1207
1208 // check for existing effect chain with the requested audio session
1209 chain = getEffectChain_l(sessionId);
1210 if (chain == 0) {
1211 // create a new chain for this session
1212 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1213 chain = new EffectChain(this, sessionId);
1214 addEffectChain_l(chain);
1215 chain->setStrategy(getStrategyForSession_l(sessionId));
1216 chainCreated = true;
1217 } else {
1218 effect = chain->getEffectFromDesc_l(desc);
1219 }
1220
1221 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1222
1223 if (effect == 0) {
1224 int id = mAudioFlinger->nextUniqueId();
1225 // Check CPU and memory usage
1226 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
1227 if (lStatus != NO_ERROR) {
1228 goto Exit;
1229 }
1230 effectRegistered = true;
1231 // create a new effect module if none present in the chain
1232 effect = new EffectModule(this, chain, desc, id, sessionId);
1233 lStatus = effect->status();
1234 if (lStatus != NO_ERROR) {
1235 goto Exit;
1236 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07001237 effect->setOffloaded(mType == OFFLOAD, mId);
1238
Eric Laurent81784c32012-11-19 14:55:58 -08001239 lStatus = chain->addEffect_l(effect);
1240 if (lStatus != NO_ERROR) {
1241 goto Exit;
1242 }
1243 effectCreated = true;
1244
1245 effect->setDevice(mOutDevice);
1246 effect->setDevice(mInDevice);
1247 effect->setMode(mAudioFlinger->getMode());
1248 effect->setAudioSource(mAudioSource);
1249 }
1250 // create effect handle and connect it to effect module
1251 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001252 lStatus = handle->initCheck();
1253 if (lStatus == OK) {
1254 lStatus = effect->addHandle(handle.get());
1255 }
Eric Laurent81784c32012-11-19 14:55:58 -08001256 if (enabled != NULL) {
1257 *enabled = (int)effect->isEnabled();
1258 }
1259 }
1260
1261Exit:
1262 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1263 Mutex::Autolock _l(mLock);
1264 if (effectCreated) {
1265 chain->removeEffect_l(effect);
1266 }
1267 if (effectRegistered) {
1268 AudioSystem::unregisterEffect(effect->id());
1269 }
1270 if (chainCreated) {
1271 removeEffectChain_l(chain);
1272 }
1273 handle.clear();
1274 }
1275
Glenn Kasten9156ef32013-08-06 15:39:08 -07001276 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001277 return handle;
1278}
1279
1280sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
1281{
1282 Mutex::Autolock _l(mLock);
1283 return getEffect_l(sessionId, effectId);
1284}
1285
1286sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
1287{
1288 sp<EffectChain> chain = getEffectChain_l(sessionId);
1289 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1290}
1291
1292// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1293// PlaybackThread::mLock held
1294status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1295{
1296 // check for existing effect chain with the requested audio session
1297 int sessionId = effect->sessionId();
1298 sp<EffectChain> chain = getEffectChain_l(sessionId);
1299 bool chainCreated = false;
1300
Eric Laurent5baf2af2013-09-12 17:37:00 -07001301 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
1302 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
1303 this, effect->desc().name, effect->desc().flags);
1304
Eric Laurent81784c32012-11-19 14:55:58 -08001305 if (chain == 0) {
1306 // create a new chain for this session
1307 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1308 chain = new EffectChain(this, sessionId);
1309 addEffectChain_l(chain);
1310 chain->setStrategy(getStrategyForSession_l(sessionId));
1311 chainCreated = true;
1312 }
1313 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1314
1315 if (chain->getEffectFromId_l(effect->id()) != 0) {
1316 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1317 this, effect->desc().name, chain.get());
1318 return BAD_VALUE;
1319 }
1320
Eric Laurent5baf2af2013-09-12 17:37:00 -07001321 effect->setOffloaded(mType == OFFLOAD, mId);
1322
Eric Laurent81784c32012-11-19 14:55:58 -08001323 status_t status = chain->addEffect_l(effect);
1324 if (status != NO_ERROR) {
1325 if (chainCreated) {
1326 removeEffectChain_l(chain);
1327 }
1328 return status;
1329 }
1330
1331 effect->setDevice(mOutDevice);
1332 effect->setDevice(mInDevice);
1333 effect->setMode(mAudioFlinger->getMode());
1334 effect->setAudioSource(mAudioSource);
1335 return NO_ERROR;
1336}
1337
1338void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
1339
1340 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
1341 effect_descriptor_t desc = effect->desc();
1342 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1343 detachAuxEffect_l(effect->id());
1344 }
1345
1346 sp<EffectChain> chain = effect->chain().promote();
1347 if (chain != 0) {
1348 // remove effect chain if removing last effect
1349 if (chain->removeEffect_l(effect) == 0) {
1350 removeEffectChain_l(chain);
1351 }
1352 } else {
1353 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1354 }
1355}
1356
1357void AudioFlinger::ThreadBase::lockEffectChains_l(
1358 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1359{
1360 effectChains = mEffectChains;
1361 for (size_t i = 0; i < mEffectChains.size(); i++) {
1362 mEffectChains[i]->lock();
1363 }
1364}
1365
1366void AudioFlinger::ThreadBase::unlockEffectChains(
1367 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1368{
1369 for (size_t i = 0; i < effectChains.size(); i++) {
1370 effectChains[i]->unlock();
1371 }
1372}
1373
1374sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
1375{
1376 Mutex::Autolock _l(mLock);
1377 return getEffectChain_l(sessionId);
1378}
1379
1380sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const
1381{
1382 size_t size = mEffectChains.size();
1383 for (size_t i = 0; i < size; i++) {
1384 if (mEffectChains[i]->sessionId() == sessionId) {
1385 return mEffectChains[i];
1386 }
1387 }
1388 return 0;
1389}
1390
1391void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1392{
1393 Mutex::Autolock _l(mLock);
1394 size_t size = mEffectChains.size();
1395 for (size_t i = 0; i < size; i++) {
1396 mEffectChains[i]->setMode_l(mode);
1397 }
1398}
1399
Eric Laurent83b88082014-06-20 18:31:16 -07001400void AudioFlinger::ThreadBase::getAudioPortConfig(struct audio_port_config *config)
1401{
1402 config->type = AUDIO_PORT_TYPE_MIX;
1403 config->ext.mix.handle = mId;
1404 config->sample_rate = mSampleRate;
1405 config->format = mFormat;
1406 config->channel_mask = mChannelMask;
1407 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1408 AUDIO_PORT_CONFIG_FORMAT;
1409}
1410
Eric Laurent72e3f392015-05-20 14:43:50 -07001411void AudioFlinger::ThreadBase::systemReady()
1412{
1413 Mutex::Autolock _l(mLock);
1414 if (mSystemReady) {
1415 return;
1416 }
1417 mSystemReady = true;
1418
1419 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1420 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1421 }
1422 mPendingConfigEvents.clear();
1423}
1424
Eric Laurent83b88082014-06-20 18:31:16 -07001425
Eric Laurent81784c32012-11-19 14:55:58 -08001426// ----------------------------------------------------------------------------
1427// Playback
1428// ----------------------------------------------------------------------------
1429
1430AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1431 AudioStreamOut* output,
1432 audio_io_handle_t id,
1433 audio_devices_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07001434 type_t type,
1435 bool systemReady)
1436 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type, systemReady),
Andy Hung2098f272014-02-27 14:00:06 -08001437 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001438 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001439 mMixerBuffer(NULL),
1440 mMixerBufferSize(0),
1441 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1442 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001443 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001444 mEffectBuffer(NULL),
1445 mEffectBufferSize(0),
1446 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1447 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001448 mSuspended(0), mBytesWritten(0),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001449 mActiveTracksGeneration(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001450 // mStreamTypes[] initialized in constructor body
1451 mOutput(output),
1452 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
1453 mMixerStatus(MIXER_IDLE),
1454 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001455 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001456 mBytesRemaining(0),
1457 mCurrentWriteLength(0),
1458 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001459 mWriteAckSequence(0),
1460 mDrainSequence(0),
Eric Laurentede6c3b2013-09-19 14:37:46 -07001461 mSignalPending(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001462 mScreenState(AudioFlinger::mScreenState),
1463 // index 0 is reserved for normal mixer's submix
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001464 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1),
Eric Laurentd1f69b02014-12-15 14:33:13 -08001465 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001466 // mLatchD, mLatchQ,
1467 mLatchDValid(false), mLatchQValid(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001468{
Glenn Kastend7dca052015-03-05 16:05:54 -08001469 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1470 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001471
1472 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1473 // it would be safer to explicitly pass initial masterVolume/masterMute as
1474 // parameter.
1475 //
1476 // If the HAL we are using has support for master volume or master mute,
1477 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1478 // and the mute set to false).
1479 mMasterVolume = audioFlinger->masterVolume_l();
1480 mMasterMute = audioFlinger->masterMute_l();
1481 if (mOutput && mOutput->audioHwDev) {
1482 if (mOutput->audioHwDev->canSetMasterVolume()) {
1483 mMasterVolume = 1.0;
1484 }
1485
1486 if (mOutput->audioHwDev->canSetMasterMute()) {
1487 mMasterMute = false;
1488 }
1489 }
1490
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001491 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001492
Eric Laurent223fd5c2014-11-11 13:43:36 -08001493 // ++ operator does not compile
Glenn Kasten66e46352014-01-16 17:44:23 -08001494 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001495 stream = (audio_stream_type_t) (stream + 1)) {
1496 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1497 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1498 }
Eric Laurent81784c32012-11-19 14:55:58 -08001499}
1500
1501AudioFlinger::PlaybackThread::~PlaybackThread()
1502{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001503 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001504 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001505 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001506 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001507}
1508
1509void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1510{
1511 dumpInternals(fd, args);
1512 dumpTracks(fd, args);
1513 dumpEffectChains(fd, args);
1514}
1515
Glenn Kasten0f11b512014-01-31 16:18:54 -08001516void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001517{
1518 const size_t SIZE = 256;
1519 char buffer[SIZE];
1520 String8 result;
1521
Marco Nelissenb2208842014-02-07 14:00:50 -08001522 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001523 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1524 const stream_type_t *st = &mStreamTypes[i];
1525 if (i > 0) {
1526 result.appendFormat(", ");
1527 }
1528 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1529 if (st->mute) {
1530 result.append("M");
1531 }
1532 }
1533 result.append("\n");
1534 write(fd, result.string(), result.length());
1535 result.clear();
1536
Eric Laurent81784c32012-11-19 14:55:58 -08001537 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1538 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001539 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001540 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001541
1542 size_t numtracks = mTracks.size();
1543 size_t numactive = mActiveTracks.size();
Elliott Hughes87cebad2014-05-22 10:14:43 -07001544 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001545 size_t numactiveseen = 0;
1546 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07001547 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08001548 Track::appendDumpHeader(result);
1549 for (size_t i = 0; i < numtracks; ++i) {
1550 sp<Track> track = mTracks[i];
1551 if (track != 0) {
1552 bool active = mActiveTracks.indexOf(track) >= 0;
1553 if (active) {
1554 numactiveseen++;
1555 }
1556 track->dump(buffer, SIZE, active);
1557 result.append(buffer);
1558 }
1559 }
1560 } else {
1561 result.append("\n");
1562 }
1563 if (numactiveseen != numactive) {
1564 // some tracks in the active list were not in the tracks list
1565 snprintf(buffer, SIZE, " The following tracks are in the active list but"
1566 " not in the track list\n");
1567 result.append(buffer);
1568 Track::appendDumpHeader(result);
1569 for (size_t i = 0; i < numactive; ++i) {
1570 sp<Track> track = mActiveTracks[i].promote();
1571 if (track != 0 && mTracks.indexOf(track) < 0) {
1572 track->dump(buffer, SIZE, true);
1573 result.append(buffer);
1574 }
1575 }
1576 }
1577
1578 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001579}
1580
1581void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1582{
Glenn Kasten97b7b752014-09-28 13:04:24 -07001583 dprintf(fd, "\nOutput thread %p type %d (%s):\n", this, type(), threadTypeToString(type()));
Glenn Kasten44182c22015-03-05 17:12:23 -08001584
1585 dumpBase(fd, args);
1586
Elliott Hughes87cebad2014-05-22 10:14:43 -07001587 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
1588 dprintf(fd, " Last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1589 dprintf(fd, " Total writes: %d\n", mNumWrites);
1590 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1591 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1592 dprintf(fd, " Suspend count: %d\n", mSuspended);
1593 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1594 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1595 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1596 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001597 AudioStreamOut *output = mOutput;
1598 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
1599 String8 flagsAsString = outputFlagsToString(flags);
1600 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n", output, flags, flagsAsString.string());
Eric Laurent81784c32012-11-19 14:55:58 -08001601}
1602
1603// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001604
1605void AudioFlinger::PlaybackThread::onFirstRef()
1606{
Glenn Kastend7dca052015-03-05 16:05:54 -08001607 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001608}
1609
1610// ThreadBase virtuals
1611void AudioFlinger::PlaybackThread::preExit()
1612{
1613 ALOGV(" preExit()");
1614 // FIXME this is using hard-coded strings but in the future, this functionality will be
1615 // converted to use audio HAL extensions required to support tunneling
1616 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1617}
1618
1619// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1620sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1621 const sp<AudioFlinger::Client>& client,
1622 audio_stream_type_t streamType,
1623 uint32_t sampleRate,
1624 audio_format_t format,
1625 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001626 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001627 const sp<IMemory>& sharedBuffer,
1628 int sessionId,
1629 IAudioFlinger::track_flags_t *flags,
1630 pid_t tid,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001631 int uid,
Eric Laurent81784c32012-11-19 14:55:58 -08001632 status_t *status)
1633{
Glenn Kasten74935e42013-12-19 08:56:45 -08001634 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001635 sp<Track> track;
1636 status_t lStatus;
1637
1638 bool isTimed = (*flags & IAudioFlinger::TRACK_TIMED) != 0;
1639
1640 // client expresses a preference for FAST, but we get the final say
1641 if (*flags & IAudioFlinger::TRACK_FAST) {
1642 if (
1643 // not timed
1644 (!isTimed) &&
1645 // either of these use cases:
1646 (
1647 // use case 1: shared buffer with any frame count
1648 (
1649 (sharedBuffer != 0)
1650 ) ||
Glenn Kasten1dfe2f92015-03-09 12:03:14 -07001651 // use case 2: frame count is default or at least as large as HAL
Eric Laurent81784c32012-11-19 14:55:58 -08001652 (
Glenn Kasten1dfe2f92015-03-09 12:03:14 -07001653 // we formerly checked for a callback handler (non-0 tid),
1654 // but that is no longer required for TRANSFER_OBTAIN mode
Eric Laurent81784c32012-11-19 14:55:58 -08001655 ((frameCount == 0) ||
Glenn Kastenb5fed682013-12-03 09:06:43 -08001656 (frameCount >= mFrameCount))
Eric Laurent81784c32012-11-19 14:55:58 -08001657 )
1658 ) &&
1659 // PCM data
1660 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07001661 // TODO: extract as a data library function that checks that a computationally
1662 // expensive downmixer is not required: isFastOutputChannelConversion()
Andy Hung9a592762014-07-21 21:56:01 -07001663 (channelMask == mChannelMask ||
Andy Hung1f439e12015-05-19 12:57:41 -07001664 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
1665 (channelMask == AUDIO_CHANNEL_OUT_MONO
1666 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001667 // hardware sample rate
1668 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001669 // normal mixer has an associated fast mixer
1670 hasFastMixer() &&
1671 // there are sufficient fast track slots available
1672 (mFastTrackAvailMask != 0)
1673 // FIXME test that MixerThread for this fast track has a capable output HAL
1674 // FIXME add a permission test also?
1675 ) {
1676 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1677 if (frameCount == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001678 // read the fast track multiplier property the first time it is needed
1679 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1680 if (ok != 0) {
1681 ALOGE("%s pthread_once failed: %d", __func__, ok);
1682 }
1683 frameCount = mFrameCount * sFastTrackMultiplier;
Eric Laurent81784c32012-11-19 14:55:58 -08001684 }
1685 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
1686 frameCount, mFrameCount);
1687 } else {
1688 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
Andy Hung6146c082014-03-18 11:56:15 -07001689 "mFrameCount=%d format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
1690 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001691 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Andy Hung6146c082014-03-18 11:56:15 -07001692 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001693 audio_is_linear_pcm(format),
1694 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
1695 *flags &= ~IAudioFlinger::TRACK_FAST;
Andy Hung0e48d252015-01-26 11:43:15 -08001696 }
1697 }
1698 // For normal PCM streaming tracks, update minimum frame count.
1699 // For compatibility with AudioTrack calculation, buffer depth is forced
1700 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1701 // This is probably too conservative, but legacy application code may depend on it.
1702 // If you change this calculation, also review the start threshold which is related.
1703 if (!(*flags & IAudioFlinger::TRACK_FAST)
1704 && audio_is_linear_pcm(format) && sharedBuffer == 0) {
Andy Hung8edb8dc2015-03-26 19:13:55 -07001705 // this must match AudioTrack.cpp calculateMinFrameCount().
1706 // TODO: Move to a common library
Eric Laurent81784c32012-11-19 14:55:58 -08001707 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1708 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1709 if (minBufCount < 2) {
1710 minBufCount = 2;
1711 }
Andy Hung8edb8dc2015-03-26 19:13:55 -07001712 // For normal mixing tracks, if speed is > 1.0f (normal), AudioTrack
1713 // or the client should compute and pass in a larger buffer request.
Andy Hung0e48d252015-01-26 11:43:15 -08001714 size_t minFrameCount =
Andy Hung8edb8dc2015-03-26 19:13:55 -07001715 minBufCount * sourceFramesNeededWithTimestretch(
1716 sampleRate, mNormalFrameCount,
1717 mSampleRate, AUDIO_TIMESTRETCH_SPEED_NORMAL /*speed*/);
Andy Hung0e48d252015-01-26 11:43:15 -08001718 if (frameCount < minFrameCount) { // including frameCount == 0
Eric Laurent81784c32012-11-19 14:55:58 -08001719 frameCount = minFrameCount;
1720 }
Eric Laurent81784c32012-11-19 14:55:58 -08001721 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001722 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001723
Glenn Kastenc3df8382014-03-13 15:05:25 -07001724 switch (mType) {
1725
1726 case DIRECT:
Glenn Kasten993fa062014-05-02 11:14:34 -07001727 if (audio_is_linear_pcm(format)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001728 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001729 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1730 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001731 sampleRate, format, channelMask, mOutput, mFormat);
1732 lStatus = BAD_VALUE;
1733 goto Exit;
1734 }
1735 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001736 break;
1737
1738 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001739 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001740 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1741 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001742 sampleRate, format, channelMask, mOutput, mFormat);
1743 lStatus = BAD_VALUE;
1744 goto Exit;
1745 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001746 break;
1747
1748 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07001749 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001750 ALOGE("createTrack_l() Bad parameter: format %#x \""
1751 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001752 format, mOutput, mFormat);
1753 lStatus = BAD_VALUE;
1754 goto Exit;
1755 }
Andy Hungcd044842014-08-07 11:04:34 -07001756 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08001757 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1758 lStatus = BAD_VALUE;
1759 goto Exit;
1760 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001761 break;
1762
Eric Laurent81784c32012-11-19 14:55:58 -08001763 }
1764
1765 lStatus = initCheck();
1766 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07001767 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08001768 goto Exit;
1769 }
1770
1771 { // scope for mLock
1772 Mutex::Autolock _l(mLock);
1773
1774 // all tracks in same audio session must share the same routing strategy otherwise
1775 // conflicts will happen when tracks are moved from one output to another by audio policy
1776 // manager
1777 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1778 for (size_t i = 0; i < mTracks.size(); ++i) {
1779 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07001780 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001781 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1782 if (sessionId == t->sessionId() && strategy != actual) {
1783 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1784 strategy, actual);
1785 lStatus = BAD_VALUE;
1786 goto Exit;
1787 }
1788 }
1789 }
1790
1791 if (!isTimed) {
1792 track = new Track(this, client, streamType, sampleRate, format,
Eric Laurent83b88082014-06-20 18:31:16 -07001793 channelMask, frameCount, NULL, sharedBuffer,
1794 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08001795 } else {
1796 track = TimedTrack::create(this, client, streamType, sampleRate, format,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001797 channelMask, frameCount, sharedBuffer, sessionId, uid);
Eric Laurent81784c32012-11-19 14:55:58 -08001798 }
Glenn Kasten03003332013-08-06 15:40:54 -07001799
1800 // new Track always returns non-NULL,
1801 // but TimedTrack::create() is a factory that could fail by returning NULL
1802 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
1803 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08001804 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001805 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08001806 goto Exit;
1807 }
1808 mTracks.add(track);
1809
1810 sp<EffectChain> chain = getEffectChain_l(sessionId);
1811 if (chain != 0) {
1812 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1813 track->setMainBuffer(chain->inBuffer());
1814 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1815 chain->incTrackCnt();
1816 }
1817
1818 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1819 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1820 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1821 // so ask activity manager to do this on our behalf
1822 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1823 }
1824 }
1825
1826 lStatus = NO_ERROR;
1827
1828Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001829 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001830 return track;
1831}
1832
1833uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1834{
1835 return latency;
1836}
1837
1838uint32_t AudioFlinger::PlaybackThread::latency() const
1839{
1840 Mutex::Autolock _l(mLock);
1841 return latency_l();
1842}
1843uint32_t AudioFlinger::PlaybackThread::latency_l() const
1844{
1845 if (initCheck() == NO_ERROR) {
1846 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
1847 } else {
1848 return 0;
1849 }
1850}
1851
1852void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1853{
1854 Mutex::Autolock _l(mLock);
1855 // Don't apply master volume in SW if our HAL can do it for us.
1856 if (mOutput && mOutput->audioHwDev &&
1857 mOutput->audioHwDev->canSetMasterVolume()) {
1858 mMasterVolume = 1.0;
1859 } else {
1860 mMasterVolume = value;
1861 }
1862}
1863
1864void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1865{
1866 Mutex::Autolock _l(mLock);
1867 // Don't apply master mute in SW if our HAL can do it for us.
1868 if (mOutput && mOutput->audioHwDev &&
1869 mOutput->audioHwDev->canSetMasterMute()) {
1870 mMasterMute = false;
1871 } else {
1872 mMasterMute = muted;
1873 }
1874}
1875
1876void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
1877{
1878 Mutex::Autolock _l(mLock);
1879 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001880 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001881}
1882
1883void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
1884{
1885 Mutex::Autolock _l(mLock);
1886 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001887 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001888}
1889
1890float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
1891{
1892 Mutex::Autolock _l(mLock);
1893 return mStreamTypes[stream].volume;
1894}
1895
1896// addTrack_l() must be called with ThreadBase::mLock held
1897status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1898{
1899 status_t status = ALREADY_EXISTS;
1900
1901 // set retry count for buffer fill
1902 track->mRetryCount = kMaxTrackStartupRetries;
1903 if (mActiveTracks.indexOf(track) < 0) {
1904 // the track is newly added, make sure it fills up all its
1905 // buffers before playing. This is to ensure the client will
1906 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07001907 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001908 TrackBase::track_state state = track->mState;
1909 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08001910 status = AudioSystem::startOutput(mId, track->streamType(),
1911 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001912 mLock.lock();
1913 // abort track was stopped/paused while we released the lock
1914 if (state != track->mState) {
1915 if (status == NO_ERROR) {
1916 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08001917 AudioSystem::stopOutput(mId, track->streamType(),
1918 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001919 mLock.lock();
1920 }
1921 return INVALID_OPERATION;
1922 }
1923 // abort if start is rejected by audio policy manager
1924 if (status != NO_ERROR) {
1925 return PERMISSION_DENIED;
1926 }
1927#ifdef ADD_BATTERY_DATA
1928 // to track the speaker usage
1929 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
1930#endif
1931 }
1932
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001933 track->mFillingUpStatus = track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent81784c32012-11-19 14:55:58 -08001934 track->mResetDone = false;
1935 track->mPresentationCompleteFrames = 0;
1936 mActiveTracks.add(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001937 mWakeLockUids.add(track->uid());
1938 mActiveTracksGeneration++;
Eric Laurentfd477972013-10-25 18:10:40 -07001939 mLatestActiveTrack = track;
Eric Laurentd0107bc2013-06-11 14:38:48 -07001940 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1941 if (chain != 0) {
1942 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
1943 track->sessionId());
1944 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08001945 }
1946
1947 status = NO_ERROR;
1948 }
1949
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08001950 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001951 return status;
1952}
1953
Eric Laurentbfb1b832013-01-07 09:53:42 -08001954bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08001955{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001956 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08001957 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001958 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
1959 track->mState = TrackBase::STOPPED;
1960 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08001961 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07001962 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001963 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08001964 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001965
1966 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08001967}
1968
1969void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1970{
1971 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
1972 mTracks.remove(track);
1973 deleteTrackName_l(track->name());
1974 // redundant as track is about to be destroyed, for dumpsys only
1975 track->mName = -1;
1976 if (track->isFastTrack()) {
1977 int index = track->mFastIndex;
1978 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
1979 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1980 mFastTrackAvailMask |= 1 << index;
1981 // redundant as track is about to be destroyed, for dumpsys only
1982 track->mFastIndex = -1;
1983 }
1984 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1985 if (chain != 0) {
1986 chain->decTrackCnt();
1987 }
1988}
1989
Eric Laurentede6c3b2013-09-19 14:37:46 -07001990void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001991{
1992 // Thread could be blocked waiting for async
1993 // so signal it to handle state changes immediately
1994 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1995 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1996 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001997 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001998}
1999
Eric Laurent81784c32012-11-19 14:55:58 -08002000String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2001{
Eric Laurent81784c32012-11-19 14:55:58 -08002002 Mutex::Autolock _l(mLock);
2003 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07002004 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002005 }
2006
Glenn Kastend8ea6992013-07-16 14:17:15 -07002007 char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
2008 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08002009 free(s);
2010 return out_s8;
2011}
2012
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002013void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002014 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2015 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002016
Eric Laurent73e26b62015-04-27 16:55:58 -07002017 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002018
2019 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002020 case AUDIO_OUTPUT_OPENED:
2021 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002022 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002023 desc->mChannelMask = mChannelMask;
2024 desc->mSamplingRate = mSampleRate;
2025 desc->mFormat = mFormat;
2026 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002027 // AudioFlinger::frameCount(audio_io_handle_t)
Eric Laurent73e26b62015-04-27 16:55:58 -07002028 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002029 break;
2030
Eric Laurent73e26b62015-04-27 16:55:58 -07002031 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002032 default:
2033 break;
2034 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002035 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002036}
2037
Eric Laurentbfb1b832013-01-07 09:53:42 -08002038void AudioFlinger::PlaybackThread::writeCallback()
2039{
2040 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002041 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002042}
2043
2044void AudioFlinger::PlaybackThread::drainCallback()
2045{
2046 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002047 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002048}
2049
Eric Laurent3b4529e2013-09-05 18:09:19 -07002050void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002051{
2052 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002053 // reject out of sequence requests
2054 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2055 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002056 mWaitWorkCV.signal();
2057 }
2058}
2059
Eric Laurent3b4529e2013-09-05 18:09:19 -07002060void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002061{
2062 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002063 // reject out of sequence requests
2064 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
2065 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002066 mWaitWorkCV.signal();
2067 }
2068}
2069
2070// static
2071int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
Glenn Kasten0f11b512014-01-31 16:18:54 -08002072 void *param __unused,
Eric Laurentbfb1b832013-01-07 09:53:42 -08002073 void *cookie)
2074{
2075 AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
2076 ALOGV("asyncCallback() event %d", event);
2077 switch (event) {
2078 case STREAM_CBK_EVENT_WRITE_READY:
2079 me->writeCallback();
2080 break;
2081 case STREAM_CBK_EVENT_DRAIN_READY:
2082 me->drainCallback();
2083 break;
2084 default:
2085 ALOGW("asyncCallback() unknown event %d", event);
2086 break;
2087 }
2088 return 0;
2089}
2090
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002091void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002092{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002093 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Phil Burkca5e6142015-07-14 09:42:29 -07002094 mSampleRate = mOutput->getSampleRate();
2095 mChannelMask = mOutput->getChannelMask();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002096 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002097 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002098 }
Andy Hung9a592762014-07-21 21:56:01 -07002099 if ((mType == MIXER || mType == DUPLICATING)
2100 && !isValidPcmSinkChannelMask(mChannelMask)) {
2101 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2102 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002103 }
Andy Hunge5412692014-05-16 11:25:07 -07002104 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002105
2106 // Get actual HAL format.
Andy Hung463be252014-07-10 16:56:07 -07002107 mHALFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Phil Burkca5e6142015-07-14 09:42:29 -07002108 // Get format from the shim, which will be different than the HAL format
2109 // if playing compressed audio over HDMI passthrough.
2110 mFormat = mOutput->getFormat();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002111 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002112 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002113 }
Andy Hung6146c082014-03-18 11:56:15 -07002114 if ((mType == MIXER || mType == DUPLICATING)
2115 && !isValidPcmSinkFormat(mFormat)) {
2116 LOG_FATAL("HAL format %#x not supported for mixed output",
2117 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002118 }
Phil Burk062e67a2015-02-11 13:40:50 -08002119 mFrameSize = mOutput->getFrameSize();
Glenn Kasten70949c42013-08-06 07:40:12 -07002120 mBufferSize = mOutput->stream->common.get_buffer_size(&mOutput->stream->common);
2121 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002122 if (mFrameCount & 15) {
2123 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
2124 mFrameCount);
2125 }
2126
Eric Laurentbfb1b832013-01-07 09:53:42 -08002127 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
2128 (mOutput->stream->set_callback != NULL)) {
2129 if (mOutput->stream->set_callback(mOutput->stream,
2130 AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
2131 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002132 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002133 }
2134 }
2135
Eric Laurentd1f69b02014-12-15 14:33:13 -08002136 mHwSupportsPause = false;
2137 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
2138 if (mOutput->stream->pause != NULL) {
2139 if (mOutput->stream->resume != NULL) {
2140 mHwSupportsPause = true;
2141 } else {
2142 ALOGW("direct output implements pause but not resume");
2143 }
2144 } else if (mOutput->stream->resume != NULL) {
2145 ALOGW("direct output implements resume but not pause");
2146 }
2147 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002148 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2149 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2150 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002151
Andy Hungfbfc3952015-01-15 13:33:51 -08002152 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2153 // For best precision, we use float instead of the associated output
2154 // device format (typically PCM 16 bit).
2155
2156 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2157 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2158 mBufferSize = mFrameSize * mFrameCount;
2159
2160 // TODO: We currently use the associated output device channel mask and sample rate.
2161 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2162 // (if a valid mask) to avoid premature downmix.
2163 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2164 // instead of the output device sample rate to avoid loss of high frequency information.
2165 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2166 }
2167
Andy Hung09a50072014-02-27 14:30:47 -08002168 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002169 double multiplier = 1.0;
2170 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2171 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002172 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2173 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Eric Laurent81784c32012-11-19 14:55:58 -08002174 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2175 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2176 maxNormalFrameCount = maxNormalFrameCount & ~15;
2177 if (maxNormalFrameCount < minNormalFrameCount) {
2178 maxNormalFrameCount = minNormalFrameCount;
2179 }
2180 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2181 if (multiplier <= 1.0) {
2182 multiplier = 1.0;
2183 } else if (multiplier <= 2.0) {
2184 if (2 * mFrameCount <= maxNormalFrameCount) {
2185 multiplier = 2.0;
2186 } else {
2187 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2188 }
2189 } else {
2190 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
Andy Hung09a50072014-02-27 14:30:47 -08002191 // SRC (it would be unusual for the normal sink buffer size to not be a multiple of fast
Eric Laurent81784c32012-11-19 14:55:58 -08002192 // track, but we sometimes have to do this to satisfy the maximum frame count
2193 // constraint)
2194 // FIXME this rounding up should not be done if no HAL SRC
2195 uint32_t truncMult = (uint32_t) multiplier;
2196 if ((truncMult & 1)) {
2197 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
2198 ++truncMult;
2199 }
2200 }
2201 multiplier = (double) truncMult;
2202 }
2203 }
2204 mNormalFrameCount = multiplier * mFrameCount;
2205 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002206 if (mType == MIXER || mType == DUPLICATING) {
2207 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2208 }
Andy Hung09a50072014-02-27 14:30:47 -08002209 ALOGI("HAL output buffer size %u frames, normal sink buffer size %u frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002210 mNormalFrameCount);
2211
Andy Hung08fb1742015-05-31 23:22:10 -07002212 // Check if we want to throttle the processing to no more than 2x normal rate
2213 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002214 mThreadThrottleTimeMs = 0;
2215 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002216 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2217
Andy Hung010a1a12014-03-13 13:57:33 -07002218 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2219 // Originally this was int16_t[] array, need to remove legacy implications.
2220 free(mSinkBuffer);
2221 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002222 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2223 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2224 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002225 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002226
Andy Hung69aed5f2014-02-25 17:24:40 -08002227 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2228 // drives the output.
2229 free(mMixerBuffer);
2230 mMixerBuffer = NULL;
2231 if (mMixerBufferEnabled) {
2232 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2233 mMixerBufferSize = mNormalFrameCount * mChannelCount
2234 * audio_bytes_per_sample(mMixerBufferFormat);
2235 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2236 }
Andy Hung98ef9782014-03-04 14:46:50 -08002237 free(mEffectBuffer);
2238 mEffectBuffer = NULL;
2239 if (mEffectBufferEnabled) {
2240 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
2241 mEffectBufferSize = mNormalFrameCount * mChannelCount
2242 * audio_bytes_per_sample(mEffectBufferFormat);
2243 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2244 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002245
Eric Laurent81784c32012-11-19 14:55:58 -08002246 // force reconfiguration of effect chains and engines to take new buffer size and audio
2247 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002248 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002249 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2250 // matter.
2251 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2252 Vector< sp<EffectChain> > effectChains = mEffectChains;
2253 for (size_t i = 0; i < effectChains.size(); i ++) {
2254 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2255 }
2256}
2257
2258
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002259status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002260{
2261 if (halFrames == NULL || dspFrames == NULL) {
2262 return BAD_VALUE;
2263 }
2264 Mutex::Autolock _l(mLock);
2265 if (initCheck() != NO_ERROR) {
2266 return INVALID_OPERATION;
2267 }
2268 size_t framesWritten = mBytesWritten / mFrameSize;
2269 *halFrames = framesWritten;
2270
2271 if (isSuspended()) {
2272 // return an estimation of rendered frames when the output is suspended
2273 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
2274 *dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0;
2275 return NO_ERROR;
2276 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002277 status_t status;
2278 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002279 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002280 *dspFrames = (size_t)frames;
2281 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002282 }
2283}
2284
2285uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
2286{
2287 Mutex::Autolock _l(mLock);
2288 uint32_t result = 0;
2289 if (getEffectChain_l(sessionId) != 0) {
2290 result = EFFECT_SESSION;
2291 }
2292
2293 for (size_t i = 0; i < mTracks.size(); ++i) {
2294 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002295 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002296 result |= TRACK_SESSION;
2297 break;
2298 }
2299 }
2300
2301 return result;
2302}
2303
2304uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
2305{
2306 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2307 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2308 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2309 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2310 }
2311 for (size_t i = 0; i < mTracks.size(); i++) {
2312 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002313 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002314 return AudioSystem::getStrategyForStream(track->streamType());
2315 }
2316 }
2317 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2318}
2319
2320
Phil Burk062e67a2015-02-11 13:40:50 -08002321AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002322{
2323 Mutex::Autolock _l(mLock);
2324 return mOutput;
2325}
2326
Phil Burk062e67a2015-02-11 13:40:50 -08002327AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002328{
2329 Mutex::Autolock _l(mLock);
2330 AudioStreamOut *output = mOutput;
2331 mOutput = NULL;
2332 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2333 // must push a NULL and wait for ack
2334 mOutputSink.clear();
2335 mPipeSink.clear();
2336 mNormalSink.clear();
2337 return output;
2338}
2339
2340// this method must always be called either with ThreadBase mLock held or inside the thread loop
2341audio_stream_t* AudioFlinger::PlaybackThread::stream() const
2342{
2343 if (mOutput == NULL) {
2344 return NULL;
2345 }
2346 return &mOutput->stream->common;
2347}
2348
2349uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2350{
2351 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2352}
2353
2354status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2355{
2356 if (!isValidSyncEvent(event)) {
2357 return BAD_VALUE;
2358 }
2359
2360 Mutex::Autolock _l(mLock);
2361
2362 for (size_t i = 0; i < mTracks.size(); ++i) {
2363 sp<Track> track = mTracks[i];
2364 if (event->triggerSession() == track->sessionId()) {
2365 (void) track->setSyncEvent(event);
2366 return NO_ERROR;
2367 }
2368 }
2369
2370 return NAME_NOT_FOUND;
2371}
2372
2373bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2374{
2375 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2376}
2377
2378void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2379 const Vector< sp<Track> >& tracksToRemove)
2380{
2381 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002382 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002383 for (size_t i = 0 ; i < count ; i++) {
2384 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002385 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002386 AudioSystem::stopOutput(mId, track->streamType(),
2387 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002388#ifdef ADD_BATTERY_DATA
2389 // to track the speaker usage
2390 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2391#endif
2392 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002393 AudioSystem::releaseOutput(mId, track->streamType(),
2394 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002395 }
Eric Laurent81784c32012-11-19 14:55:58 -08002396 }
2397 }
2398 }
Eric Laurent81784c32012-11-19 14:55:58 -08002399}
2400
2401void AudioFlinger::PlaybackThread::checkSilentMode_l()
2402{
2403 if (!mMasterMute) {
2404 char value[PROPERTY_VALUE_MAX];
2405 if (property_get("ro.audio.silent", value, "0") > 0) {
2406 char *endptr;
2407 unsigned long ul = strtoul(value, &endptr, 0);
2408 if (*endptr == '\0' && ul != 0) {
2409 ALOGD("Silence is golden");
2410 // The setprop command will not allow a property to be changed after
2411 // the first time it is set, so we don't have to worry about un-muting.
2412 setMasterMute_l(true);
2413 }
2414 }
2415 }
2416}
2417
2418// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002419ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002420{
2421 // FIXME rewrite to reduce number of system calls
2422 mLastWriteTime = systemTime();
2423 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002424 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002425 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002426
2427 // If an NBAIO sink is present, use it to write the normal mixer's submix
2428 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002429
Andy Hung010a1a12014-03-13 13:57:33 -07002430 const size_t count = mBytesRemaining / mFrameSize;
2431
Simon Wilson2d590962012-11-29 15:18:50 -08002432 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002433 // update the setpoint when AudioFlinger::mScreenState changes
2434 uint32_t screenState = AudioFlinger::mScreenState;
2435 if (screenState != mScreenState) {
2436 mScreenState = screenState;
2437 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2438 if (pipe != NULL) {
2439 pipe->setAvgFrames((mScreenState & 1) ?
2440 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2441 }
2442 }
Andy Hung010a1a12014-03-13 13:57:33 -07002443 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002444 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002445 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002446 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002447 } else {
2448 bytesWritten = framesWritten;
2449 }
Glenn Kastenefaa7ab2014-08-20 08:48:54 -07002450 mLatchDValid = false;
Glenn Kasten767094d2013-08-23 13:51:43 -07002451 status_t status = mNormalSink->getTimestamp(mLatchD.mTimestamp);
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002452 if (status == NO_ERROR) {
2453 size_t totalFramesWritten = mNormalSink->framesWritten();
2454 if (totalFramesWritten >= mLatchD.mTimestamp.mPosition) {
2455 mLatchD.mUnpresentedFrames = totalFramesWritten - mLatchD.mTimestamp.mPosition;
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002456 // mLatchD.mFramesReleased is set immediately before D is clocked into Q
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002457 mLatchDValid = true;
2458 }
2459 }
Eric Laurent81784c32012-11-19 14:55:58 -08002460 // otherwise use the HAL / AudioStreamOut directly
2461 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002462 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002463
Eric Laurentbfb1b832013-01-07 09:53:42 -08002464 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002465 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2466 mWriteAckSequence += 2;
2467 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002468 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002469 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002470 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002471 // FIXME We should have an implementation of timestamps for direct output threads.
2472 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002473 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002474 if (mUseAsyncWrite &&
2475 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2476 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002477 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002478 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002479 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002480 }
Eric Laurent81784c32012-11-19 14:55:58 -08002481 }
2482
Eric Laurent81784c32012-11-19 14:55:58 -08002483 mNumWrites++;
2484 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002485 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002486 return bytesWritten;
2487}
2488
2489void AudioFlinger::PlaybackThread::threadLoop_drain()
2490{
2491 if (mOutput->stream->drain) {
2492 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2493 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002494 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2495 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002496 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002497 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002498 }
2499 mOutput->stream->drain(mOutput->stream,
2500 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
2501 : AUDIO_DRAIN_ALL);
2502 }
2503}
2504
2505void AudioFlinger::PlaybackThread::threadLoop_exit()
2506{
Eric Laurent275e8e92014-11-30 15:14:47 -08002507 {
2508 Mutex::Autolock _l(mLock);
2509 for (size_t i = 0; i < mTracks.size(); i++) {
2510 sp<Track> track = mTracks[i];
2511 track->invalidate();
2512 }
2513 }
Eric Laurent81784c32012-11-19 14:55:58 -08002514}
2515
2516/*
2517The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002518 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002519 - mActiveSleepTimeUs from activeSleepTimeUs()
2520 - mIdleSleepTimeUs from idleSleepTimeUs()
2521 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only)
Eric Laurent81784c32012-11-19 14:55:58 -08002522 - maxPeriod from frame count and sample rate (MIXER only)
2523
2524The parameters that affect these derived values are:
2525 - frame count
2526 - frame size
2527 - sample rate
2528 - device type: A2DP or not
2529 - device latency
2530 - format: PCM or not
2531 - active sleep time
2532 - idle sleep time
2533*/
2534
2535void AudioFlinger::PlaybackThread::cacheParameters_l()
2536{
Andy Hung25c2dac2014-02-27 14:56:00 -08002537 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002538 mActiveSleepTimeUs = activeSleepTimeUs();
2539 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent81784c32012-11-19 14:55:58 -08002540}
2541
2542void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2543{
Glenn Kasten7c027242012-12-26 14:43:16 -08002544 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurent81784c32012-11-19 14:55:58 -08002545 this, streamType, mTracks.size());
2546 Mutex::Autolock _l(mLock);
2547
2548 size_t size = mTracks.size();
2549 for (size_t i = 0; i < size; i++) {
2550 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07002551 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002552 t->invalidate();
Eric Laurent81784c32012-11-19 14:55:58 -08002553 }
2554 }
2555}
2556
2557status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2558{
2559 int session = chain->sessionId();
Andy Hung010a1a12014-03-13 13:57:33 -07002560 int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled
2561 ? mEffectBuffer : mSinkBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002562 bool ownsBuffer = false;
2563
2564 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
2565 if (session > 0) {
2566 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002567 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002568 if (mType != DIRECT) {
2569 size_t numSamples = mNormalFrameCount * mChannelCount;
2570 buffer = new int16_t[numSamples];
2571 memset(buffer, 0, numSamples * sizeof(int16_t));
2572 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2573 ownsBuffer = true;
2574 }
2575
2576 // Attach all tracks with same session ID to this chain.
2577 for (size_t i = 0; i < mTracks.size(); ++i) {
2578 sp<Track> track = mTracks[i];
2579 if (session == track->sessionId()) {
2580 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2581 buffer);
2582 track->setMainBuffer(buffer);
2583 chain->incTrackCnt();
2584 }
2585 }
2586
2587 // indicate all active tracks in the chain
2588 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2589 sp<Track> track = mActiveTracks[i].promote();
2590 if (track == 0) {
2591 continue;
2592 }
2593 if (session == track->sessionId()) {
2594 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2595 chain->incActiveTrackCnt();
2596 }
2597 }
2598 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002599 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08002600 chain->setInBuffer(buffer, ownsBuffer);
Andy Hung010a1a12014-03-13 13:57:33 -07002601 chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled
2602 ? mEffectBuffer : mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002603 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
2604 // chains list in order to be processed last as it contains output stage effects
2605 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2606 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
2607 // after track specific effects and before output stage
2608 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
2609 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
2610 // Effect chain for other sessions are inserted at beginning of effect
2611 // chains list to be processed before output mix effects. Relative order between other
2612 // sessions is not important
2613 size_t size = mEffectChains.size();
2614 size_t i = 0;
2615 for (i = 0; i < size; i++) {
2616 if (mEffectChains[i]->sessionId() < session) {
2617 break;
2618 }
2619 }
2620 mEffectChains.insertAt(chain, i);
2621 checkSuspendOnAddEffectChain_l(chain);
2622
2623 return NO_ERROR;
2624}
2625
2626size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2627{
2628 int session = chain->sessionId();
2629
2630 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2631
2632 for (size_t i = 0; i < mEffectChains.size(); i++) {
2633 if (chain == mEffectChains[i]) {
2634 mEffectChains.removeAt(i);
2635 // detach all active tracks from the chain
2636 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2637 sp<Track> track = mActiveTracks[i].promote();
2638 if (track == 0) {
2639 continue;
2640 }
2641 if (session == track->sessionId()) {
2642 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2643 chain.get(), session);
2644 chain->decActiveTrackCnt();
2645 }
2646 }
2647
2648 // detach all tracks with same session ID from this chain
2649 for (size_t i = 0; i < mTracks.size(); ++i) {
2650 sp<Track> track = mTracks[i];
2651 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002652 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002653 chain->decTrackCnt();
2654 }
2655 }
2656 break;
2657 }
2658 }
2659 return mEffectChains.size();
2660}
2661
2662status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2663 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2664{
2665 Mutex::Autolock _l(mLock);
2666 return attachAuxEffect_l(track, EffectId);
2667}
2668
2669status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2670 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2671{
2672 status_t status = NO_ERROR;
2673
2674 if (EffectId == 0) {
2675 track->setAuxBuffer(0, NULL);
2676 } else {
2677 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2678 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2679 if (effect != 0) {
2680 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2681 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2682 } else {
2683 status = INVALID_OPERATION;
2684 }
2685 } else {
2686 status = BAD_VALUE;
2687 }
2688 }
2689 return status;
2690}
2691
2692void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2693{
2694 for (size_t i = 0; i < mTracks.size(); ++i) {
2695 sp<Track> track = mTracks[i];
2696 if (track->auxEffectId() == effectId) {
2697 attachAuxEffect_l(track, 0);
2698 }
2699 }
2700}
2701
2702bool AudioFlinger::PlaybackThread::threadLoop()
2703{
2704 Vector< sp<Track> > tracksToRemove;
2705
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002706 mStandbyTimeNs = systemTime();
Eric Laurent81784c32012-11-19 14:55:58 -08002707
2708 // MIXER
2709 nsecs_t lastWarning = 0;
2710
2711 // DUPLICATING
2712 // FIXME could this be made local to while loop?
2713 writeFrames = 0;
2714
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002715 int lastGeneration = 0;
2716
Eric Laurent81784c32012-11-19 14:55:58 -08002717 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002718 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08002719
2720 if (mType == MIXER) {
2721 sleepTimeShift = 0;
2722 }
2723
2724 CpuStats cpuStats;
2725 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2726
2727 acquireWakeLock();
2728
Glenn Kasten9e58b552013-01-18 15:09:48 -08002729 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2730 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2731 // and then that string will be logged at the next convenient opportunity.
2732 const char *logString = NULL;
2733
Eric Laurent664539d2013-09-23 18:24:31 -07002734 checkSilentMode_l();
2735
Eric Laurent81784c32012-11-19 14:55:58 -08002736 while (!exitPending())
2737 {
2738 cpuStats.sample(myName);
2739
2740 Vector< sp<EffectChain> > effectChains;
2741
Eric Laurent81784c32012-11-19 14:55:58 -08002742 { // scope for mLock
2743
2744 Mutex::Autolock _l(mLock);
2745
Eric Laurent021cf962014-05-13 10:18:14 -07002746 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07002747
Glenn Kasten9e58b552013-01-18 15:09:48 -08002748 if (logString != NULL) {
2749 mNBLogWriter->logTimestamp();
2750 mNBLogWriter->log(logString);
2751 logString = NULL;
2752 }
2753
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002754 // Gather the framesReleased counters for all active tracks,
2755 // and latch them atomically with the timestamp.
2756 // FIXME We're using raw pointers as indices. A unique track ID would be a better index.
2757 mLatchD.mFramesReleased.clear();
2758 size_t size = mActiveTracks.size();
2759 for (size_t i = 0; i < size; i++) {
2760 sp<Track> t = mActiveTracks[i].promote();
2761 if (t != 0) {
2762 mLatchD.mFramesReleased.add(t.get(),
2763 t->mAudioTrackServerProxy->framesReleased());
2764 }
2765 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002766 if (mLatchDValid) {
2767 mLatchQ = mLatchD;
2768 mLatchDValid = false;
2769 mLatchQValid = true;
2770 }
2771
Eric Laurent81784c32012-11-19 14:55:58 -08002772 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002773 if (mSignalPending) {
2774 // A signal was raised while we were unlocked
2775 mSignalPending = false;
2776 } else if (waitingAsyncCallback_l()) {
2777 if (exitPending()) {
2778 break;
2779 }
Marco Nelissen078538c2015-05-12 09:17:57 -07002780 bool released = false;
2781 // The following works around a bug in the offload driver. Ideally we would release
2782 // the wake lock every time, but that causes the last offload buffer(s) to be
2783 // dropped while the device is on battery, so we need to hold a wake lock during
2784 // the drain phase.
2785 if (mBytesRemaining && !(mDrainSequence & 1)) {
2786 releaseWakeLock_l();
2787 released = true;
2788 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002789 mWakeLockUids.clear();
2790 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002791 ALOGV("wait async completion");
2792 mWaitWorkCV.wait(mLock);
2793 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07002794 if (released) {
2795 acquireWakeLock_l();
2796 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002797 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
2798 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002799
2800 continue;
2801 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002802 if ((!mActiveTracks.size() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08002803 isSuspended()) {
2804 // put audio hardware into standby after short delay
2805 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002806
2807 threadLoop_standby();
2808
2809 mStandby = true;
2810 }
2811
2812 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2813 // we're about to wait, flush the binder command buffer
2814 IPCThreadState::self()->flushCommands();
2815
2816 clearOutputTracks();
2817
2818 if (exitPending()) {
2819 break;
2820 }
2821
2822 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002823 mWakeLockUids.clear();
2824 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002825 // wait until we have something to do...
2826 ALOGV("%s going to sleep", myName.string());
2827 mWaitWorkCV.wait(mLock);
2828 ALOGV("%s waking up", myName.string());
2829 acquireWakeLock_l();
2830
2831 mMixerStatus = MIXER_IDLE;
2832 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2833 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002834 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002835 checkSilentMode_l();
2836
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002837 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
2838 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08002839 if (mType == MIXER) {
2840 sleepTimeShift = 0;
2841 }
2842
2843 continue;
2844 }
2845 }
Eric Laurent81784c32012-11-19 14:55:58 -08002846 // mMixerStatusIgnoringFastTracks is also updated internally
2847 mMixerStatus = prepareTracks_l(&tracksToRemove);
2848
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002849 // compare with previously applied list
2850 if (lastGeneration != mActiveTracksGeneration) {
2851 // update wakelock
2852 updateWakeLockUids_l(mWakeLockUids);
2853 lastGeneration = mActiveTracksGeneration;
2854 }
2855
Eric Laurent81784c32012-11-19 14:55:58 -08002856 // prevent any changes in effect chain list and in each effect chain
2857 // during mixing and effect process as the audio buffers could be deleted
2858 // or modified if an effect is created or deleted
2859 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002860 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08002861
Eric Laurentbfb1b832013-01-07 09:53:42 -08002862 if (mBytesRemaining == 0) {
2863 mCurrentWriteLength = 0;
2864 if (mMixerStatus == MIXER_TRACKS_READY) {
2865 // threadLoop_mix() sets mCurrentWriteLength
2866 threadLoop_mix();
2867 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
2868 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002869 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08002870 // must be written to HAL
2871 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002872 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08002873 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002874 }
2875 }
Andy Hung98ef9782014-03-04 14:46:50 -08002876 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002877 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08002878 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
2879 // or mSinkBuffer (if there are no effects).
2880 //
2881 // This is done pre-effects computation; if effects change to
2882 // support higher precision, this needs to move.
2883 //
2884 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002885 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08002886 if (mMixerBufferValid) {
2887 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
2888 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
2889
2890 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
2891 mNormalFrameCount * mChannelCount);
2892 }
2893
Eric Laurentbfb1b832013-01-07 09:53:42 -08002894 mBytesRemaining = mCurrentWriteLength;
2895 if (isSuspended()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002896 mSleepTimeUs = suspendSleepTimeUs();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002897 // simulate write to HAL when suspended
Andy Hung25c2dac2014-02-27 14:56:00 -08002898 mBytesWritten += mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002899 mBytesRemaining = 0;
2900 }
Eric Laurent81784c32012-11-19 14:55:58 -08002901
Eric Laurentbfb1b832013-01-07 09:53:42 -08002902 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002903 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002904 for (size_t i = 0; i < effectChains.size(); i ++) {
2905 effectChains[i]->process_l();
2906 }
Eric Laurent81784c32012-11-19 14:55:58 -08002907 }
2908 }
Eric Laurent59fe0102013-09-27 18:48:26 -07002909 // Process effect chains for offloaded thread even if no audio
2910 // was read from audio track: process only updates effect state
2911 // and thus does have to be synchronized with audio writes but may have
2912 // to be called while waiting for async write callback
2913 if (mType == OFFLOAD) {
2914 for (size_t i = 0; i < effectChains.size(); i ++) {
2915 effectChains[i]->process_l();
2916 }
2917 }
Eric Laurent81784c32012-11-19 14:55:58 -08002918
Andy Hung98ef9782014-03-04 14:46:50 -08002919 // Only if the Effects buffer is enabled and there is data in the
2920 // Effects buffer (buffer valid), we need to
2921 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002922 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08002923 if (mEffectBufferValid) {
2924 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
2925 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
2926 mNormalFrameCount * mChannelCount);
2927 }
2928
Eric Laurent81784c32012-11-19 14:55:58 -08002929 // enable changes in effect chain
2930 unlockEffectChains(effectChains);
2931
Eric Laurentbfb1b832013-01-07 09:53:42 -08002932 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002933 // mSleepTimeUs == 0 means we must write to audio hardware
2934 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07002935 ssize_t ret = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002936 if (mBytesRemaining) {
Andy Hung08fb1742015-05-31 23:22:10 -07002937 ret = threadLoop_write();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002938 if (ret < 0) {
2939 mBytesRemaining = 0;
2940 } else {
2941 mBytesWritten += ret;
2942 mBytesRemaining -= ret;
2943 }
2944 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
2945 (mMixerStatus == MIXER_DRAIN_ALL)) {
2946 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08002947 }
Andy Hung08fb1742015-05-31 23:22:10 -07002948 if (mType == MIXER && !mStandby) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07002949 // write blocked detection
2950 nsecs_t now = systemTime();
2951 nsecs_t delta = now - mLastWriteTime;
Andy Hung08fb1742015-05-31 23:22:10 -07002952 if (delta > maxPeriod) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07002953 mNumDelayedWrites++;
2954 if ((now - lastWarning) > kWarningThrottleNs) {
2955 ATRACE_NAME("underrun");
2956 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2957 ns2ms(delta), mNumDelayedWrites, this);
2958 lastWarning = now;
2959 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002960 }
Andy Hung08fb1742015-05-31 23:22:10 -07002961
2962 if (mThreadThrottle
2963 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
2964 && ret > 0) { // we wrote something
2965 // Limit MixerThread data processing to no more than twice the
2966 // expected processing rate.
2967 //
2968 // This helps prevent underruns with NuPlayer and other applications
2969 // which may set up buffers that are close to the minimum size, or use
2970 // deep buffers, and rely on a double-buffering sleep strategy to fill.
2971 //
2972 // The throttle smooths out sudden large data drains from the device,
2973 // e.g. when it comes out of standby, which often causes problems with
2974 // (1) mixer threads without a fast mixer (which has its own warm-up)
2975 // (2) minimum buffer sized tracks (even if the track is full,
2976 // the app won't fill fast enough to handle the sudden draw).
2977
2978 const int32_t deltaMs = delta / 1000000;
2979 const int32_t throttleMs = mHalfBufferMs - deltaMs;
2980 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
2981 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07002982 // notify of throttle start on verbose log
2983 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
2984 "mixer(%p) throttle begin:"
2985 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07002986 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07002987 mThreadThrottleTimeMs += throttleMs;
2988 } else {
2989 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
2990 if (diff > 0) {
2991 // notify of throttle end on debug log
2992 ALOGD("mixer(%p) throttle end: throttle time(%u)", this, diff);
2993 mThreadThrottleEndMs = mThreadThrottleTimeMs;
2994 }
Andy Hung08fb1742015-05-31 23:22:10 -07002995 }
2996 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002997 }
Eric Laurent81784c32012-11-19 14:55:58 -08002998
Eric Laurentbfb1b832013-01-07 09:53:42 -08002999 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003000 ATRACE_BEGIN("sleep");
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003001 usleep(mSleepTimeUs);
Glenn Kastene7754022014-10-31 12:11:26 -07003002 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003003 }
Eric Laurent81784c32012-11-19 14:55:58 -08003004 }
3005
3006 // Finally let go of removed track(s), without the lock held
3007 // since we can't guarantee the destructors won't acquire that
3008 // same lock. This will also mutate and push a new fast mixer state.
3009 threadLoop_removeTracks(tracksToRemove);
3010 tracksToRemove.clear();
3011
3012 // FIXME I don't understand the need for this here;
3013 // it was in the original code but maybe the
3014 // assignment in saveOutputTracks() makes this unnecessary?
3015 clearOutputTracks();
3016
3017 // Effect chains will be actually deleted here if they were removed from
3018 // mEffectChains list during mixing or effects processing
3019 effectChains.clear();
3020
3021 // FIXME Note that the above .clear() is no longer necessary since effectChains
3022 // is now local to this block, but will keep it for now (at least until merge done).
3023 }
3024
Eric Laurentbfb1b832013-01-07 09:53:42 -08003025 threadLoop_exit();
3026
Eric Laurentcf817a22014-08-04 20:36:31 -07003027 if (!mStandby) {
3028 threadLoop_standby();
3029 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003030 }
3031
3032 releaseWakeLock();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003033 mWakeLockUids.clear();
3034 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08003035
3036 ALOGV("Thread %p type %d exiting", this, mType);
3037 return false;
3038}
3039
Eric Laurentbfb1b832013-01-07 09:53:42 -08003040// removeTracks_l() must be called with ThreadBase::mLock held
3041void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3042{
3043 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07003044 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003045 for (size_t i=0 ; i<count ; i++) {
3046 const sp<Track>& track = tracksToRemove.itemAt(i);
3047 mActiveTracks.remove(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003048 mWakeLockUids.remove(track->uid());
3049 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003050 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
3051 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3052 if (chain != 0) {
3053 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
3054 track->sessionId());
3055 chain->decActiveTrackCnt();
3056 }
3057 if (track->isTerminated()) {
3058 removeTrack_l(track);
3059 }
3060 }
3061 }
3062
3063}
Eric Laurent81784c32012-11-19 14:55:58 -08003064
Eric Laurentaccc1472013-09-20 09:36:34 -07003065status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3066{
3067 if (mNormalSink != 0) {
3068 return mNormalSink->getTimestamp(timestamp);
3069 }
Andy Hung9a1c8892014-12-03 11:37:42 -08003070 if ((mType == OFFLOAD || mType == DIRECT)
3071 && mOutput != NULL && mOutput->stream->get_presentation_position) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003072 uint64_t position64;
Phil Burk062e67a2015-02-11 13:40:50 -08003073 int ret = mOutput->getPresentationPosition(&position64, &timestamp.mTime);
Eric Laurentaccc1472013-09-20 09:36:34 -07003074 if (ret == 0) {
3075 timestamp.mPosition = (uint32_t)position64;
3076 return NO_ERROR;
3077 }
3078 }
3079 return INVALID_OPERATION;
3080}
Eric Laurent1c333e22014-05-20 10:48:17 -07003081
Eric Laurent054d9d32015-04-24 08:48:48 -07003082status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
3083 audio_patch_handle_t *handle)
3084{
3085 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3086 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3087 if (mFastMixer != 0) {
3088 FastMixerStateQueue *sq = mFastMixer->sq();
3089 FastMixerState *state = sq->begin();
3090 if (!(state->mCommand & FastMixerState::IDLE)) {
3091 previousCommand = state->mCommand;
3092 state->mCommand = FastMixerState::HOT_IDLE;
3093 sq->end();
3094 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3095 } else {
3096 sq->end(false /*didModify*/);
3097 }
3098 }
3099 status_t status = PlaybackThread::createAudioPatch_l(patch, handle);
3100
3101 if (!(previousCommand & FastMixerState::IDLE)) {
3102 ALOG_ASSERT(mFastMixer != 0);
3103 FastMixerStateQueue *sq = mFastMixer->sq();
3104 FastMixerState *state = sq->begin();
3105 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3106 state->mCommand = previousCommand;
3107 sq->end();
3108 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3109 }
3110
3111 return status;
3112}
3113
Eric Laurent1c333e22014-05-20 10:48:17 -07003114status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3115 audio_patch_handle_t *handle)
3116{
3117 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003118
3119 // store new device and send to effects
3120 audio_devices_t type = AUDIO_DEVICE_NONE;
3121 for (unsigned int i = 0; i < patch->num_sinks; i++) {
3122 type |= patch->sinks[i].ext.device.type;
3123 }
3124
3125#ifdef ADD_BATTERY_DATA
3126 // when changing the audio output device, call addBatteryData to notify
3127 // the change
3128 if (mOutDevice != type) {
3129 uint32_t params = 0;
3130 // check whether speaker is on
3131 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3132 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003133 }
3134
Eric Laurent054d9d32015-04-24 08:48:48 -07003135 audio_devices_t deviceWithoutSpeaker
3136 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3137 // check if any other device (except speaker) is on
3138 if (type & deviceWithoutSpeaker) {
3139 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3140 }
3141
3142 if (params != 0) {
3143 addBatteryData(params);
3144 }
3145 }
3146#endif
3147
3148 for (size_t i = 0; i < mEffectChains.size(); i++) {
3149 mEffectChains[i]->setDevice_l(type);
3150 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003151
3152 // mPrevOutDevice is the latest device set by createAudioPatch_l(). It is not set when
3153 // the thread is created so that the first patch creation triggers an ioConfigChanged callback
3154 bool configChanged = mPrevOutDevice != type;
Eric Laurent054d9d32015-04-24 08:48:48 -07003155 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003156 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003157
3158 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003159 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
3160 status = hwDevice->create_audio_patch(hwDevice,
3161 patch->num_sources,
3162 patch->sources,
3163 patch->num_sinks,
3164 patch->sinks,
3165 handle);
3166 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003167 char *address;
3168 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3169 //FIXME: we only support address on first sink with HAL version < 3.0
3170 address = audio_device_address_to_parameter(
3171 patch->sinks[0].ext.device.type,
3172 patch->sinks[0].ext.device.address);
3173 } else {
3174 address = (char *)calloc(1, 1);
3175 }
3176 AudioParameter param = AudioParameter(String8(address));
3177 free(address);
3178 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), (int)type);
3179 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3180 param.toString().string());
3181 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003182 }
Eric Laurente8726fe2015-06-26 09:39:24 -07003183 if (configChanged) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003184 mPrevOutDevice = type;
Eric Laurente8726fe2015-06-26 09:39:24 -07003185 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
3186 }
Eric Laurent1c333e22014-05-20 10:48:17 -07003187 return status;
3188}
3189
Eric Laurent054d9d32015-04-24 08:48:48 -07003190status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3191{
3192 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3193 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3194 if (mFastMixer != 0) {
3195 FastMixerStateQueue *sq = mFastMixer->sq();
3196 FastMixerState *state = sq->begin();
3197 if (!(state->mCommand & FastMixerState::IDLE)) {
3198 previousCommand = state->mCommand;
3199 state->mCommand = FastMixerState::HOT_IDLE;
3200 sq->end();
3201 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3202 } else {
3203 sq->end(false /*didModify*/);
3204 }
3205 }
3206
3207 status_t status = PlaybackThread::releaseAudioPatch_l(handle);
3208
3209 if (!(previousCommand & FastMixerState::IDLE)) {
3210 ALOG_ASSERT(mFastMixer != 0);
3211 FastMixerStateQueue *sq = mFastMixer->sq();
3212 FastMixerState *state = sq->begin();
3213 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3214 state->mCommand = previousCommand;
3215 sq->end();
3216 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3217 }
3218
3219 return status;
3220}
3221
Eric Laurent1c333e22014-05-20 10:48:17 -07003222status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3223{
3224 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003225
3226 mOutDevice = AUDIO_DEVICE_NONE;
3227
Eric Laurent1c333e22014-05-20 10:48:17 -07003228 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
3229 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
3230 status = hwDevice->release_audio_patch(hwDevice, handle);
3231 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003232 AudioParameter param;
3233 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
3234 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3235 param.toString().string());
Eric Laurent1c333e22014-05-20 10:48:17 -07003236 }
3237 return status;
3238}
3239
Eric Laurent83b88082014-06-20 18:31:16 -07003240void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3241{
3242 Mutex::Autolock _l(mLock);
3243 mTracks.add(track);
3244}
3245
3246void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3247{
3248 Mutex::Autolock _l(mLock);
3249 destroyTrack_l(track);
3250}
3251
3252void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
3253{
3254 ThreadBase::getAudioPortConfig(config);
3255 config->role = AUDIO_PORT_ROLE_SOURCE;
3256 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3257 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
3258}
3259
Eric Laurent81784c32012-11-19 14:55:58 -08003260// ----------------------------------------------------------------------------
3261
3262AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurent72e3f392015-05-20 14:43:50 -07003263 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
3264 : PlaybackThread(audioFlinger, output, id, device, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08003265 // mAudioMixer below
3266 // mFastMixer below
3267 mFastMixerFutex(0)
3268 // mOutputSink below
3269 // mPipeSink below
3270 // mNormalSink below
3271{
3272 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07003273 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, "
Eric Laurent81784c32012-11-19 14:55:58 -08003274 "mFrameCount=%d, mNormalFrameCount=%d",
3275 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3276 mNormalFrameCount);
3277 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3278
Andy Hungfbfc3952015-01-15 13:33:51 -08003279 if (type == DUPLICATING) {
3280 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3281 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3282 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3283 return;
3284 }
Eric Laurent81784c32012-11-19 14:55:58 -08003285 // create an NBAIO sink for the HAL output stream, and negotiate
3286 mOutputSink = new AudioStreamOutSink(output->stream);
3287 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003288 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Eric Laurent81784c32012-11-19 14:55:58 -08003289 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
3290 ALOG_ASSERT(index == 0);
3291
3292 // initialize fast mixer depending on configuration
3293 bool initFastMixer;
3294 switch (kUseFastMixer) {
3295 case FastMixer_Never:
3296 initFastMixer = false;
3297 break;
3298 case FastMixer_Always:
3299 initFastMixer = true;
3300 break;
3301 case FastMixer_Static:
3302 case FastMixer_Dynamic:
3303 initFastMixer = mFrameCount < mNormalFrameCount;
3304 break;
3305 }
3306 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003307 audio_format_t fastMixerFormat;
3308 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3309 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3310 } else {
3311 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3312 }
3313 if (mFormat != fastMixerFormat) {
3314 // change our Sink format to accept our intermediate precision
3315 mFormat = fastMixerFormat;
3316 free(mSinkBuffer);
3317 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3318 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3319 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3320 }
Eric Laurent81784c32012-11-19 14:55:58 -08003321
3322 // create a MonoPipe to connect our submix to FastMixer
3323 NBAIO_Format format = mOutputSink->format();
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003324 NBAIO_Format origformat = format;
Andy Hung1258c1a2014-05-23 21:22:17 -07003325 // adjust format to match that of the Fast Mixer
Glenn Kasten97b7b752014-09-28 13:04:24 -07003326 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003327 format.mFormat = fastMixerFormat;
3328 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3329
Eric Laurent81784c32012-11-19 14:55:58 -08003330 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3331 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3332 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3333 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3334 const NBAIO_Format offers[1] = {format};
3335 size_t numCounterOffers = 0;
3336 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
3337 ALOG_ASSERT(index == 0);
3338 monoPipe->setAvgFrames((mScreenState & 1) ?
3339 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3340 mPipeSink = monoPipe;
3341
Glenn Kasten46909e72013-02-26 09:20:22 -08003342#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08003343 if (mTeeSinkOutputEnabled) {
3344 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003345 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
3346 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08003347 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003348 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003349 ALOG_ASSERT(index == 0);
3350 mTeeSink = teeSink;
3351 PipeReader *teeSource = new PipeReader(*teeSink);
3352 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003353 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003354 ALOG_ASSERT(index == 0);
3355 mTeeSource = teeSource;
3356 }
Glenn Kasten46909e72013-02-26 09:20:22 -08003357#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003358
3359 // create fast mixer and configure it initially with just one fast track for our submix
3360 mFastMixer = new FastMixer();
3361 FastMixerStateQueue *sq = mFastMixer->sq();
3362#ifdef STATE_QUEUE_DUMP
3363 sq->setObserverDump(&mStateQueueObserverDump);
3364 sq->setMutatorDump(&mStateQueueMutatorDump);
3365#endif
3366 FastMixerState *state = sq->begin();
3367 FastTrack *fastTrack = &state->mFastTracks[0];
3368 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3369 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3370 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003371 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3372 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003373 fastTrack->mGeneration++;
3374 state->mFastTracksGen++;
3375 state->mTrackMask = 1;
3376 // fast mixer will use the HAL output sink
3377 state->mOutputSink = mOutputSink.get();
3378 state->mOutputSinkGen++;
3379 state->mFrameCount = mFrameCount;
3380 state->mCommand = FastMixerState::COLD_IDLE;
3381 // already done in constructor initialization list
3382 //mFastMixerFutex = 0;
3383 state->mColdFutexAddr = &mFastMixerFutex;
3384 state->mColdGen++;
3385 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08003386#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003387 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08003388#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08003389 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3390 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003391 sq->end();
3392 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3393
3394 // start the fast mixer
3395 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3396 pid_t tid = mFastMixer->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003397 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003398
3399#ifdef AUDIO_WATCHDOG
3400 // create and start the watchdog
3401 mAudioWatchdog = new AudioWatchdog();
3402 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3403 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3404 tid = mAudioWatchdog->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003405 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003406#endif
3407
Eric Laurent81784c32012-11-19 14:55:58 -08003408 }
3409
3410 switch (kUseFastMixer) {
3411 case FastMixer_Never:
3412 case FastMixer_Dynamic:
3413 mNormalSink = mOutputSink;
3414 break;
3415 case FastMixer_Always:
3416 mNormalSink = mPipeSink;
3417 break;
3418 case FastMixer_Static:
3419 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3420 break;
3421 }
3422}
3423
3424AudioFlinger::MixerThread::~MixerThread()
3425{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003426 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003427 FastMixerStateQueue *sq = mFastMixer->sq();
3428 FastMixerState *state = sq->begin();
3429 if (state->mCommand == FastMixerState::COLD_IDLE) {
3430 int32_t old = android_atomic_inc(&mFastMixerFutex);
3431 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003432 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003433 }
3434 }
3435 state->mCommand = FastMixerState::EXIT;
3436 sq->end();
3437 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3438 mFastMixer->join();
3439 // Though the fast mixer thread has exited, it's state queue is still valid.
3440 // We'll use that extract the final state which contains one remaining fast track
3441 // corresponding to our sub-mix.
3442 state = sq->begin();
3443 ALOG_ASSERT(state->mTrackMask == 1);
3444 FastTrack *fastTrack = &state->mFastTracks[0];
3445 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3446 delete fastTrack->mBufferProvider;
3447 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003448 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003449#ifdef AUDIO_WATCHDOG
3450 if (mAudioWatchdog != 0) {
3451 mAudioWatchdog->requestExit();
3452 mAudioWatchdog->requestExitAndWait();
3453 mAudioWatchdog.clear();
3454 }
3455#endif
3456 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003457 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003458 delete mAudioMixer;
3459}
3460
3461
3462uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3463{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003464 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003465 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3466 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3467 }
3468 return latency;
3469}
3470
3471
3472void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3473{
3474 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3475}
3476
Eric Laurentbfb1b832013-01-07 09:53:42 -08003477ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003478{
3479 // FIXME we should only do one push per cycle; confirm this is true
3480 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003481 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003482 FastMixerStateQueue *sq = mFastMixer->sq();
3483 FastMixerState *state = sq->begin();
3484 if (state->mCommand != FastMixerState::MIX_WRITE &&
3485 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3486 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07003487
3488 // FIXME workaround for first HAL write being CPU bound on some devices
3489 ATRACE_BEGIN("write");
3490 mOutput->write((char *)mSinkBuffer, 0);
3491 ATRACE_END();
3492
Eric Laurent81784c32012-11-19 14:55:58 -08003493 int32_t old = android_atomic_inc(&mFastMixerFutex);
3494 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003495 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003496 }
3497#ifdef AUDIO_WATCHDOG
3498 if (mAudioWatchdog != 0) {
3499 mAudioWatchdog->resume();
3500 }
3501#endif
3502 }
3503 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08003504#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003505 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08003506 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08003507#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003508 sq->end();
3509 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3510 if (kUseFastMixer == FastMixer_Dynamic) {
3511 mNormalSink = mPipeSink;
3512 }
3513 } else {
3514 sq->end(false /*didModify*/);
3515 }
3516 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003517 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003518}
3519
3520void AudioFlinger::MixerThread::threadLoop_standby()
3521{
3522 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003523 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003524 FastMixerStateQueue *sq = mFastMixer->sq();
3525 FastMixerState *state = sq->begin();
3526 if (!(state->mCommand & FastMixerState::IDLE)) {
3527 state->mCommand = FastMixerState::COLD_IDLE;
3528 state->mColdFutexAddr = &mFastMixerFutex;
3529 state->mColdGen++;
3530 mFastMixerFutex = 0;
3531 sq->end();
3532 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3533 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3534 if (kUseFastMixer == FastMixer_Dynamic) {
3535 mNormalSink = mOutputSink;
3536 }
3537#ifdef AUDIO_WATCHDOG
3538 if (mAudioWatchdog != 0) {
3539 mAudioWatchdog->pause();
3540 }
3541#endif
3542 } else {
3543 sq->end(false /*didModify*/);
3544 }
3545 }
3546 PlaybackThread::threadLoop_standby();
3547}
3548
Eric Laurentbfb1b832013-01-07 09:53:42 -08003549bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3550{
3551 return false;
3552}
3553
3554bool AudioFlinger::PlaybackThread::shouldStandby_l()
3555{
3556 return !mStandby;
3557}
3558
3559bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3560{
3561 Mutex::Autolock _l(mLock);
3562 return waitingAsyncCallback_l();
3563}
3564
Eric Laurent81784c32012-11-19 14:55:58 -08003565// shared by MIXER and DIRECT, overridden by DUPLICATING
3566void AudioFlinger::PlaybackThread::threadLoop_standby()
3567{
3568 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08003569 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003570 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003571 // discard any pending drain or write ack by incrementing sequence
3572 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3573 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003574 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003575 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3576 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003577 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003578 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003579}
3580
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003581void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3582{
3583 ALOGV("signal playback thread");
3584 broadcast_l();
3585}
3586
Eric Laurent81784c32012-11-19 14:55:58 -08003587void AudioFlinger::MixerThread::threadLoop_mix()
3588{
3589 // obtain the presentation timestamp of the next output buffer
3590 int64_t pts;
3591 status_t status = INVALID_OPERATION;
3592
3593 if (mNormalSink != 0) {
3594 status = mNormalSink->getNextWriteTimestamp(&pts);
3595 } else {
3596 status = mOutputSink->getNextWriteTimestamp(&pts);
3597 }
3598
3599 if (status != NO_ERROR) {
3600 pts = AudioBufferProvider::kInvalidPTS;
3601 }
3602
3603 // mix buffers...
3604 mAudioMixer->process(pts);
Andy Hung25c2dac2014-02-27 14:56:00 -08003605 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003606 // increase sleep time progressively when application underrun condition clears.
3607 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3608 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3609 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003610 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003611 sleepTimeShift--;
3612 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003613 mSleepTimeUs = 0;
3614 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08003615 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003616
Eric Laurent81784c32012-11-19 14:55:58 -08003617}
3618
3619void AudioFlinger::MixerThread::threadLoop_sleepTime()
3620{
3621 // If no tracks are ready, sleep once for the duration of an output
3622 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003623 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003624 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003625 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
3626 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
3627 mSleepTimeUs = kMinThreadSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003628 }
3629 // reduce sleep time in case of consecutive application underruns to avoid
3630 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3631 // duration we would end up writing less data than needed by the audio HAL if
3632 // the condition persists.
3633 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3634 sleepTimeShift++;
3635 }
3636 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003637 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003638 }
3639 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003640 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3641 // before effects processing or output.
3642 if (mMixerBufferValid) {
3643 memset(mMixerBuffer, 0, mMixerBufferSize);
3644 } else {
3645 memset(mSinkBuffer, 0, mSinkBufferSize);
3646 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003647 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003648 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3649 "anticipated start");
3650 }
3651 // TODO add standby time extension fct of effect tail
3652}
3653
3654// prepareTracks_l() must be called with ThreadBase::mLock held
3655AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3656 Vector< sp<Track> > *tracksToRemove)
3657{
3658
3659 mixer_state mixerStatus = MIXER_IDLE;
3660 // find out which tracks need to be processed
3661 size_t count = mActiveTracks.size();
3662 size_t mixedTracks = 0;
3663 size_t tracksWithEffect = 0;
3664 // counts only _active_ fast tracks
3665 size_t fastTracks = 0;
3666 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
3667
3668 float masterVolume = mMasterVolume;
3669 bool masterMute = mMasterMute;
3670
3671 if (masterMute) {
3672 masterVolume = 0;
3673 }
3674 // Delegate master volume control to effect in output mix effect chain if needed
3675 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3676 if (chain != 0) {
3677 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
3678 chain->setVolume_l(&v, &v);
3679 masterVolume = (float)((v + (1 << 23)) >> 24);
3680 chain.clear();
3681 }
3682
3683 // prepare a new state to push
3684 FastMixerStateQueue *sq = NULL;
3685 FastMixerState *state = NULL;
3686 bool didModify = false;
3687 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003688 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003689 sq = mFastMixer->sq();
3690 state = sq->begin();
3691 }
3692
Andy Hung69aed5f2014-02-25 17:24:40 -08003693 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08003694 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08003695
Eric Laurent81784c32012-11-19 14:55:58 -08003696 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003697 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003698 if (t == 0) {
3699 continue;
3700 }
3701
3702 // this const just means the local variable doesn't change
3703 Track* const track = t.get();
3704
3705 // process fast tracks
3706 if (track->isFastTrack()) {
3707
3708 // It's theoretically possible (though unlikely) for a fast track to be created
3709 // and then removed within the same normal mix cycle. This is not a problem, as
3710 // the track never becomes active so it's fast mixer slot is never touched.
3711 // The converse, of removing an (active) track and then creating a new track
3712 // at the identical fast mixer slot within the same normal mix cycle,
3713 // is impossible because the slot isn't marked available until the end of each cycle.
3714 int j = track->mFastIndex;
3715 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
3716 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
3717 FastTrack *fastTrack = &state->mFastTracks[j];
3718
3719 // Determine whether the track is currently in underrun condition,
3720 // and whether it had a recent underrun.
3721 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
3722 FastTrackUnderruns underruns = ftDump->mUnderruns;
3723 uint32_t recentFull = (underruns.mBitFields.mFull -
3724 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
3725 uint32_t recentPartial = (underruns.mBitFields.mPartial -
3726 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
3727 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
3728 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
3729 uint32_t recentUnderruns = recentPartial + recentEmpty;
3730 track->mObservedUnderruns = underruns;
3731 // don't count underruns that occur while stopping or pausing
3732 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07003733 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
3734 recentUnderruns > 0) {
3735 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
3736 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003737 }
3738
3739 // This is similar to the state machine for normal tracks,
3740 // with a few modifications for fast tracks.
3741 bool isActive = true;
3742 switch (track->mState) {
3743 case TrackBase::STOPPING_1:
3744 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08003745 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003746 track->mState = TrackBase::STOPPING_2;
3747 }
3748 break;
3749 case TrackBase::PAUSING:
3750 // ramp down is not yet implemented
3751 track->setPaused();
3752 break;
3753 case TrackBase::RESUMING:
3754 // ramp up is not yet implemented
3755 track->mState = TrackBase::ACTIVE;
3756 break;
3757 case TrackBase::ACTIVE:
3758 if (recentFull > 0 || recentPartial > 0) {
3759 // track has provided at least some frames recently: reset retry count
3760 track->mRetryCount = kMaxTrackRetries;
3761 }
3762 if (recentUnderruns == 0) {
3763 // no recent underruns: stay active
3764 break;
3765 }
3766 // there has recently been an underrun of some kind
3767 if (track->sharedBuffer() == 0) {
3768 // were any of the recent underruns "empty" (no frames available)?
3769 if (recentEmpty == 0) {
3770 // no, then ignore the partial underruns as they are allowed indefinitely
3771 break;
3772 }
3773 // there has recently been an "empty" underrun: decrement the retry counter
3774 if (--(track->mRetryCount) > 0) {
3775 break;
3776 }
3777 // indicate to client process that the track was disabled because of underrun;
3778 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003779 android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003780 // remove from active list, but state remains ACTIVE [confusing but true]
3781 isActive = false;
3782 break;
3783 }
3784 // fall through
3785 case TrackBase::STOPPING_2:
3786 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003787 case TrackBase::STOPPED:
3788 case TrackBase::FLUSHED: // flush() while active
3789 // Check for presentation complete if track is inactive
3790 // We have consumed all the buffers of this track.
3791 // This would be incomplete if we auto-paused on underrun
3792 {
3793 size_t audioHALFrames =
3794 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3795 size_t framesWritten = mBytesWritten / mFrameSize;
3796 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
3797 // track stays in active list until presentation is complete
3798 break;
3799 }
3800 }
3801 if (track->isStopping_2()) {
3802 track->mState = TrackBase::STOPPED;
3803 }
3804 if (track->isStopped()) {
3805 // Can't reset directly, as fast mixer is still polling this track
3806 // track->reset();
3807 // So instead mark this track as needing to be reset after push with ack
3808 resetMask |= 1 << i;
3809 }
3810 isActive = false;
3811 break;
3812 case TrackBase::IDLE:
3813 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08003814 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08003815 }
3816
3817 if (isActive) {
3818 // was it previously inactive?
3819 if (!(state->mTrackMask & (1 << j))) {
3820 ExtendedAudioBufferProvider *eabp = track;
3821 VolumeProvider *vp = track;
3822 fastTrack->mBufferProvider = eabp;
3823 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08003824 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003825 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08003826 fastTrack->mGeneration++;
3827 state->mTrackMask |= 1 << j;
3828 didModify = true;
3829 // no acknowledgement required for newly active tracks
3830 }
3831 // cache the combined master volume and stream type volume for fast mixer; this
3832 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08003833 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08003834 ++fastTracks;
3835 } else {
3836 // was it previously active?
3837 if (state->mTrackMask & (1 << j)) {
3838 fastTrack->mBufferProvider = NULL;
3839 fastTrack->mGeneration++;
3840 state->mTrackMask &= ~(1 << j);
3841 didModify = true;
3842 // If any fast tracks were removed, we must wait for acknowledgement
3843 // because we're about to decrement the last sp<> on those tracks.
3844 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3845 } else {
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08003846 LOG_ALWAYS_FATAL("fast track %d should have been active; "
3847 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
3848 j, track->mState, state->mTrackMask, recentUnderruns,
3849 track->sharedBuffer() != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08003850 }
3851 tracksToRemove->add(track);
3852 // Avoids a misleading display in dumpsys
3853 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
3854 }
3855 continue;
3856 }
3857
3858 { // local variable scope to avoid goto warning
3859
3860 audio_track_cblk_t* cblk = track->cblk();
3861
3862 // The first time a track is added we wait
3863 // for all its buffers to be filled before processing it
3864 int name = track->name();
3865 // make sure that we have enough frames to mix one full buffer.
3866 // enforce this condition only once to enable draining the buffer in case the client
3867 // app does not call stop() and relies on underrun to stop:
3868 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
3869 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003870 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07003871 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07003872 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07003873
3874 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07003875 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07003876 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
3877 // add frames already consumed but not yet released by the resampler
3878 // because mAudioTrackServerProxy->framesReady() will include these frames
3879 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
3880
Eric Laurent81784c32012-11-19 14:55:58 -08003881 uint32_t minFrames = 1;
3882 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
3883 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003884 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08003885 }
Eric Laurent13e4c962013-12-20 17:36:01 -08003886
3887 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07003888 if (ATRACE_ENABLED()) {
3889 // I wish we had formatted trace names
3890 char traceName[16];
3891 strcpy(traceName, "nRdy");
3892 int name = track->name();
3893 if (AudioMixer::TRACK0 <= name &&
3894 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
3895 name -= AudioMixer::TRACK0;
3896 traceName[4] = (name / 10) + '0';
3897 traceName[5] = (name % 10) + '0';
3898 } else {
3899 traceName[4] = '?';
3900 traceName[5] = '?';
3901 }
3902 traceName[6] = '\0';
3903 ATRACE_INT(traceName, framesReady);
3904 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003905 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08003906 !track->isPaused() && !track->isTerminated())
3907 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003908 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003909
3910 mixedTracks++;
3911
Andy Hung69aed5f2014-02-25 17:24:40 -08003912 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
3913 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08003914 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08003915 if (track->mainBuffer() != mSinkBuffer &&
3916 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08003917 if (mEffectBufferEnabled) {
3918 mEffectBufferValid = true; // Later can set directly.
3919 }
Eric Laurent81784c32012-11-19 14:55:58 -08003920 chain = getEffectChain_l(track->sessionId());
3921 // Delegate volume control to effect in track effect chain if needed
3922 if (chain != 0) {
3923 tracksWithEffect++;
3924 } else {
3925 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
3926 "session %d",
3927 name, track->sessionId());
3928 }
3929 }
3930
3931
3932 int param = AudioMixer::VOLUME;
3933 if (track->mFillingUpStatus == Track::FS_FILLED) {
3934 // no ramp for the first volume setting
3935 track->mFillingUpStatus = Track::FS_ACTIVE;
3936 if (track->mState == TrackBase::RESUMING) {
3937 track->mState = TrackBase::ACTIVE;
3938 param = AudioMixer::RAMP_VOLUME;
3939 }
3940 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003941 // FIXME should not make a decision based on mServer
3942 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003943 // If the track is stopped before the first frame was mixed,
3944 // do not apply ramp
3945 param = AudioMixer::RAMP_VOLUME;
3946 }
3947
3948 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07003949 uint32_t vl, vr; // in U8.24 integer format
3950 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08003951 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07003952 vl = vr = 0;
3953 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08003954 if (track->isPausing()) {
3955 track->setPaused();
3956 }
3957 } else {
3958
3959 // read original volumes with volume control
3960 float typeVolume = mStreamTypes[track->streamType()].volume;
3961 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003962 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07003963 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07003964 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
3965 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08003966 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07003967 if (vlf > GAIN_FLOAT_UNITY) {
3968 ALOGV("Track left volume out of range: %.3g", vlf);
3969 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003970 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07003971 if (vrf > GAIN_FLOAT_UNITY) {
3972 ALOGV("Track right volume out of range: %.3g", vrf);
3973 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003974 }
3975 // now apply the master volume and stream type volume
Andy Hung6be49402014-05-30 10:42:03 -07003976 vlf *= v;
3977 vrf *= v;
Eric Laurent81784c32012-11-19 14:55:58 -08003978 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07003979 // then derive vl and vr as U8.24 versions for the effect chain
3980 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
3981 vl = (uint32_t) (scaleto8_24 * vlf);
3982 vr = (uint32_t) (scaleto8_24 * vrf);
3983 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08003984 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08003985 // send level comes from shared memory and so may be corrupt
3986 if (sendLevel > MAX_GAIN_INT) {
3987 ALOGV("Track send level out of range: %04X", sendLevel);
3988 sendLevel = MAX_GAIN_INT;
3989 }
Andy Hung6be49402014-05-30 10:42:03 -07003990 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
3991 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08003992 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003993
Eric Laurent81784c32012-11-19 14:55:58 -08003994 // Delegate volume control to effect in track effect chain if needed
3995 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3996 // Do not ramp volume if volume is controlled by effect
3997 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08003998 // Update remaining floating point volume levels
3999 vlf = (float)vl / (1 << 24);
4000 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08004001 track->mHasVolumeController = true;
4002 } else {
4003 // force no volume ramp when volume controller was just disabled or removed
4004 // from effect chain to avoid volume spike
4005 if (track->mHasVolumeController) {
4006 param = AudioMixer::VOLUME;
4007 }
4008 track->mHasVolumeController = false;
4009 }
4010
Eric Laurent81784c32012-11-19 14:55:58 -08004011 // XXX: these things DON'T need to be done each time
4012 mAudioMixer->setBufferProvider(name, track);
4013 mAudioMixer->enable(name);
4014
Andy Hung6be49402014-05-30 10:42:03 -07004015 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
4016 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
4017 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08004018 mAudioMixer->setParameter(
4019 name,
4020 AudioMixer::TRACK,
4021 AudioMixer::FORMAT, (void *)track->format());
4022 mAudioMixer->setParameter(
4023 name,
4024 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004025 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07004026 mAudioMixer->setParameter(
4027 name,
4028 AudioMixer::TRACK,
4029 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08004030 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07004031 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004032 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08004033 if (reqSampleRate == 0) {
4034 reqSampleRate = mSampleRate;
4035 } else if (reqSampleRate > maxSampleRate) {
4036 reqSampleRate = maxSampleRate;
4037 }
Eric Laurent81784c32012-11-19 14:55:58 -08004038 mAudioMixer->setParameter(
4039 name,
4040 AudioMixer::RESAMPLE,
4041 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004042 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004043
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004044 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004045 mAudioMixer->setParameter(
4046 name,
4047 AudioMixer::TIMESTRETCH,
4048 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004049 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004050
Andy Hung69aed5f2014-02-25 17:24:40 -08004051 /*
4052 * Select the appropriate output buffer for the track.
4053 *
Andy Hung98ef9782014-03-04 14:46:50 -08004054 * Tracks with effects go into their own effects chain buffer
4055 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08004056 *
4057 * Other tracks can use mMixerBuffer for higher precision
4058 * channel accumulation. If this buffer is enabled
4059 * (mMixerBufferEnabled true), then selected tracks will accumulate
4060 * into it.
4061 *
4062 */
4063 if (mMixerBufferEnabled
4064 && (track->mainBuffer() == mSinkBuffer
4065 || track->mainBuffer() == mMixerBuffer)) {
4066 mAudioMixer->setParameter(
4067 name,
4068 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004069 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08004070 mAudioMixer->setParameter(
4071 name,
4072 AudioMixer::TRACK,
4073 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
4074 // TODO: override track->mainBuffer()?
4075 mMixerBufferValid = true;
4076 } else {
4077 mAudioMixer->setParameter(
4078 name,
4079 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004080 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08004081 mAudioMixer->setParameter(
4082 name,
4083 AudioMixer::TRACK,
4084 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
4085 }
Eric Laurent81784c32012-11-19 14:55:58 -08004086 mAudioMixer->setParameter(
4087 name,
4088 AudioMixer::TRACK,
4089 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
4090
4091 // reset retry count
4092 track->mRetryCount = kMaxTrackRetries;
4093
4094 // If one track is ready, set the mixer ready if:
4095 // - the mixer was not ready during previous round OR
4096 // - no other track is not ready
4097 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
4098 mixerStatus != MIXER_TRACKS_ENABLED) {
4099 mixerStatus = MIXER_TRACKS_READY;
4100 }
4101 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004102 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hung08fb1742015-05-31 23:22:10 -07004103 ALOGV("track(%p) underrun, framesReady(%zu) < framesDesired(%zd)",
4104 track, framesReady, desiredFrames);
Glenn Kasten82aaf942013-07-17 16:05:07 -07004105 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004106 }
Eric Laurent81784c32012-11-19 14:55:58 -08004107 // clear effect chain input buffer if an active track underruns to avoid sending
4108 // previous audio buffer again to effects
4109 chain = getEffectChain_l(track->sessionId());
4110 if (chain != 0) {
4111 chain->clearInputBuffer();
4112 }
4113
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004114 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004115 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
4116 track->isStopped() || track->isPaused()) {
4117 // We have consumed all the buffers of this track.
4118 // Remove it from the list of active tracks.
4119 // TODO: use actual buffer filling status instead of latency when available from
4120 // audio HAL
4121 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
4122 size_t framesWritten = mBytesWritten / mFrameSize;
4123 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
4124 if (track->isStopped()) {
4125 track->reset();
4126 }
4127 tracksToRemove->add(track);
4128 }
4129 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08004130 // No buffers for this track. Give it a few chances to
4131 // fill a buffer, then remove it from active list.
4132 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004133 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004134 tracksToRemove->add(track);
4135 // indicate to client process that the track was disabled because of underrun;
4136 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07004137 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08004138 // If one track is not ready, mark the mixer also not ready if:
4139 // - the mixer was ready during previous round OR
4140 // - no other track is ready
4141 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
4142 mixerStatus != MIXER_TRACKS_READY) {
4143 mixerStatus = MIXER_TRACKS_ENABLED;
4144 }
4145 }
4146 mAudioMixer->disable(name);
4147 }
4148
4149 } // local variable scope to avoid goto warning
4150track_is_ready: ;
4151
4152 }
4153
4154 // Push the new FastMixer state if necessary
4155 bool pauseAudioWatchdog = false;
4156 if (didModify) {
4157 state->mFastTracksGen++;
4158 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4159 if (kUseFastMixer == FastMixer_Dynamic &&
4160 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4161 state->mCommand = FastMixerState::COLD_IDLE;
4162 state->mColdFutexAddr = &mFastMixerFutex;
4163 state->mColdGen++;
4164 mFastMixerFutex = 0;
4165 if (kUseFastMixer == FastMixer_Dynamic) {
4166 mNormalSink = mOutputSink;
4167 }
4168 // If we go into cold idle, need to wait for acknowledgement
4169 // so that fast mixer stops doing I/O.
4170 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4171 pauseAudioWatchdog = true;
4172 }
Eric Laurent81784c32012-11-19 14:55:58 -08004173 }
4174 if (sq != NULL) {
4175 sq->end(didModify);
4176 sq->push(block);
4177 }
4178#ifdef AUDIO_WATCHDOG
4179 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4180 mAudioWatchdog->pause();
4181 }
4182#endif
4183
4184 // Now perform the deferred reset on fast tracks that have stopped
4185 while (resetMask != 0) {
4186 size_t i = __builtin_ctz(resetMask);
4187 ALOG_ASSERT(i < count);
4188 resetMask &= ~(1 << i);
4189 sp<Track> t = mActiveTracks[i].promote();
4190 if (t == 0) {
4191 continue;
4192 }
4193 Track* track = t.get();
4194 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
4195 track->reset();
4196 }
4197
4198 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004199 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004200
Eric Laurent97d547d2014-09-02 14:45:53 -07004201 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
4202 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07004203 }
4204
4205 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07004206 // as long as there are effects we should clear the effects buffer, to avoid
4207 // passing a non-clean buffer to the effect chain
4208 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07004209 }
Andy Hung69aed5f2014-02-25 17:24:40 -08004210 // sink or mix buffer must be cleared if all tracks are connected to an
4211 // effect chain as in this case the mixer will not write to the sink or mix buffer
4212 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08004213 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4214 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08004215 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08004216 if (mMixerBufferValid) {
4217 memset(mMixerBuffer, 0, mMixerBufferSize);
4218 // TODO: In testing, mSinkBuffer below need not be cleared because
4219 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
4220 // after mixing.
4221 //
4222 // To enforce this guarantee:
4223 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4224 // (mixedTracks == 0 && fastTracks > 0))
4225 // must imply MIXER_TRACKS_READY.
4226 // Later, we may clear buffers regardless, and skip much of this logic.
4227 }
Andy Hung98ef9782014-03-04 14:46:50 -08004228 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07004229 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004230 }
4231
4232 // if any fast tracks, then status is ready
4233 mMixerStatusIgnoringFastTracks = mixerStatus;
4234 if (fastTracks > 0) {
4235 mixerStatus = MIXER_TRACKS_READY;
4236 }
4237 return mixerStatus;
4238}
4239
4240// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07004241int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
4242 audio_format_t format, int sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08004243{
Andy Hunge8a1ced2014-05-09 15:02:21 -07004244 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08004245}
4246
4247// deleteTrackName_l() must be called with ThreadBase::mLock held
4248void AudioFlinger::MixerThread::deleteTrackName_l(int name)
4249{
4250 ALOGV("remove track (%d) and delete from mixer", name);
4251 mAudioMixer->deleteTrackName(name);
4252}
4253
Eric Laurent10351942014-05-08 18:49:52 -07004254// checkForNewParameter_l() must be called with ThreadBase::mLock held
4255bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
4256 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004257{
Eric Laurent81784c32012-11-19 14:55:58 -08004258 bool reconfig = false;
4259
Eric Laurent10351942014-05-08 18:49:52 -07004260 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004261
Eric Laurent10351942014-05-08 18:49:52 -07004262 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
4263 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004264 if (mFastMixer != 0) {
Eric Laurent10351942014-05-08 18:49:52 -07004265 FastMixerStateQueue *sq = mFastMixer->sq();
4266 FastMixerState *state = sq->begin();
4267 if (!(state->mCommand & FastMixerState::IDLE)) {
4268 previousCommand = state->mCommand;
4269 state->mCommand = FastMixerState::HOT_IDLE;
4270 sq->end();
4271 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
4272 } else {
4273 sq->end(false /*didModify*/);
Eric Laurent81784c32012-11-19 14:55:58 -08004274 }
Eric Laurent10351942014-05-08 18:49:52 -07004275 }
Eric Laurent81784c32012-11-19 14:55:58 -08004276
Eric Laurent10351942014-05-08 18:49:52 -07004277 AudioParameter param = AudioParameter(keyValuePair);
4278 int value;
4279 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4280 reconfig = true;
4281 }
4282 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004283 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004284 status = BAD_VALUE;
4285 } else {
4286 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08004287 reconfig = true;
4288 }
Eric Laurent10351942014-05-08 18:49:52 -07004289 }
4290 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004291 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004292 status = BAD_VALUE;
4293 } else {
4294 // no need to save value, since it's constant
4295 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004296 }
Eric Laurent10351942014-05-08 18:49:52 -07004297 }
4298 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4299 // do not accept frame count changes if tracks are open as the track buffer
4300 // size depends on frame count and correct behavior would not be guaranteed
4301 // if frame count is changed after track creation
4302 if (!mTracks.isEmpty()) {
4303 status = INVALID_OPERATION;
4304 } else {
4305 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004306 }
Eric Laurent10351942014-05-08 18:49:52 -07004307 }
4308 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004309#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07004310 // when changing the audio output device, call addBatteryData to notify
4311 // the change
4312 if (mOutDevice != value) {
4313 uint32_t params = 0;
4314 // check whether speaker is on
4315 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
4316 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08004317 }
Eric Laurent10351942014-05-08 18:49:52 -07004318
4319 audio_devices_t deviceWithoutSpeaker
4320 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
4321 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07004322 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07004323 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4324 }
4325
4326 if (params != 0) {
4327 addBatteryData(params);
4328 }
4329 }
Eric Laurent81784c32012-11-19 14:55:58 -08004330#endif
4331
Eric Laurent10351942014-05-08 18:49:52 -07004332 // forward device change to effects that have requested to be
4333 // aware of attached audio device.
4334 if (value != AUDIO_DEVICE_NONE) {
4335 mOutDevice = value;
4336 for (size_t i = 0; i < mEffectChains.size(); i++) {
4337 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08004338 }
4339 }
Eric Laurent10351942014-05-08 18:49:52 -07004340 }
Eric Laurent81784c32012-11-19 14:55:58 -08004341
Eric Laurent10351942014-05-08 18:49:52 -07004342 if (status == NO_ERROR) {
4343 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4344 keyValuePair.string());
4345 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004346 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004347 mStandby = true;
4348 mBytesWritten = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004349 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Eric Laurent10351942014-05-08 18:49:52 -07004350 keyValuePair.string());
Eric Laurent81784c32012-11-19 14:55:58 -08004351 }
Eric Laurent10351942014-05-08 18:49:52 -07004352 if (status == NO_ERROR && reconfig) {
4353 readOutputParameters_l();
4354 delete mAudioMixer;
4355 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4356 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07004357 int name = getTrackName_l(mTracks[i]->mChannelMask,
4358 mTracks[i]->mFormat, mTracks[i]->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07004359 if (name < 0) {
4360 break;
4361 }
4362 mTracks[i]->mName = name;
4363 }
Eric Laurent73e26b62015-04-27 16:55:58 -07004364 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004365 }
Eric Laurent81784c32012-11-19 14:55:58 -08004366 }
4367
4368 if (!(previousCommand & FastMixerState::IDLE)) {
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004369 ALOG_ASSERT(mFastMixer != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08004370 FastMixerStateQueue *sq = mFastMixer->sq();
4371 FastMixerState *state = sq->begin();
4372 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
4373 state->mCommand = previousCommand;
4374 sq->end();
4375 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4376 }
4377
4378 return reconfig;
4379}
4380
4381
4382void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
4383{
4384 const size_t SIZE = 256;
4385 char buffer[SIZE];
4386 String8 result;
4387
4388 PlaybackThread::dumpInternals(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07004389 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Elliott Hughes87cebad2014-05-22 10:14:43 -07004390 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Eric Laurent81784c32012-11-19 14:55:58 -08004391
4392 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten4182c4e2013-07-15 14:45:07 -07004393 const FastMixerDumpState copy(mFastMixerDumpState);
Eric Laurent81784c32012-11-19 14:55:58 -08004394 copy.dump(fd);
4395
4396#ifdef STATE_QUEUE_DUMP
4397 // Similar for state queue
4398 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4399 observerCopy.dump(fd);
4400 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4401 mutatorCopy.dump(fd);
4402#endif
4403
Glenn Kasten46909e72013-02-26 09:20:22 -08004404#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08004405 // Write the tee output to a .wav file
4406 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08004407#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004408
4409#ifdef AUDIO_WATCHDOG
4410 if (mAudioWatchdog != 0) {
4411 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4412 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4413 wdCopy.dump(fd);
4414 }
4415#endif
4416}
4417
4418uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4419{
4420 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4421}
4422
4423uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4424{
4425 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4426}
4427
4428void AudioFlinger::MixerThread::cacheParameters_l()
4429{
4430 PlaybackThread::cacheParameters_l();
4431
4432 // FIXME: Relaxed timing because of a certain device that can't meet latency
4433 // Should be reduced to 2x after the vendor fixes the driver issue
4434 // increase threshold again due to low power audio mode. The way this warning
4435 // threshold is calculated and its usefulness should be reconsidered anyway.
4436 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4437}
4438
4439// ----------------------------------------------------------------------------
4440
4441AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07004442 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device, bool systemReady)
4443 : PlaybackThread(audioFlinger, output, id, device, DIRECT, systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08004444 // mLeftVolFloat, mRightVolFloat
4445{
4446}
4447
Eric Laurentbfb1b832013-01-07 09:53:42 -08004448AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4449 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07004450 ThreadBase::type_t type, bool systemReady)
4451 : PlaybackThread(audioFlinger, output, id, device, type, systemReady)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004452 // mLeftVolFloat, mRightVolFloat
4453{
4454}
4455
Eric Laurent81784c32012-11-19 14:55:58 -08004456AudioFlinger::DirectOutputThread::~DirectOutputThread()
4457{
4458}
4459
Eric Laurentbfb1b832013-01-07 09:53:42 -08004460void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
4461{
4462 audio_track_cblk_t* cblk = track->cblk();
4463 float left, right;
4464
4465 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4466 left = right = 0;
4467 } else {
4468 float typeVolume = mStreamTypes[track->streamType()].volume;
4469 float v = mMasterVolume * typeVolume;
4470 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004471 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4472 left = float_from_gain(gain_minifloat_unpack_left(vlr));
4473 if (left > GAIN_FLOAT_UNITY) {
4474 left = GAIN_FLOAT_UNITY;
4475 }
4476 left *= v;
4477 right = float_from_gain(gain_minifloat_unpack_right(vlr));
4478 if (right > GAIN_FLOAT_UNITY) {
4479 right = GAIN_FLOAT_UNITY;
4480 }
4481 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004482 }
4483
4484 if (lastTrack) {
4485 if (left != mLeftVolFloat || right != mRightVolFloat) {
4486 mLeftVolFloat = left;
4487 mRightVolFloat = right;
4488
4489 // Convert volumes from float to 8.24
4490 uint32_t vl = (uint32_t)(left * (1 << 24));
4491 uint32_t vr = (uint32_t)(right * (1 << 24));
4492
4493 // Delegate volume control to effect in track effect chain if needed
4494 // only one effect chain can be present on DirectOutputThread, so if
4495 // there is one, the track is connected to it
4496 if (!mEffectChains.isEmpty()) {
4497 mEffectChains[0]->setVolume_l(&vl, &vr);
4498 left = (float)vl / (1 << 24);
4499 right = (float)vr / (1 << 24);
4500 }
4501 if (mOutput->stream->set_volume) {
4502 mOutput->stream->set_volume(mOutput->stream, left, right);
4503 }
4504 }
4505 }
4506}
4507
Phil Burk43b4dcc2015-06-09 16:53:44 -07004508void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
4509{
4510 sp<Track> previousTrack = mPreviousTrack.promote();
4511 sp<Track> latestTrack = mLatestActiveTrack.promote();
4512
Eric Laurent0f0631e2015-07-06 18:01:25 -07004513 if (previousTrack != 0 && latestTrack != 0) {
4514 if (mType == DIRECT) {
4515 if (previousTrack.get() != latestTrack.get()) {
4516 mFlushPending = true;
4517 }
4518 } else /* mType == OFFLOAD */ {
4519 if (previousTrack->sessionId() != latestTrack->sessionId()) {
4520 mFlushPending = true;
4521 }
4522 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004523 }
4524 PlaybackThread::onAddNewTrack_l();
4525}
Eric Laurentbfb1b832013-01-07 09:53:42 -08004526
Eric Laurent81784c32012-11-19 14:55:58 -08004527AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4528 Vector< sp<Track> > *tracksToRemove
4529)
4530{
Eric Laurentd595b7c2013-04-03 17:27:56 -07004531 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08004532 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004533 bool doHwPause = false;
4534 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004535
4536 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07004537 for (size_t i = 0; i < count; i++) {
4538 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08004539 // The track died recently
4540 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004541 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08004542 }
4543
Phil Burk43b4dcc2015-06-09 16:53:44 -07004544 if (t->isInvalid()) {
4545 ALOGW("An invalidated track shouldn't be in active list");
4546 tracksToRemove->add(t);
4547 continue;
4548 }
4549
Eric Laurent81784c32012-11-19 14:55:58 -08004550 Track* const track = t.get();
4551 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07004552 // Only consider last track started for volume and mixer state control.
4553 // In theory an older track could underrun and restart after the new one starts
4554 // but as we only care about the transition phase between two tracks on a
4555 // direct output, it is not a problem to ignore the underrun case.
4556 sp<Track> l = mLatestActiveTrack.promote();
4557 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08004558
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004559 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004560 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004561 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004562 doHwPause = true;
4563 mHwPaused = true;
4564 }
4565 tracksToRemove->add(track);
4566 } else if (track->isFlushPending()) {
4567 track->flushAck();
4568 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004569 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004570 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004571 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004572 track->resumeAck();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004573 if (last && mHwPaused) {
4574 doHwResume = true;
4575 mHwPaused = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004576 }
4577 }
4578
Eric Laurent81784c32012-11-19 14:55:58 -08004579 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08004580 // for all its buffers to be filled before processing it.
4581 // Allow draining the buffer in case the client
4582 // app does not call stop() and relies on underrun to stop:
4583 // hence the test on (track->mRetryCount > 1).
4584 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07004585 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08004586 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08004587 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkca5e6142015-07-14 09:42:29 -07004588 && (track->mRetryCount > 1) && audio_is_linear_pcm(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004589 minFrames = mNormalFrameCount;
4590 } else {
4591 minFrames = 1;
4592 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004593
Eric Laurentab5cdba2014-06-09 17:22:27 -07004594 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4595 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08004596 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004597 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08004598
4599 if (track->mFillingUpStatus == Track::FS_FILLED) {
4600 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004601 // make sure processVolume_l() will apply new volume even if 0
4602 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004603 if (!mHwSupportsPause) {
4604 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08004605 }
4606 }
4607
4608 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004609 processVolume_l(track, last);
4610 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004611 sp<Track> previousTrack = mPreviousTrack.promote();
4612 if (previousTrack != 0) {
4613 if (track != previousTrack.get()) {
4614 // Flush any data still being written from last track
4615 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07004616 // Invalidate previous track to force a seek when resuming.
4617 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004618 }
4619 }
4620 mPreviousTrack = track;
4621
Eric Laurentd595b7c2013-04-03 17:27:56 -07004622 // reset retry count
4623 track->mRetryCount = kMaxTrackRetriesDirect;
4624 mActiveTrack = t;
4625 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07004626 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004627 doHwResume = true;
4628 mHwPaused = false;
4629 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004630 }
Eric Laurent81784c32012-11-19 14:55:58 -08004631 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004632 // clear effect chain input buffer if the last active track started underruns
4633 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07004634 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004635 mEffectChains[0]->clearInputBuffer();
4636 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004637 if (track->isStopping_1()) {
4638 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07004639 if (last && mHwPaused) {
4640 doHwResume = true;
4641 mHwPaused = false;
4642 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004643 }
4644 if ((track->sharedBuffer() != 0) || track->isStopped() ||
4645 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004646 // We have consumed all the buffers of this track.
4647 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07004648 size_t audioHALFrames;
4649 if (audio_is_linear_pcm(mFormat)) {
4650 audioHALFrames = (latency_l() * mSampleRate) / 1000;
4651 } else {
4652 audioHALFrames = 0;
4653 }
4654
Eric Laurent81784c32012-11-19 14:55:58 -08004655 size_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07004656 if (mStandby || !last ||
4657 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004658 if (track->isStopping_2()) {
4659 track->mState = TrackBase::STOPPED;
4660 }
Eric Laurent81784c32012-11-19 14:55:58 -08004661 if (track->isStopped()) {
4662 track->reset();
4663 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004664 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08004665 }
4666 } else {
4667 // No buffers for this track. Give it a few chances to
4668 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07004669 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08004670 if (--(track->mRetryCount) <= 0) {
4671 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07004672 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004673 // indicate to client process that the track was disabled because of underrun;
4674 // it will then automatically call start() when data is available
4675 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004676 } else if (last) {
Phil Burkca5e6142015-07-14 09:42:29 -07004677 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
4678 "minFrames = %u, mFormat = %#x",
4679 track->framesReady(), minFrames, mFormat);
Eric Laurent81784c32012-11-19 14:55:58 -08004680 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07004681 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004682 doHwPause = true;
4683 mHwPaused = true;
4684 }
Eric Laurent81784c32012-11-19 14:55:58 -08004685 }
4686 }
4687 }
4688 }
4689
Eric Laurentd1f69b02014-12-15 14:33:13 -08004690 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07004691 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004692 for (size_t i = 0; i < mTracks.size(); i++) {
4693 if (mTracks[i]->isFlushPending()) {
4694 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004695 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004696 }
4697 }
4698 }
4699
4700 // make sure the pause/flush/resume sequence is executed in the right order.
4701 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4702 // before flush and then resume HW. This can happen in case of pause/flush/resume
4703 // if resume is received before pause is executed.
4704 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07004705 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004706 mOutput->stream->pause(mOutput->stream);
4707 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004708 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004709 flushHw_l();
4710 }
4711 if (mHwSupportsPause && !mStandby && doHwResume) {
4712 mOutput->stream->resume(mOutput->stream);
4713 }
Eric Laurent81784c32012-11-19 14:55:58 -08004714 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004715 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004716
4717 return mixerStatus;
4718}
4719
4720void AudioFlinger::DirectOutputThread::threadLoop_mix()
4721{
Eric Laurent81784c32012-11-19 14:55:58 -08004722 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08004723 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004724 // output audio to hardware
4725 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07004726 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004727 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08004728 status_t status = mActiveTrack->getNextBuffer(&buffer);
4729 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08004730 memset(curBuf, 0, frameCount * mFrameSize);
4731 break;
4732 }
4733 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
4734 frameCount -= buffer.frameCount;
4735 curBuf += buffer.frameCount * mFrameSize;
4736 mActiveTrack->releaseBuffer(&buffer);
4737 }
Andy Hung2098f272014-02-27 14:00:06 -08004738 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004739 mSleepTimeUs = 0;
4740 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08004741 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004742}
4743
4744void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
4745{
Eric Laurentd1f69b02014-12-15 14:33:13 -08004746 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004747 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004748 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004749 return;
4750 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004751 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004752 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004753 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004754 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004755 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004756 }
4757 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08004758 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004759 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004760 }
4761}
4762
Eric Laurentd1f69b02014-12-15 14:33:13 -08004763void AudioFlinger::DirectOutputThread::threadLoop_exit()
4764{
4765 {
4766 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08004767 for (size_t i = 0; i < mTracks.size(); i++) {
4768 if (mTracks[i]->isFlushPending()) {
4769 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004770 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004771 }
4772 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004773 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004774 flushHw_l();
4775 }
4776 }
4777 PlaybackThread::threadLoop_exit();
4778}
4779
4780// must be called with thread mutex locked
4781bool AudioFlinger::DirectOutputThread::shouldStandby_l()
4782{
4783 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07004784 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004785
4786 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4787 // after a timeout and we will enter standby then.
4788 if (mTracks.size() > 0) {
4789 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07004790 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
4791 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004792 }
4793
Eric Laurent5cff4032015-05-26 13:49:58 -07004794 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08004795}
4796
Eric Laurent81784c32012-11-19 14:55:58 -08004797// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004798int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Andy Hunge8a1ced2014-05-09 15:02:21 -07004799 audio_format_t format __unused, int sessionId __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004800{
4801 return 0;
4802}
4803
4804// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004805void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004806{
4807}
4808
Eric Laurent10351942014-05-08 18:49:52 -07004809// checkForNewParameter_l() must be called with ThreadBase::mLock held
4810bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
4811 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004812{
4813 bool reconfig = false;
4814
Eric Laurent10351942014-05-08 18:49:52 -07004815 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004816
Eric Laurent10351942014-05-08 18:49:52 -07004817 AudioParameter param = AudioParameter(keyValuePair);
4818 int value;
4819 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4820 // forward device change to effects that have requested to be
4821 // aware of attached audio device.
4822 if (value != AUDIO_DEVICE_NONE) {
4823 mOutDevice = value;
4824 for (size_t i = 0; i < mEffectChains.size(); i++) {
4825 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07004826 }
4827 }
Eric Laurent81784c32012-11-19 14:55:58 -08004828 }
Eric Laurent10351942014-05-08 18:49:52 -07004829 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4830 // do not accept frame count changes if tracks are open as the track buffer
4831 // size depends on frame count and correct behavior would not be garantied
4832 // if frame count is changed after track creation
4833 if (!mTracks.isEmpty()) {
4834 status = INVALID_OPERATION;
4835 } else {
4836 reconfig = true;
4837 }
4838 }
4839 if (status == NO_ERROR) {
4840 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4841 keyValuePair.string());
4842 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004843 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004844 mStandby = true;
4845 mBytesWritten = 0;
4846 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4847 keyValuePair.string());
4848 }
4849 if (status == NO_ERROR && reconfig) {
4850 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07004851 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004852 }
4853 }
4854
Eric Laurent81784c32012-11-19 14:55:58 -08004855 return reconfig;
4856}
4857
4858uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
4859{
4860 uint32_t time;
4861 if (audio_is_linear_pcm(mFormat)) {
4862 time = PlaybackThread::activeSleepTimeUs();
4863 } else {
4864 time = 10000;
4865 }
4866 return time;
4867}
4868
4869uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
4870{
4871 uint32_t time;
4872 if (audio_is_linear_pcm(mFormat)) {
4873 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
4874 } else {
4875 time = 10000;
4876 }
4877 return time;
4878}
4879
4880uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
4881{
4882 uint32_t time;
4883 if (audio_is_linear_pcm(mFormat)) {
4884 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
4885 } else {
4886 time = 10000;
4887 }
4888 return time;
4889}
4890
4891void AudioFlinger::DirectOutputThread::cacheParameters_l()
4892{
4893 PlaybackThread::cacheParameters_l();
4894
4895 // use shorter standby delay as on normal output to release
4896 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07004897 // no delay on outputs with HW A/V sync
4898 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004899 mStandbyDelayNs = 0;
Eric Laurent5cff4032015-05-26 13:49:58 -07004900 } else if ((mType == OFFLOAD) && !audio_is_linear_pcm(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004901 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07004902 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004903 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07004904 }
Eric Laurent81784c32012-11-19 14:55:58 -08004905}
4906
Eric Laurente659ef42014-09-29 13:06:46 -07004907void AudioFlinger::DirectOutputThread::flushHw_l()
4908{
Phil Burk062e67a2015-02-11 13:40:50 -08004909 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08004910 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07004911 mFlushPending = false;
Eric Laurente659ef42014-09-29 13:06:46 -07004912}
4913
Eric Laurent81784c32012-11-19 14:55:58 -08004914// ----------------------------------------------------------------------------
4915
Eric Laurentbfb1b832013-01-07 09:53:42 -08004916AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07004917 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004918 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07004919 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07004920 mWriteAckSequence(0),
4921 mDrainSequence(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004922{
4923}
4924
4925AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
4926{
4927}
4928
4929void AudioFlinger::AsyncCallbackThread::onFirstRef()
4930{
4931 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
4932}
4933
4934bool AudioFlinger::AsyncCallbackThread::threadLoop()
4935{
4936 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004937 uint32_t writeAckSequence;
4938 uint32_t drainSequence;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004939
4940 {
4941 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08004942 while (!((mWriteAckSequence & 1) ||
4943 (mDrainSequence & 1) ||
4944 exitPending())) {
4945 mWaitWorkCV.wait(mLock);
4946 }
4947
Eric Laurentbfb1b832013-01-07 09:53:42 -08004948 if (exitPending()) {
4949 break;
4950 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004951 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
4952 mWriteAckSequence, mDrainSequence);
4953 writeAckSequence = mWriteAckSequence;
4954 mWriteAckSequence &= ~1;
4955 drainSequence = mDrainSequence;
4956 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004957 }
4958 {
Eric Laurent4de95592013-09-26 15:28:21 -07004959 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
4960 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004961 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004962 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004963 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004964 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004965 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004966 }
4967 }
4968 }
4969 }
4970 return false;
4971}
4972
4973void AudioFlinger::AsyncCallbackThread::exit()
4974{
4975 ALOGV("AsyncCallbackThread::exit");
4976 Mutex::Autolock _l(mLock);
4977 requestExit();
4978 mWaitWorkCV.broadcast();
4979}
4980
Eric Laurent3b4529e2013-09-05 18:09:19 -07004981void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004982{
4983 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004984 // bit 0 is cleared
4985 mWriteAckSequence = sequence << 1;
4986}
4987
4988void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
4989{
4990 Mutex::Autolock _l(mLock);
4991 // ignore unexpected callbacks
4992 if (mWriteAckSequence & 2) {
4993 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004994 mWaitWorkCV.signal();
4995 }
4996}
4997
Eric Laurent3b4529e2013-09-05 18:09:19 -07004998void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004999{
5000 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005001 // bit 0 is cleared
5002 mDrainSequence = sequence << 1;
5003}
5004
5005void AudioFlinger::AsyncCallbackThread::resetDraining()
5006{
5007 Mutex::Autolock _l(mLock);
5008 // ignore unexpected callbacks
5009 if (mDrainSequence & 2) {
5010 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005011 mWaitWorkCV.signal();
5012 }
5013}
5014
5015
5016// ----------------------------------------------------------------------------
5017AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07005018 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady)
5019 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady),
Eric Laurentd7e59222013-11-15 12:02:28 -08005020 mPausedBytesRemaining(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005021{
Eric Laurentfd477972013-10-25 18:10:40 -07005022 //FIXME: mStandby should be set to true by ThreadBase constructor
5023 mStandby = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005024}
5025
Eric Laurentbfb1b832013-01-07 09:53:42 -08005026void AudioFlinger::OffloadThread::threadLoop_exit()
5027{
5028 if (mFlushPending || mHwPaused) {
5029 // If a flush is pending or track was paused, just discard buffered data
5030 flushHw_l();
5031 } else {
5032 mMixerStatus = MIXER_DRAIN_ALL;
5033 threadLoop_drain();
5034 }
Uday Gupta56604aa2014-05-13 11:19:17 -07005035 if (mUseAsyncWrite) {
5036 ALOG_ASSERT(mCallbackThread != 0);
5037 mCallbackThread->exit();
5038 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005039 PlaybackThread::threadLoop_exit();
5040}
5041
5042AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
5043 Vector< sp<Track> > *tracksToRemove
5044)
5045{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005046 size_t count = mActiveTracks.size();
5047
5048 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07005049 bool doHwPause = false;
5050 bool doHwResume = false;
5051
Eric Laurentede6c3b2013-09-19 14:37:46 -07005052 ALOGV("OffloadThread::prepareTracks_l active tracks %d", count);
5053
Eric Laurentbfb1b832013-01-07 09:53:42 -08005054 // find out which tracks need to be processed
5055 for (size_t i = 0; i < count; i++) {
5056 sp<Track> t = mActiveTracks[i].promote();
5057 // The track died recently
5058 if (t == 0) {
5059 continue;
5060 }
5061 Track* const track = t.get();
5062 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07005063 // Only consider last track started for volume and mixer state control.
5064 // In theory an older track could underrun and restart after the new one starts
5065 // but as we only care about the transition phase between two tracks on a
5066 // direct output, it is not a problem to ignore the underrun case.
5067 sp<Track> l = mLatestActiveTrack.promote();
5068 bool last = l.get() == track;
5069
Haynes Mathew George7844f672014-01-15 12:32:55 -08005070 if (track->isInvalid()) {
5071 ALOGW("An invalidated track shouldn't be in active list");
5072 tracksToRemove->add(track);
5073 continue;
5074 }
5075
5076 if (track->mState == TrackBase::IDLE) {
5077 ALOGW("An idle track shouldn't be in active list");
5078 continue;
5079 }
5080
Eric Laurentbfb1b832013-01-07 09:53:42 -08005081 if (track->isPausing()) {
5082 track->setPaused();
5083 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07005084 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07005085 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005086 mHwPaused = true;
5087 }
5088 // If we were part way through writing the mixbuffer to
5089 // the HAL we must save this until we resume
5090 // BUG - this will be wrong if a different track is made active,
5091 // in that case we want to discard the pending data in the
5092 // mixbuffer and tell the client to present it again when the
5093 // track is resumed
5094 mPausedWriteLength = mCurrentWriteLength;
5095 mPausedBytesRemaining = mBytesRemaining;
5096 mBytesRemaining = 0; // stop writing
5097 }
5098 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08005099 } else if (track->isFlushPending()) {
5100 track->flushAck();
5101 if (last) {
5102 mFlushPending = true;
5103 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005104 } else if (track->isResumePending()){
5105 track->resumeAck();
5106 if (last) {
5107 if (mPausedBytesRemaining) {
5108 // Need to continue write that was interrupted
5109 mCurrentWriteLength = mPausedWriteLength;
5110 mBytesRemaining = mPausedBytesRemaining;
5111 mPausedBytesRemaining = 0;
5112 }
5113 if (mHwPaused) {
5114 doHwResume = true;
5115 mHwPaused = false;
5116 // threadLoop_mix() will handle the case that we need to
5117 // resume an interrupted write
5118 }
5119 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005120 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005121
5122 // Do not handle new data in this iteration even if track->framesReady()
5123 mixerStatus = MIXER_TRACKS_ENABLED;
5124 }
5125 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07005126 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005127 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005128 if (track->mFillingUpStatus == Track::FS_FILLED) {
5129 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07005130 // make sure processVolume_l() will apply new volume even if 0
5131 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005132 }
5133
5134 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08005135 sp<Track> previousTrack = mPreviousTrack.promote();
5136 if (previousTrack != 0) {
5137 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08005138 // Flush any data still being written from last track
5139 mBytesRemaining = 0;
5140 if (mPausedBytesRemaining) {
5141 // Last track was paused so we also need to flush saved
5142 // mixbuffer state and invalidate track so that it will
5143 // re-submit that unwritten data when it is next resumed
5144 mPausedBytesRemaining = 0;
5145 // Invalidate is a bit drastic - would be more efficient
5146 // to have a flag to tell client that some of the
5147 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08005148 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005149 }
5150 // flush data already sent to the DSP if changing audio session as audio
5151 // comes from a different source. Also invalidate previous track to force a
5152 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08005153 if (previousTrack->sessionId() != track->sessionId()) {
5154 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005155 }
5156 }
5157 }
5158 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005159 // reset retry count
5160 track->mRetryCount = kMaxTrackRetriesOffload;
5161 mActiveTrack = t;
5162 mixerStatus = MIXER_TRACKS_READY;
5163 }
5164 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005165 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005166 if (track->isStopping_1()) {
5167 // Hardware buffer can hold a large amount of audio so we must
5168 // wait for all current track's data to drain before we say
5169 // that the track is stopped.
5170 if (mBytesRemaining == 0) {
5171 // Only start draining when all data in mixbuffer
5172 // has been written
5173 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
5174 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005175 // do not drain if no data was ever sent to HAL (mStandby == true)
5176 if (last && !mStandby) {
Eric Laurent1b9f9b12013-11-12 19:10:17 -08005177 // do not modify drain sequence if we are already draining. This happens
5178 // when resuming from pause after drain.
5179 if ((mDrainSequence & 1) == 0) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005180 mSleepTimeUs = 0;
5181 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent1b9f9b12013-11-12 19:10:17 -08005182 mixerStatus = MIXER_DRAIN_TRACK;
5183 mDrainSequence += 2;
5184 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005185 if (mHwPaused) {
5186 // It is possible to move from PAUSED to STOPPING_1 without
5187 // a resume so we must ensure hardware is running
Eric Laurent1b9f9b12013-11-12 19:10:17 -08005188 doHwResume = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005189 mHwPaused = false;
5190 }
5191 }
5192 }
5193 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005194 // Drain has completed or we are in standby, signal presentation complete
5195 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005196 track->mState = TrackBase::STOPPED;
5197 size_t audioHALFrames =
5198 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
5199 size_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08005200 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005201 track->presentationComplete(framesWritten, audioHALFrames);
5202 track->reset();
5203 tracksToRemove->add(track);
5204 }
5205 } else {
5206 // No buffers for this track. Give it a few chances to
5207 // fill a buffer, then remove it from active list.
5208 if (--(track->mRetryCount) <= 0) {
5209 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
5210 track->name());
5211 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08005212 // indicate to client process that the track was disabled because of underrun;
5213 // it will then automatically call start() when data is available
5214 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005215 } else if (last){
5216 mixerStatus = MIXER_TRACKS_ENABLED;
5217 }
5218 }
5219 }
5220 // compute volume for this track
5221 processVolume_l(track, last);
5222 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005223
Eric Laurentea0fade2013-10-04 16:23:48 -07005224 // make sure the pause/flush/resume sequence is executed in the right order.
5225 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5226 // before flush and then resume HW. This can happen in case of pause/flush/resume
5227 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07005228 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurent972a1732013-09-04 09:42:59 -07005229 mOutput->stream->pause(mOutput->stream);
5230 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005231 if (mFlushPending) {
5232 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005233 }
Eric Laurentfd477972013-10-25 18:10:40 -07005234 if (!mStandby && doHwResume) {
Eric Laurent972a1732013-09-04 09:42:59 -07005235 mOutput->stream->resume(mOutput->stream);
5236 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005237
Eric Laurentbfb1b832013-01-07 09:53:42 -08005238 // remove all the tracks that need to be...
5239 removeTracks_l(*tracksToRemove);
5240
5241 return mixerStatus;
5242}
5243
Eric Laurentbfb1b832013-01-07 09:53:42 -08005244// must be called with thread mutex locked
5245bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
5246{
Eric Laurent3b4529e2013-09-05 18:09:19 -07005247 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
5248 mWriteAckSequence, mDrainSequence);
5249 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005250 return true;
5251 }
5252 return false;
5253}
5254
Eric Laurentbfb1b832013-01-07 09:53:42 -08005255bool AudioFlinger::OffloadThread::waitingAsyncCallback()
5256{
5257 Mutex::Autolock _l(mLock);
5258 return waitingAsyncCallback_l();
5259}
5260
5261void AudioFlinger::OffloadThread::flushHw_l()
5262{
Eric Laurente659ef42014-09-29 13:06:46 -07005263 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005264 // Flush anything still waiting in the mixbuffer
5265 mCurrentWriteLength = 0;
5266 mBytesRemaining = 0;
5267 mPausedWriteLength = 0;
5268 mPausedBytesRemaining = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08005269
Eric Laurentbfb1b832013-01-07 09:53:42 -08005270 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005271 // discard any pending drain or write ack by incrementing sequence
5272 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5273 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005274 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005275 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5276 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005277 }
5278}
5279
5280// ----------------------------------------------------------------------------
5281
Eric Laurent81784c32012-11-19 14:55:58 -08005282AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07005283 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08005284 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
Eric Laurent72e3f392015-05-20 14:43:50 -07005285 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08005286 mWaitTimeMs(UINT_MAX)
5287{
5288 addOutputTrack(mainThread);
5289}
5290
5291AudioFlinger::DuplicatingThread::~DuplicatingThread()
5292{
5293 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5294 mOutputTracks[i]->destroy();
5295 }
5296}
5297
5298void AudioFlinger::DuplicatingThread::threadLoop_mix()
5299{
5300 // mix buffers...
5301 if (outputsReady(outputTracks)) {
5302 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
5303 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08005304 if (mMixerBufferValid) {
5305 memset(mMixerBuffer, 0, mMixerBufferSize);
5306 } else {
5307 memset(mSinkBuffer, 0, mSinkBufferSize);
5308 }
Eric Laurent81784c32012-11-19 14:55:58 -08005309 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005310 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005311 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005312 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005313 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005314}
5315
5316void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
5317{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005318 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005319 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005320 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005321 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005322 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005323 }
5324 } else if (mBytesWritten != 0) {
5325 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5326 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005327 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005328 } else {
5329 // flush remaining overflow buffers in output tracks
5330 writeFrames = 0;
5331 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005332 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005333 }
5334}
5335
Eric Laurentbfb1b832013-01-07 09:53:42 -08005336ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005337{
5338 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08005339 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005340 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07005341 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08005342 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005343}
5344
5345void AudioFlinger::DuplicatingThread::threadLoop_standby()
5346{
5347 // DuplicatingThread implements standby by stopping all tracks
5348 for (size_t i = 0; i < outputTracks.size(); i++) {
5349 outputTracks[i]->stop();
5350 }
5351}
5352
5353void AudioFlinger::DuplicatingThread::saveOutputTracks()
5354{
5355 outputTracks = mOutputTracks;
5356}
5357
5358void AudioFlinger::DuplicatingThread::clearOutputTracks()
5359{
5360 outputTracks.clear();
5361}
5362
5363void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
5364{
5365 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08005366 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
5367 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
5368 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
5369 const size_t frameCount =
5370 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
5371 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
5372 // from different OutputTracks and their associated MixerThreads (e.g. one may
5373 // nearly empty and the other may be dropping data).
5374
5375 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08005376 this,
5377 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08005378 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08005379 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005380 frameCount,
5381 IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08005382 if (outputTrack->cblk() != NULL) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005383 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
Eric Laurent81784c32012-11-19 14:55:58 -08005384 mOutputTracks.add(outputTrack);
Andy Hungc25b84a2015-01-14 19:04:10 -08005385 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005386 updateWaitTime_l();
5387 }
5388}
5389
5390void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
5391{
5392 Mutex::Autolock _l(mLock);
5393 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5394 if (mOutputTracks[i]->thread() == thread) {
5395 mOutputTracks[i]->destroy();
5396 mOutputTracks.removeAt(i);
5397 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07005398 if (thread->getOutput() == mOutput) {
5399 mOutput = NULL;
5400 }
Eric Laurent81784c32012-11-19 14:55:58 -08005401 return;
5402 }
5403 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07005404 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005405}
5406
5407// caller must hold mLock
5408void AudioFlinger::DuplicatingThread::updateWaitTime_l()
5409{
5410 mWaitTimeMs = UINT_MAX;
5411 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5412 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
5413 if (strong != 0) {
5414 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
5415 if (waitTimeMs < mWaitTimeMs) {
5416 mWaitTimeMs = waitTimeMs;
5417 }
5418 }
5419 }
5420}
5421
5422
5423bool AudioFlinger::DuplicatingThread::outputsReady(
5424 const SortedVector< sp<OutputTrack> > &outputTracks)
5425{
5426 for (size_t i = 0; i < outputTracks.size(); i++) {
5427 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
5428 if (thread == 0) {
5429 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
5430 outputTracks[i].get());
5431 return false;
5432 }
5433 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5434 // see note at standby() declaration
5435 if (playbackThread->standby() && !playbackThread->isSuspended()) {
5436 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
5437 thread.get());
5438 return false;
5439 }
5440 }
5441 return true;
5442}
5443
5444uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
5445{
5446 return (mWaitTimeMs * 1000) / 2;
5447}
5448
5449void AudioFlinger::DuplicatingThread::cacheParameters_l()
5450{
5451 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
5452 updateWaitTime_l();
5453
5454 MixerThread::cacheParameters_l();
5455}
5456
5457// ----------------------------------------------------------------------------
5458// Record
5459// ----------------------------------------------------------------------------
5460
5461AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5462 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08005463 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08005464 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07005465 audio_devices_t inDevice,
5466 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08005467#ifdef TEE_SINK
5468 , const sp<NBAIO_Sink>& teeSink
5469#endif
5470 ) :
Eric Laurent72e3f392015-05-20 14:43:50 -07005471 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005472 mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005473 // mRsmpInFrames and mRsmpInFramesP2 are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005474 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08005475#ifdef TEE_SINK
5476 , mTeeSink(teeSink)
5477#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07005478 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
5479 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005480 // mFastCapture below
5481 , mFastCaptureFutex(0)
5482 // mInputSource
5483 // mPipeSink
5484 // mPipeSource
5485 , mPipeFramesP2(0)
5486 // mPipeMemory
5487 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005488 , mFastTrackAvail(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005489{
Glenn Kastend7dca052015-03-05 16:05:54 -08005490 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
5491 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08005492
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005493 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005494
5495 // create an NBAIO source for the HAL input stream, and negotiate
5496 mInputSource = new AudioStreamInSource(input->stream);
5497 size_t numCounterOffers = 0;
5498 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
5499 ssize_t index = mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
5500 ALOG_ASSERT(index == 0);
5501
5502 // initialize fast capture depending on configuration
5503 bool initFastCapture;
5504 switch (kUseFastCapture) {
5505 case FastCapture_Never:
5506 initFastCapture = false;
5507 break;
5508 case FastCapture_Always:
5509 initFastCapture = true;
5510 break;
5511 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07005512 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005513 break;
5514 // case FastCapture_Dynamic:
5515 }
5516
5517 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07005518 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005519 NBAIO_Format format = mInputSource->format();
Glenn Kasten49d00ad2014-07-21 11:22:03 -07005520 size_t pipeFramesP2 = roundup(mSampleRate / 25); // double-buffering of 20 ms each
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005521 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
5522 void *pipeBuffer;
5523 const sp<MemoryDealer> roHeap(readOnlyHeap());
5524 sp<IMemory> pipeMemory;
5525 if ((roHeap == 0) ||
5526 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
5527 (pipeBuffer = pipeMemory->pointer()) == NULL) {
5528 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
5529 goto failed;
5530 }
5531 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
5532 memset(pipeBuffer, 0, pipeSize);
5533 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
5534 const NBAIO_Format offers[1] = {format};
5535 size_t numCounterOffers = 0;
5536 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
5537 ALOG_ASSERT(index == 0);
5538 mPipeSink = pipe;
5539 PipeReader *pipeReader = new PipeReader(*pipe);
5540 numCounterOffers = 0;
5541 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
5542 ALOG_ASSERT(index == 0);
5543 mPipeSource = pipeReader;
5544 mPipeFramesP2 = pipeFramesP2;
5545 mPipeMemory = pipeMemory;
5546
5547 // create fast capture
5548 mFastCapture = new FastCapture();
5549 FastCaptureStateQueue *sq = mFastCapture->sq();
5550#ifdef STATE_QUEUE_DUMP
5551 // FIXME
5552#endif
5553 FastCaptureState *state = sq->begin();
5554 state->mCblk = NULL;
5555 state->mInputSource = mInputSource.get();
5556 state->mInputSourceGen++;
5557 state->mPipeSink = pipe;
5558 state->mPipeSinkGen++;
5559 state->mFrameCount = mFrameCount;
5560 state->mCommand = FastCaptureState::COLD_IDLE;
5561 // already done in constructor initialization list
5562 //mFastCaptureFutex = 0;
5563 state->mColdFutexAddr = &mFastCaptureFutex;
5564 state->mColdGen++;
5565 state->mDumpState = &mFastCaptureDumpState;
5566#ifdef TEE_SINK
5567 // FIXME
5568#endif
5569 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
5570 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
5571 sq->end();
5572 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5573
5574 // start the fast capture
5575 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
5576 pid_t tid = mFastCapture->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07005577 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005578#ifdef AUDIO_WATCHDOG
5579 // FIXME
5580#endif
5581
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005582 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005583 }
5584failed: ;
5585
5586 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08005587}
5588
Eric Laurent81784c32012-11-19 14:55:58 -08005589AudioFlinger::RecordThread::~RecordThread()
5590{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005591 if (mFastCapture != 0) {
5592 FastCaptureStateQueue *sq = mFastCapture->sq();
5593 FastCaptureState *state = sq->begin();
5594 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5595 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5596 if (old == -1) {
5597 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5598 }
5599 }
5600 state->mCommand = FastCaptureState::EXIT;
5601 sq->end();
5602 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5603 mFastCapture->join();
5604 mFastCapture.clear();
5605 }
5606 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07005607 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07005608 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08005609}
5610
5611void AudioFlinger::RecordThread::onFirstRef()
5612{
Glenn Kastend7dca052015-03-05 16:05:54 -08005613 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08005614}
5615
Eric Laurent81784c32012-11-19 14:55:58 -08005616bool AudioFlinger::RecordThread::threadLoop()
5617{
Eric Laurent81784c32012-11-19 14:55:58 -08005618 nsecs_t lastWarning = 0;
5619
5620 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08005621
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005622reacquire_wakelock:
5623 sp<RecordTrack> activeTrack;
Glenn Kasten2b806402013-11-20 16:37:38 -08005624 int activeTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005625 {
5626 Mutex::Autolock _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005627 size_t size = mActiveTracks.size();
5628 activeTracksGen = mActiveTracksGen;
5629 if (size > 0) {
5630 // FIXME an arbitrary choice
5631 activeTrack = mActiveTracks[0];
5632 acquireWakeLock_l(activeTrack->uid());
5633 if (size > 1) {
5634 SortedVector<int> tmp;
5635 for (size_t i = 0; i < size; i++) {
5636 tmp.add(mActiveTracks[i]->uid());
5637 }
5638 updateWakeLockUids_l(tmp);
5639 }
5640 } else {
5641 acquireWakeLock_l(-1);
5642 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005643 }
5644
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005645 // used to request a deferred sleep, to be executed later while mutex is unlocked
5646 uint32_t sleepUs = 0;
5647
5648 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005649 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005650 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07005651
Glenn Kasten5edadd42013-08-14 16:30:49 -07005652 // sleep with mutex unlocked
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005653 if (sleepUs > 0) {
Glenn Kastene7754022014-10-31 12:11:26 -07005654 ATRACE_BEGIN("sleep");
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005655 usleep(sleepUs);
Glenn Kastene7754022014-10-31 12:11:26 -07005656 ATRACE_END();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005657 sleepUs = 0;
Glenn Kasten5edadd42013-08-14 16:30:49 -07005658 }
5659
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005660 // activeTracks accumulates a copy of a subset of mActiveTracks
5661 Vector< sp<RecordTrack> > activeTracks;
5662
Glenn Kasten735f45f2014-08-18 15:51:59 -07005663 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005664 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07005665
Glenn Kasten735f45f2014-08-18 15:51:59 -07005666 // reference to a fast track which is about to be removed
5667 sp<RecordTrack> fastTrackToRemove;
5668
Eric Laurent81784c32012-11-19 14:55:58 -08005669 { // scope for mLock
5670 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08005671
Eric Laurent021cf962014-05-13 10:18:14 -07005672 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005673
Eric Laurent000a4192014-01-29 15:17:32 -08005674 // check exitPending here because checkForNewParameters_l() and
5675 // checkForNewParameters_l() can temporarily release mLock
5676 if (exitPending()) {
5677 break;
5678 }
5679
Glenn Kasten2b806402013-11-20 16:37:38 -08005680 // if no active track(s), then standby and release wakelock
5681 size_t size = mActiveTracks.size();
5682 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07005683 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005684 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08005685 releaseWakeLock_l();
5686 ALOGV("RecordThread: loop stopping");
5687 // go to sleep
5688 mWaitWorkCV.wait(mLock);
5689 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005690 goto reacquire_wakelock;
5691 }
5692
Glenn Kasten2b806402013-11-20 16:37:38 -08005693 if (mActiveTracksGen != activeTracksGen) {
5694 activeTracksGen = mActiveTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005695 SortedVector<int> tmp;
Glenn Kasten2b806402013-11-20 16:37:38 -08005696 for (size_t i = 0; i < size; i++) {
5697 tmp.add(mActiveTracks[i]->uid());
5698 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005699 updateWakeLockUids_l(tmp);
Eric Laurent81784c32012-11-19 14:55:58 -08005700 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005701
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005702 bool doBroadcast = false;
5703 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07005704
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005705 activeTrack = mActiveTracks[i];
5706 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07005707 if (activeTrack->isFastTrack()) {
5708 ALOG_ASSERT(fastTrackToRemove == 0);
5709 fastTrackToRemove = activeTrack;
5710 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005711 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08005712 mActiveTracks.remove(activeTrack);
5713 mActiveTracksGen++;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005714 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07005715 continue;
5716 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005717
5718 TrackBase::track_state activeTrackState = activeTrack->mState;
5719 switch (activeTrackState) {
5720
5721 case TrackBase::PAUSING:
5722 mActiveTracks.remove(activeTrack);
5723 mActiveTracksGen++;
5724 doBroadcast = true;
5725 size--;
5726 continue;
5727
5728 case TrackBase::STARTING_1:
5729 sleepUs = 10000;
5730 i++;
5731 continue;
5732
5733 case TrackBase::STARTING_2:
5734 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005735 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07005736 activeTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005737 break;
5738
5739 case TrackBase::ACTIVE:
5740 break;
5741
5742 case TrackBase::IDLE:
5743 i++;
5744 continue;
5745
5746 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08005747 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07005748 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005749
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005750 activeTracks.add(activeTrack);
5751 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07005752
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005753 if (activeTrack->isFastTrack()) {
5754 ALOG_ASSERT(!mFastTrackAvail);
5755 ALOG_ASSERT(fastTrack == 0);
5756 fastTrack = activeTrack;
5757 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005758 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005759 if (doBroadcast) {
5760 mStartStopCond.broadcast();
5761 }
5762
5763 // sleep if there are no active tracks to process
5764 if (activeTracks.size() == 0) {
5765 if (sleepUs == 0) {
5766 sleepUs = kRecordThreadSleepUs;
5767 }
5768 continue;
5769 }
5770 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07005771
Eric Laurent81784c32012-11-19 14:55:58 -08005772 lockEffectChains_l(effectChains);
5773 }
5774
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005775 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07005776
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005777 size_t size = effectChains.size();
5778 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005779 // thread mutex is not locked, but effect chain is locked
5780 effectChains[i]->process_l();
5781 }
5782
Glenn Kasten735f45f2014-08-18 15:51:59 -07005783 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005784 if (mFastCapture != 0) {
5785 FastCaptureStateQueue *sq = mFastCapture->sq();
5786 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07005787 bool didModify = false;
5788 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005789 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
5790 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
5791 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5792 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5793 if (old == -1) {
5794 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5795 }
5796 }
5797 state->mCommand = FastCaptureState::READ_WRITE;
5798#if 0 // FIXME
5799 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08005800 FastThreadDumpState::kSamplingNforLowRamDevice :
5801 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005802#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07005803 didModify = true;
5804 }
5805 audio_track_cblk_t *cblkOld = state->mCblk;
5806 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
5807 if (cblkNew != cblkOld) {
5808 state->mCblk = cblkNew;
5809 // block until acked if removing a fast track
5810 if (cblkOld != NULL) {
5811 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
5812 }
5813 didModify = true;
5814 }
5815 sq->end(didModify);
5816 if (didModify) {
5817 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005818#if 0
5819 if (kUseFastCapture == FastCapture_Dynamic) {
5820 mNormalSource = mPipeSource;
5821 }
5822#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005823 }
5824 }
5825
Glenn Kasten735f45f2014-08-18 15:51:59 -07005826 // now run the fast track destructor with thread mutex unlocked
5827 fastTrackToRemove.clear();
5828
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005829 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
5830 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
5831 // slow, then this RecordThread will overrun by not calling HAL read often enough.
5832 // If destination is non-contiguous, first read past the nominal end of buffer, then
5833 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005834
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005835 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005836 ssize_t framesRead;
5837
5838 // If an NBAIO source is present, use it to read the normal capture's data
5839 if (mPipeSource != 0) {
5840 size_t framesToRead = mBufferSize / mFrameSize;
Andy Hung57446612015-04-19 23:56:46 -07005841 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005842 framesToRead, AudioBufferProvider::kInvalidPTS);
5843 if (framesRead == 0) {
5844 // since pipe is non-blocking, simulate blocking input
5845 sleepUs = (framesToRead * 1000000LL) / mSampleRate;
5846 }
5847 // otherwise use the HAL / AudioStreamIn directly
5848 } else {
5849 ssize_t bytesRead = mInput->stream->read(mInput->stream,
Andy Hung57446612015-04-19 23:56:46 -07005850 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005851 if (bytesRead < 0) {
5852 framesRead = bytesRead;
5853 } else {
5854 framesRead = bytesRead / mFrameSize;
5855 }
5856 }
5857
5858 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
5859 ALOGE("read failed: framesRead=%d", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005860 // Force input into standby so that it tries to recover at next read attempt
5861 inputStandBy();
5862 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005863 }
5864 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005865 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005866 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005867 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005868
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005869 if (mTeeSink != 0) {
Andy Hung57446612015-04-19 23:56:46 -07005870 (void) mTeeSink->write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005871 }
5872 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005873 {
5874 size_t part1 = mRsmpInFramesP2 - rear;
5875 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07005876 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005877 (framesRead - part1) * mFrameSize);
5878 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005879 }
5880 rear = mRsmpInRear += framesRead;
5881
5882 size = activeTracks.size();
5883 // loop over each active track
5884 for (size_t i = 0; i < size; i++) {
5885 activeTrack = activeTracks[i];
5886
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005887 // skip fast tracks, as those are handled directly by FastCapture
5888 if (activeTrack->isFastTrack()) {
5889 continue;
5890 }
5891
Andy Hung73c02e42015-03-29 01:13:58 -07005892 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07005893 // TODO: Update the activeTrack buffer converter in case of reconfigure.
5894
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005895 enum {
5896 OVERRUN_UNKNOWN,
5897 OVERRUN_TRUE,
5898 OVERRUN_FALSE
5899 } overrun = OVERRUN_UNKNOWN;
5900
5901 // loop over getNextBuffer to handle circular sink
5902 for (;;) {
5903
5904 activeTrack->mSink.frameCount = ~0;
5905 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
5906 size_t framesOut = activeTrack->mSink.frameCount;
5907 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
5908
Andy Hung73c02e42015-03-29 01:13:58 -07005909 // check available frames and handle overrun conditions
5910 // if the record track isn't draining fast enough.
5911 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005912 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07005913 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
5914 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005915 overrun = OVERRUN_TRUE;
5916 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005917 if (framesOut == 0 || framesIn == 0) {
5918 break;
5919 }
5920
Andy Hung6770c6f2015-04-07 13:43:36 -07005921 // Don't allow framesOut to be larger than what is possible with resampling
5922 // from framesIn.
5923 // This isn't strictly necessary but helps limit buffer resizing in
5924 // RecordBufferConverter. TODO: remove when no longer needed.
5925 framesOut = min(framesOut,
5926 destinationFramesPossible(
5927 framesIn, mSampleRate, activeTrack->mSampleRate));
Andy Hung97a893e2015-03-29 01:03:07 -07005928 // process frames from the RecordThread buffer provider to the RecordTrack buffer
5929 framesOut = activeTrack->mRecordBufferConverter->convert(
5930 activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005931
5932 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
5933 overrun = OVERRUN_FALSE;
5934 }
5935
5936 if (activeTrack->mFramesToDrop == 0) {
5937 if (framesOut > 0) {
5938 activeTrack->mSink.frameCount = framesOut;
5939 activeTrack->releaseBuffer(&activeTrack->mSink);
5940 }
5941 } else {
5942 // FIXME could do a partial drop of framesOut
5943 if (activeTrack->mFramesToDrop > 0) {
5944 activeTrack->mFramesToDrop -= framesOut;
5945 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005946 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005947 }
5948 } else {
5949 activeTrack->mFramesToDrop += framesOut;
5950 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
5951 activeTrack->mSyncStartEvent->isCancelled()) {
5952 ALOGW("Synced record %s, session %d, trigger session %d",
5953 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
5954 activeTrack->sessionId(),
5955 (activeTrack->mSyncStartEvent != 0) ?
5956 activeTrack->mSyncStartEvent->triggerSession() : 0);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005957 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005958 }
5959 }
5960 }
5961
5962 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005963 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005964 }
5965 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005966
5967 switch (overrun) {
5968 case OVERRUN_TRUE:
5969 // client isn't retrieving buffers fast enough
5970 if (!activeTrack->setOverflow()) {
5971 nsecs_t now = systemTime();
5972 // FIXME should lastWarning per track?
5973 if ((now - lastWarning) > kWarningThrottleNs) {
5974 ALOGW("RecordThread: buffer overflow");
5975 lastWarning = now;
5976 }
5977 }
5978 break;
5979 case OVERRUN_FALSE:
5980 activeTrack->clearOverflow();
5981 break;
5982 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005983 break;
5984 }
5985
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005986 }
5987
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005988unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08005989 // enable changes in effect chain
5990 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005991 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08005992 }
5993
Glenn Kasten93e471f2013-08-19 08:40:07 -07005994 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08005995
5996 {
5997 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07005998 for (size_t i = 0; i < mTracks.size(); i++) {
5999 sp<RecordTrack> track = mTracks[i];
6000 track->invalidate();
6001 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006002 mActiveTracks.clear();
6003 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08006004 mStartStopCond.broadcast();
6005 }
6006
6007 releaseWakeLock();
6008
6009 ALOGV("RecordThread %p exiting", this);
6010 return false;
6011}
6012
Glenn Kasten93e471f2013-08-19 08:40:07 -07006013void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08006014{
6015 if (!mStandby) {
6016 inputStandBy();
6017 mStandby = true;
6018 }
6019}
6020
6021void AudioFlinger::RecordThread::inputStandBy()
6022{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006023 // Idle the fast capture if it's currently running
6024 if (mFastCapture != 0) {
6025 FastCaptureStateQueue *sq = mFastCapture->sq();
6026 FastCaptureState *state = sq->begin();
6027 if (!(state->mCommand & FastCaptureState::IDLE)) {
6028 state->mCommand = FastCaptureState::COLD_IDLE;
6029 state->mColdFutexAddr = &mFastCaptureFutex;
6030 state->mColdGen++;
6031 mFastCaptureFutex = 0;
6032 sq->end();
6033 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
6034 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
6035#if 0
6036 if (kUseFastCapture == FastCapture_Dynamic) {
6037 // FIXME
6038 }
6039#endif
6040#ifdef AUDIO_WATCHDOG
6041 // FIXME
6042#endif
6043 } else {
6044 sq->end(false /*didModify*/);
6045 }
6046 }
Eric Laurent81784c32012-11-19 14:55:58 -08006047 mInput->stream->common.standby(&mInput->stream->common);
6048}
6049
Glenn Kasten05997e22014-03-13 15:08:33 -07006050// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07006051sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08006052 const sp<AudioFlinger::Client>& client,
6053 uint32_t sampleRate,
6054 audio_format_t format,
6055 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08006056 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08006057 int sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07006058 size_t *notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08006059 int uid,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07006060 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08006061 pid_t tid,
6062 status_t *status)
6063{
Glenn Kasten74935e42013-12-19 08:56:45 -08006064 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08006065 sp<RecordTrack> track;
6066 status_t lStatus;
6067
Glenn Kasten90e58b12013-07-31 16:16:02 -07006068 // client expresses a preference for FAST, but we get the final say
6069 if (*flags & IAudioFlinger::TRACK_FAST) {
6070 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07006071 // we formerly checked for a callback handler (non-0 tid),
6072 // but that is no longer required for TRANSFER_OBTAIN mode
6073 //
Glenn Kasten74105912014-07-03 12:28:53 -07006074 // frame count is not specified, or is exactly the pipe depth
6075 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006076 // PCM data
6077 audio_is_linear_pcm(format) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006078 // native format
6079 (format == mFormat) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006080 // native channel mask
6081 (channelMask == mChannelMask) &&
6082 // native hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07006083 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006084 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006085 hasFastCapture() &&
6086 // there are sufficient fast track slots available
6087 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07006088 ) {
Glenn Kasten74105912014-07-03 12:28:53 -07006089 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%u mFrameCount=%u",
Glenn Kasten90e58b12013-07-31 16:16:02 -07006090 frameCount, mFrameCount);
6091 } else {
Glenn Kasten74105912014-07-03 12:28:53 -07006092 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%u mFrameCount=%u mPipeFramesP2=%u "
6093 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006094 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Glenn Kasten74105912014-07-03 12:28:53 -07006095 frameCount, mFrameCount, mPipeFramesP2,
6096 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
6097 hasFastCapture(), tid, mFastTrackAvail);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006098 *flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kasten74105912014-07-03 12:28:53 -07006099 }
6100 }
6101
6102 // compute track buffer size in frames, and suggest the notification frame count
6103 if (*flags & IAudioFlinger::TRACK_FAST) {
6104 // fast track: frame count is exactly the pipe depth
6105 frameCount = mPipeFramesP2;
6106 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
6107 *notificationFrames = mFrameCount;
6108 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006109 // not fast track: max notification period is resampled equivalent of one HAL buffer time
6110 // or 20 ms if there is a fast capture
6111 // TODO This could be a roundupRatio inline, and const
6112 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
6113 * sampleRate + mSampleRate - 1) / mSampleRate;
6114 // minimum number of notification periods is at least kMinNotifications,
6115 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
6116 static const size_t kMinNotifications = 3;
6117 static const uint32_t kMinMs = 30;
6118 // TODO This could be a roundupRatio inline
6119 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
6120 // TODO This could be a roundupRatio inline
6121 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
6122 maxNotificationFrames;
6123 const size_t minFrameCount = maxNotificationFrames *
6124 max(kMinNotifications, minNotificationsByMs);
6125 frameCount = max(frameCount, minFrameCount);
6126 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
6127 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07006128 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07006129 }
Glenn Kasten74935e42013-12-19 08:56:45 -08006130 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07006131
Glenn Kasten15e57982013-09-24 11:52:37 -07006132 lStatus = initCheck();
6133 if (lStatus != NO_ERROR) {
6134 ALOGE("createRecordTrack_l() audio driver not initialized");
6135 goto Exit;
6136 }
Eric Laurent81784c32012-11-19 14:55:58 -08006137
6138 { // scope for mLock
6139 Mutex::Autolock _l(mLock);
6140
6141 track = new RecordTrack(this, client, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07006142 format, channelMask, frameCount, NULL, sessionId, uid,
6143 *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08006144
Glenn Kasten03003332013-08-06 15:40:54 -07006145 lStatus = track->initCheck();
6146 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07006147 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08006148 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08006149 goto Exit;
6150 }
6151 mTracks.add(track);
6152
6153 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6154 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6155 mAudioFlinger->btNrecIsOff();
6156 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6157 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006158
6159 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
6160 pid_t callingPid = IPCThreadState::self()->getCallingPid();
6161 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
6162 // so ask activity manager to do this on our behalf
6163 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
6164 }
Eric Laurent81784c32012-11-19 14:55:58 -08006165 }
Glenn Kasten05997e22014-03-13 15:08:33 -07006166
Eric Laurent81784c32012-11-19 14:55:58 -08006167 lStatus = NO_ERROR;
6168
6169Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07006170 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08006171 return track;
6172}
6173
6174status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
6175 AudioSystem::sync_event_t event,
6176 int triggerSession)
6177{
6178 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
6179 sp<ThreadBase> strongMe = this;
6180 status_t status = NO_ERROR;
6181
6182 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006183 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006184 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006185 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08006186 triggerSession,
6187 recordTrack->sessionId(),
6188 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006189 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08006190 // Sync event can be cancelled by the trigger session if the track is not in a
6191 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006192 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006193 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006194 } else {
6195 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006196 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006197 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08006198 }
6199 }
6200
6201 {
Glenn Kasten47c20702013-08-13 15:37:35 -07006202 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08006203 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006204 if (mActiveTracks.indexOf(recordTrack) >= 0) {
6205 if (recordTrack->mState == TrackBase::PAUSING) {
6206 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006207 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006208 } else {
6209 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08006210 }
6211 return status;
6212 }
6213
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006214 // TODO consider other ways of handling this, such as changing the state to :STARTING and
6215 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
6216 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006217 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08006218 mActiveTracks.add(recordTrack);
6219 mActiveTracksGen++;
Eric Laurent83b88082014-06-20 18:31:16 -07006220 status_t status = NO_ERROR;
6221 if (recordTrack->isExternalTrack()) {
6222 mLock.unlock();
Eric Laurent4dc68062014-07-28 17:26:49 -07006223 status = AudioSystem::startInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006224 mLock.lock();
6225 // FIXME should verify that recordTrack is still in mActiveTracks
6226 if (status != NO_ERROR) {
6227 mActiveTracks.remove(recordTrack);
6228 mActiveTracksGen++;
6229 recordTrack->clearSyncStartEvent();
6230 ALOGV("RecordThread::start error %d", status);
6231 return status;
6232 }
Eric Laurent81784c32012-11-19 14:55:58 -08006233 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006234 // Catch up with current buffer indices if thread is already running.
6235 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
6236 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
6237 // see previously buffered data before it called start(), but with greater risk of overrun.
6238
Andy Hung73c02e42015-03-29 01:13:58 -07006239 recordTrack->mResamplerBufferProvider->reset();
Andy Hung97a893e2015-03-29 01:03:07 -07006240 // clear any converter state as new data will be discontinuous
6241 recordTrack->mRecordBufferConverter->reset();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006242 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08006243 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08006244 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08006245 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006246 ALOGV("Record failed to start");
6247 status = BAD_VALUE;
6248 goto startError;
6249 }
Eric Laurent81784c32012-11-19 14:55:58 -08006250 return status;
6251 }
Glenn Kasten7c027242012-12-26 14:43:16 -08006252
Eric Laurent81784c32012-11-19 14:55:58 -08006253startError:
Eric Laurent83b88082014-06-20 18:31:16 -07006254 if (recordTrack->isExternalTrack()) {
Eric Laurent4dc68062014-07-28 17:26:49 -07006255 AudioSystem::stopInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006256 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006257 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006258 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08006259 return status;
6260}
6261
Eric Laurent81784c32012-11-19 14:55:58 -08006262void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6263{
6264 sp<SyncEvent> strongEvent = event.promote();
6265
6266 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08006267 sp<RefBase> ptr = strongEvent->cookie().promote();
6268 if (ptr != 0) {
6269 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
6270 recordTrack->handleSyncStartEvent(strongEvent);
6271 }
Eric Laurent81784c32012-11-19 14:55:58 -08006272 }
6273}
6274
Glenn Kastena8356f62013-07-25 14:37:52 -07006275bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08006276 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07006277 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006278 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08006279 return false;
6280 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006281 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08006282 recordTrack->mState = TrackBase::PAUSING;
6283 // do not wait for mStartStopCond if exiting
6284 if (exitPending()) {
6285 return true;
6286 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006287 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08006288 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006289 // if we have been restarted, recordTrack is in mActiveTracks here
6290 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006291 ALOGV("Record stopped OK");
6292 return true;
6293 }
6294 return false;
6295}
6296
Glenn Kasten0f11b512014-01-31 16:18:54 -08006297bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08006298{
6299 return false;
6300}
6301
Glenn Kasten0f11b512014-01-31 16:18:54 -08006302status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006303{
6304#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
6305 if (!isValidSyncEvent(event)) {
6306 return BAD_VALUE;
6307 }
6308
6309 int eventSession = event->triggerSession();
6310 status_t ret = NAME_NOT_FOUND;
6311
6312 Mutex::Autolock _l(mLock);
6313
6314 for (size_t i = 0; i < mTracks.size(); i++) {
6315 sp<RecordTrack> track = mTracks[i];
6316 if (eventSession == track->sessionId()) {
6317 (void) track->setSyncEvent(event);
6318 ret = NO_ERROR;
6319 }
6320 }
6321 return ret;
6322#else
6323 return BAD_VALUE;
6324#endif
6325}
6326
6327// destroyTrack_l() must be called with ThreadBase::mLock held
6328void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6329{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006330 track->terminate();
6331 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08006332 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08006333 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006334 removeTrack_l(track);
6335 }
6336}
6337
6338void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6339{
6340 mTracks.remove(track);
6341 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006342 if (track->isFastTrack()) {
6343 ALOG_ASSERT(!mFastTrackAvail);
6344 mFastTrackAvail = true;
6345 }
Eric Laurent81784c32012-11-19 14:55:58 -08006346}
6347
6348void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6349{
6350 dumpInternals(fd, args);
6351 dumpTracks(fd, args);
6352 dumpEffectChains(fd, args);
6353}
6354
6355void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6356{
Elliott Hughes87cebad2014-05-22 10:14:43 -07006357 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08006358
Glenn Kasten44182c22015-03-05 17:12:23 -08006359 dumpBase(fd, args);
6360
6361 if (mActiveTracks.size() == 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006362 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006363 }
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006364 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006365 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08006366
6367 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
6368 const FastCaptureDumpState copy(mFastCaptureDumpState);
6369 copy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006370}
6371
Glenn Kasten0f11b512014-01-31 16:18:54 -08006372void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006373{
6374 const size_t SIZE = 256;
6375 char buffer[SIZE];
6376 String8 result;
6377
Marco Nelissenb2208842014-02-07 14:00:50 -08006378 size_t numtracks = mTracks.size();
6379 size_t numactive = mActiveTracks.size();
6380 size_t numactiveseen = 0;
Elliott Hughes87cebad2014-05-22 10:14:43 -07006381 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08006382 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006383 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08006384 RecordTrack::appendDumpHeader(result);
6385 for (size_t i = 0; i < numtracks ; ++i) {
6386 sp<RecordTrack> track = mTracks[i];
6387 if (track != 0) {
6388 bool active = mActiveTracks.indexOf(track) >= 0;
6389 if (active) {
6390 numactiveseen++;
6391 }
6392 track->dump(buffer, SIZE, active);
6393 result.append(buffer);
6394 }
Eric Laurent81784c32012-11-19 14:55:58 -08006395 }
Marco Nelissenb2208842014-02-07 14:00:50 -08006396 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006397 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006398 }
6399
Marco Nelissenb2208842014-02-07 14:00:50 -08006400 if (numactiveseen != numactive) {
6401 snprintf(buffer, SIZE, " The following tracks are in the active list but"
6402 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006403 result.append(buffer);
6404 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08006405 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08006406 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08006407 if (mTracks.indexOf(track) < 0) {
6408 track->dump(buffer, SIZE, true);
6409 result.append(buffer);
6410 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006411 }
Eric Laurent81784c32012-11-19 14:55:58 -08006412
6413 }
6414 write(fd, result.string(), result.size());
6415}
6416
Andy Hung73c02e42015-03-29 01:13:58 -07006417
6418void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
6419{
6420 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6421 RecordThread *recordThread = (RecordThread *) threadBase.get();
6422 mRsmpInFront = recordThread->mRsmpInRear;
6423 mRsmpInUnrel = 0;
6424}
6425
6426void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
6427 size_t *framesAvailable, bool *hasOverrun)
6428{
6429 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6430 RecordThread *recordThread = (RecordThread *) threadBase.get();
6431 const int32_t rear = recordThread->mRsmpInRear;
6432 const int32_t front = mRsmpInFront;
6433 const ssize_t filled = rear - front;
6434
6435 size_t framesIn;
6436 bool overrun = false;
6437 if (filled < 0) {
6438 // should not happen, but treat like a massive overrun and re-sync
6439 framesIn = 0;
6440 mRsmpInFront = rear;
6441 overrun = true;
6442 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
6443 framesIn = (size_t) filled;
6444 } else {
6445 // client is not keeping up with server, but give it latest data
6446 framesIn = recordThread->mRsmpInFrames;
6447 mRsmpInFront = /* front = */ rear - framesIn;
6448 overrun = true;
6449 }
6450 if (framesAvailable != NULL) {
6451 *framesAvailable = framesIn;
6452 }
6453 if (hasOverrun != NULL) {
6454 *hasOverrun = overrun;
6455 }
6456}
6457
Eric Laurent81784c32012-11-19 14:55:58 -08006458// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006459status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
6460 AudioBufferProvider::Buffer* buffer, int64_t pts __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006461{
Andy Hung73c02e42015-03-29 01:13:58 -07006462 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006463 if (threadBase == 0) {
6464 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006465 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006466 return NOT_ENOUGH_DATA;
6467 }
6468 RecordThread *recordThread = (RecordThread *) threadBase.get();
6469 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07006470 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07006471 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006472 // FIXME should not be P2 (don't want to increase latency)
6473 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006474 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07006475 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006476 front &= recordThread->mRsmpInFramesP2 - 1;
6477 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07006478 if (part1 > (size_t) filled) {
6479 part1 = filled;
6480 }
6481 size_t ask = buffer->frameCount;
6482 ALOG_ASSERT(ask > 0);
6483 if (part1 > ask) {
6484 part1 = ask;
6485 }
6486 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07006487 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07006488 buffer->raw = NULL;
6489 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07006490 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07006491 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08006492 }
6493
Andy Hung57446612015-04-19 23:56:46 -07006494 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07006495 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07006496 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08006497 return NO_ERROR;
6498}
6499
6500// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006501void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
6502 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006503{
Glenn Kasten85948432013-08-19 12:09:05 -07006504 size_t stepCount = buffer->frameCount;
6505 if (stepCount == 0) {
6506 return;
6507 }
Andy Hung73c02e42015-03-29 01:13:58 -07006508 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
6509 mRsmpInUnrel -= stepCount;
6510 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07006511 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006512 buffer->frameCount = 0;
6513}
6514
Andy Hung97a893e2015-03-29 01:03:07 -07006515AudioFlinger::RecordThread::RecordBufferConverter::RecordBufferConverter(
6516 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6517 uint32_t srcSampleRate,
6518 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6519 uint32_t dstSampleRate) :
6520 mSrcChannelMask(AUDIO_CHANNEL_INVALID), // updateParameters will set following vars
6521 // mSrcFormat
6522 // mSrcSampleRate
6523 // mDstChannelMask
6524 // mDstFormat
6525 // mDstSampleRate
6526 // mSrcChannelCount
6527 // mDstChannelCount
6528 // mDstFrameSize
6529 mBuf(NULL), mBufFrames(0), mBufFrameSize(0),
Andy Hungd330ee42015-04-20 13:23:41 -07006530 mResampler(NULL),
6531 mIsLegacyDownmix(false),
6532 mIsLegacyUpmix(false),
6533 mRequiresFloat(false),
6534 mInputConverterProvider(NULL)
Andy Hung97a893e2015-03-29 01:03:07 -07006535{
6536 (void)updateParameters(srcChannelMask, srcFormat, srcSampleRate,
6537 dstChannelMask, dstFormat, dstSampleRate);
6538}
6539
6540AudioFlinger::RecordThread::RecordBufferConverter::~RecordBufferConverter() {
6541 free(mBuf);
6542 delete mResampler;
Andy Hungd330ee42015-04-20 13:23:41 -07006543 delete mInputConverterProvider;
Andy Hung97a893e2015-03-29 01:03:07 -07006544}
6545
6546size_t AudioFlinger::RecordThread::RecordBufferConverter::convert(void *dst,
6547 AudioBufferProvider *provider, size_t frames)
6548{
Andy Hungd330ee42015-04-20 13:23:41 -07006549 if (mInputConverterProvider != NULL) {
6550 mInputConverterProvider->setBufferProvider(provider);
6551 provider = mInputConverterProvider;
6552 }
6553
6554 if (mResampler == NULL) {
Andy Hung97a893e2015-03-29 01:03:07 -07006555 ALOGVV("NO RESAMPLING sampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6556 mSrcSampleRate, mSrcFormat, mDstFormat);
6557
6558 AudioBufferProvider::Buffer buffer;
6559 for (size_t i = frames; i > 0; ) {
6560 buffer.frameCount = i;
6561 status_t status = provider->getNextBuffer(&buffer, 0);
6562 if (status != OK || buffer.frameCount == 0) {
6563 frames -= i; // cannot fill request.
6564 break;
6565 }
Andy Hungd330ee42015-04-20 13:23:41 -07006566 // format convert to destination buffer
6567 convertNoResampler(dst, buffer.raw, buffer.frameCount);
Andy Hung97a893e2015-03-29 01:03:07 -07006568
6569 dst = (int8_t*)dst + buffer.frameCount * mDstFrameSize;
6570 i -= buffer.frameCount;
6571 provider->releaseBuffer(&buffer);
6572 }
6573 } else {
6574 ALOGVV("RESAMPLING mSrcSampleRate:%u mDstSampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6575 mSrcSampleRate, mDstSampleRate, mSrcFormat, mDstFormat);
6576
Andy Hungd330ee42015-04-20 13:23:41 -07006577 // reallocate buffer if needed
6578 if (mBufFrameSize != 0 && mBufFrames < frames) {
6579 free(mBuf);
6580 mBufFrames = frames;
6581 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
6582 }
Andy Hung97a893e2015-03-29 01:03:07 -07006583 // resampler accumulates, but we only have one source track
Andy Hungd330ee42015-04-20 13:23:41 -07006584 memset(mBuf, 0, frames * mBufFrameSize);
6585 frames = mResampler->resample((int32_t*)mBuf, frames, provider);
6586 // format convert to destination buffer
6587 convertResampler(dst, mBuf, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006588 }
6589 return frames;
6590}
6591
6592status_t AudioFlinger::RecordThread::RecordBufferConverter::updateParameters(
6593 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6594 uint32_t srcSampleRate,
6595 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6596 uint32_t dstSampleRate)
6597{
6598 // quick evaluation if there is any change.
6599 if (mSrcFormat == srcFormat
6600 && mSrcChannelMask == srcChannelMask
6601 && mSrcSampleRate == srcSampleRate
6602 && mDstFormat == dstFormat
6603 && mDstChannelMask == dstChannelMask
6604 && mDstSampleRate == dstSampleRate) {
6605 return NO_ERROR;
6606 }
6607
Andy Hungdb4c0312015-05-06 08:46:52 -07006608 ALOGV("RecordBufferConverter updateParameters srcMask:%#x dstMask:%#x"
6609 " srcFormat:%#x dstFormat:%#x srcRate:%u dstRate:%u",
6610 srcChannelMask, dstChannelMask, srcFormat, dstFormat, srcSampleRate, dstSampleRate);
Andy Hung97a893e2015-03-29 01:03:07 -07006611 const bool valid =
6612 audio_is_input_channel(srcChannelMask)
6613 && audio_is_input_channel(dstChannelMask)
6614 && audio_is_valid_format(srcFormat) && audio_is_linear_pcm(srcFormat)
6615 && audio_is_valid_format(dstFormat) && audio_is_linear_pcm(dstFormat)
6616 && (srcSampleRate <= dstSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX)
6617 ; // no upsampling checks for now
6618 if (!valid) {
6619 return BAD_VALUE;
6620 }
6621
6622 mSrcFormat = srcFormat;
6623 mSrcChannelMask = srcChannelMask;
6624 mSrcSampleRate = srcSampleRate;
6625 mDstFormat = dstFormat;
6626 mDstChannelMask = dstChannelMask;
6627 mDstSampleRate = dstSampleRate;
6628
6629 // compute derived parameters
6630 mSrcChannelCount = audio_channel_count_from_in_mask(srcChannelMask);
6631 mDstChannelCount = audio_channel_count_from_in_mask(dstChannelMask);
6632 mDstFrameSize = mDstChannelCount * audio_bytes_per_sample(mDstFormat);
6633
Andy Hungd330ee42015-04-20 13:23:41 -07006634 // do we need to resample?
6635 delete mResampler;
6636 mResampler = NULL;
6637 if (mSrcSampleRate != mDstSampleRate) {
6638 mResampler = AudioResampler::create(AUDIO_FORMAT_PCM_FLOAT,
6639 mSrcChannelCount, mDstSampleRate);
6640 mResampler->setSampleRate(mSrcSampleRate);
6641 mResampler->setVolume(AudioMixer::UNITY_GAIN_FLOAT, AudioMixer::UNITY_GAIN_FLOAT);
6642 }
6643
6644 // are we running legacy channel conversion modes?
6645 mIsLegacyDownmix = (mSrcChannelMask == AUDIO_CHANNEL_IN_STEREO
6646 || mSrcChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK)
6647 && mDstChannelMask == AUDIO_CHANNEL_IN_MONO;
6648 mIsLegacyUpmix = mSrcChannelMask == AUDIO_CHANNEL_IN_MONO
6649 && (mDstChannelMask == AUDIO_CHANNEL_IN_STEREO
6650 || mDstChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK);
6651
6652 // do we need to process in float?
6653 mRequiresFloat = mResampler != NULL || mIsLegacyDownmix || mIsLegacyUpmix;
6654
6655 // do we need a staging buffer to convert for destination (we can still optimize this)?
6656 // we use mBufFrameSize > 0 to indicate both frame size as well as buffer necessity
6657 if (mResampler != NULL) {
6658 mBufFrameSize = max(mSrcChannelCount, FCC_2)
6659 * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
Andy Hunga97630b2015-07-22 23:27:24 -07006660 } else if (mIsLegacyUpmix || mIsLegacyDownmix) { // legacy modes always float
Andy Hungd330ee42015-04-20 13:23:41 -07006661 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
6662 } else if (mSrcChannelMask != mDstChannelMask && mDstFormat != mSrcFormat) {
Andy Hung97a893e2015-03-29 01:03:07 -07006663 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(mSrcFormat);
6664 } else {
6665 mBufFrameSize = 0;
6666 }
6667 mBufFrames = 0; // force the buffer to be resized.
6668
Andy Hungd330ee42015-04-20 13:23:41 -07006669 // do we need an input converter buffer provider to give us float?
6670 delete mInputConverterProvider;
6671 mInputConverterProvider = NULL;
6672 if (mRequiresFloat && mSrcFormat != AUDIO_FORMAT_PCM_FLOAT) {
6673 mInputConverterProvider = new ReformatBufferProvider(
6674 audio_channel_count_from_in_mask(mSrcChannelMask),
6675 mSrcFormat,
6676 AUDIO_FORMAT_PCM_FLOAT,
6677 256 /* provider buffer frame count */);
6678 }
6679
6680 // do we need a remixer to do channel mask conversion
6681 if (!mIsLegacyDownmix && !mIsLegacyUpmix && mSrcChannelMask != mDstChannelMask) {
6682 (void) memcpy_by_index_array_initialization_from_channel_mask(
6683 mIdxAry, ARRAY_SIZE(mIdxAry), mDstChannelMask, mSrcChannelMask);
Andy Hung97a893e2015-03-29 01:03:07 -07006684 }
6685 return NO_ERROR;
6686}
6687
Andy Hungd330ee42015-04-20 13:23:41 -07006688void AudioFlinger::RecordThread::RecordBufferConverter::convertNoResampler(
6689 void *dst, const void *src, size_t frames)
Andy Hung97a893e2015-03-29 01:03:07 -07006690{
Andy Hungd330ee42015-04-20 13:23:41 -07006691 // src is native type unless there is legacy upmix or downmix, whereupon it is float.
Andy Hung97a893e2015-03-29 01:03:07 -07006692 if (mBufFrameSize != 0 && mBufFrames < frames) {
6693 free(mBuf);
6694 mBufFrames = frames;
6695 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
6696 }
Andy Hungd330ee42015-04-20 13:23:41 -07006697 // do we need to do legacy upmix and downmix?
6698 if (mIsLegacyUpmix || mIsLegacyDownmix) {
Andy Hung97a893e2015-03-29 01:03:07 -07006699 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07006700 if (mIsLegacyUpmix) {
6701 upmix_to_stereo_float_from_mono_float((float *)dstBuf,
6702 (const float *)src, frames);
6703 } else /*mIsLegacyDownmix */ {
6704 downmix_to_mono_float_from_stereo_float((float *)dstBuf,
6705 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006706 }
Andy Hungd330ee42015-04-20 13:23:41 -07006707 if (mBuf != NULL) {
6708 memcpy_by_audio_format(dst, mDstFormat, mBuf, AUDIO_FORMAT_PCM_FLOAT,
6709 frames * mDstChannelCount);
6710 }
6711 return;
6712 }
6713 // do we need to do channel mask conversion?
6714 if (mSrcChannelMask != mDstChannelMask) {
Andy Hung97a893e2015-03-29 01:03:07 -07006715 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07006716 memcpy_by_index_array(dstBuf, mDstChannelCount,
6717 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mSrcFormat), frames);
6718 if (dstBuf == dst) {
6719 return; // format is the same
6720 }
6721 }
6722 // convert to destination buffer
6723 const void *convertBuf = mBuf != NULL ? mBuf : src;
6724 memcpy_by_audio_format(dst, mDstFormat, convertBuf, mSrcFormat,
6725 frames * mDstChannelCount);
6726}
6727
6728void AudioFlinger::RecordThread::RecordBufferConverter::convertResampler(
6729 void *dst, /*not-a-const*/ void *src, size_t frames)
6730{
6731 // src buffer format is ALWAYS float when entering this routine
6732 if (mIsLegacyUpmix) {
6733 ; // mono to stereo already handled by resampler
6734 } else if (mIsLegacyDownmix
6735 || (mSrcChannelMask == mDstChannelMask && mSrcChannelCount == 1)) {
6736 // the resampler outputs stereo for mono input channel (a feature?)
6737 // must convert to mono
6738 downmix_to_mono_float_from_stereo_float((float *)src,
6739 (const float *)src, frames);
6740 } else if (mSrcChannelMask != mDstChannelMask) {
6741 // convert to mono channel again for channel mask conversion (could be skipped
6742 // with further optimization).
Andy Hung97a893e2015-03-29 01:03:07 -07006743 if (mSrcChannelCount == 1) {
Andy Hungd330ee42015-04-20 13:23:41 -07006744 downmix_to_mono_float_from_stereo_float((float *)src,
6745 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006746 }
Andy Hungd330ee42015-04-20 13:23:41 -07006747 // convert to destination format (in place, OK as float is larger than other types)
6748 if (mDstFormat != AUDIO_FORMAT_PCM_FLOAT) {
6749 memcpy_by_audio_format(src, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
6750 frames * mSrcChannelCount);
6751 }
6752 // channel convert and save to dst
6753 memcpy_by_index_array(dst, mDstChannelCount,
6754 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mDstFormat), frames);
6755 return;
Andy Hung97a893e2015-03-29 01:03:07 -07006756 }
Andy Hungd330ee42015-04-20 13:23:41 -07006757 // convert to destination format and save to dst
6758 memcpy_by_audio_format(dst, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
6759 frames * mDstChannelCount);
Andy Hung97a893e2015-03-29 01:03:07 -07006760}
6761
Eric Laurent10351942014-05-08 18:49:52 -07006762bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
6763 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006764{
6765 bool reconfig = false;
6766
Eric Laurent10351942014-05-08 18:49:52 -07006767 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006768
Eric Laurent10351942014-05-08 18:49:52 -07006769 audio_format_t reqFormat = mFormat;
6770 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07006771 // 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 -07006772 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
6773
6774 AudioParameter param = AudioParameter(keyValuePair);
6775 int value;
6776 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
6777 // channel count change can be requested. Do we mandate the first client defines the
6778 // HAL sampling rate and channel count or do we allow changes on the fly?
6779 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6780 samplingRate = value;
6781 reconfig = true;
6782 }
6783 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07006784 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07006785 status = BAD_VALUE;
6786 } else {
6787 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08006788 reconfig = true;
6789 }
Eric Laurent10351942014-05-08 18:49:52 -07006790 }
6791 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
6792 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07006793 if (!audio_is_input_channel(mask) ||
6794 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07006795 status = BAD_VALUE;
6796 } else {
6797 channelMask = mask;
6798 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006799 }
Eric Laurent10351942014-05-08 18:49:52 -07006800 }
6801 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6802 // do not accept frame count changes if tracks are open as the track buffer
6803 // size depends on frame count and correct behavior would not be guaranteed
6804 // if frame count is changed after track creation
6805 if (mActiveTracks.size() > 0) {
6806 status = INVALID_OPERATION;
6807 } else {
6808 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006809 }
Eric Laurent10351942014-05-08 18:49:52 -07006810 }
6811 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6812 // forward device change to effects that have requested to be
6813 // aware of attached audio device.
6814 for (size_t i = 0; i < mEffectChains.size(); i++) {
6815 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08006816 }
Eric Laurent81784c32012-11-19 14:55:58 -08006817
Eric Laurent10351942014-05-08 18:49:52 -07006818 // store input device and output device but do not forward output device to audio HAL.
6819 // Note that status is ignored by the caller for output device
6820 // (see AudioFlinger::setParameters()
6821 if (audio_is_output_devices(value)) {
6822 mOutDevice = value;
6823 status = BAD_VALUE;
6824 } else {
6825 mInDevice = value;
Eric Laurente8726fe2015-06-26 09:39:24 -07006826 if (value != AUDIO_DEVICE_NONE) {
6827 mPrevInDevice = value;
6828 }
Eric Laurent10351942014-05-08 18:49:52 -07006829 // disable AEC and NS if the device is a BT SCO headset supporting those
6830 // pre processings
6831 if (mTracks.size() > 0) {
6832 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6833 mAudioFlinger->btNrecIsOff();
6834 for (size_t i = 0; i < mTracks.size(); i++) {
6835 sp<RecordTrack> track = mTracks[i];
6836 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
6837 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08006838 }
6839 }
6840 }
Eric Laurent10351942014-05-08 18:49:52 -07006841 }
6842 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
6843 mAudioSource != (audio_source_t)value) {
6844 // forward device change to effects that have requested to be
6845 // aware of attached audio device.
6846 for (size_t i = 0; i < mEffectChains.size(); i++) {
6847 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08006848 }
Eric Laurent10351942014-05-08 18:49:52 -07006849 mAudioSource = (audio_source_t)value;
6850 }
Glenn Kastene198c362013-08-13 09:13:36 -07006851
Eric Laurent10351942014-05-08 18:49:52 -07006852 if (status == NO_ERROR) {
6853 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6854 keyValuePair.string());
6855 if (status == INVALID_OPERATION) {
6856 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006857 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6858 keyValuePair.string());
Eric Laurent10351942014-05-08 18:49:52 -07006859 }
6860 if (reconfig) {
6861 if (status == BAD_VALUE &&
Andy Hung97a893e2015-03-29 01:03:07 -07006862 audio_is_linear_pcm(mInput->stream->common.get_format(&mInput->stream->common)) &&
6863 audio_is_linear_pcm(reqFormat) &&
Eric Laurent10351942014-05-08 18:49:52 -07006864 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
Andy Hung97a893e2015-03-29 01:03:07 -07006865 <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate)) &&
Andy Hunge5412692014-05-16 11:25:07 -07006866 audio_channel_count_from_in_mask(
Andy Hungd1abb8f2015-05-05 23:42:34 -07006867 mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07006868 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006869 }
Eric Laurent10351942014-05-08 18:49:52 -07006870 if (status == NO_ERROR) {
6871 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07006872 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08006873 }
6874 }
Eric Laurent81784c32012-11-19 14:55:58 -08006875 }
Eric Laurent10351942014-05-08 18:49:52 -07006876
Eric Laurent81784c32012-11-19 14:55:58 -08006877 return reconfig;
6878}
6879
6880String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6881{
Eric Laurent81784c32012-11-19 14:55:58 -08006882 Mutex::Autolock _l(mLock);
6883 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07006884 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08006885 }
6886
Glenn Kastend8ea6992013-07-16 14:17:15 -07006887 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
6888 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08006889 free(s);
6890 return out_s8;
6891}
6892
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07006893void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07006894 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
6895
6896 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08006897
6898 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07006899 case AUDIO_INPUT_OPENED:
6900 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07006901 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07006902 desc->mChannelMask = mChannelMask;
6903 desc->mSamplingRate = mSampleRate;
6904 desc->mFormat = mFormat;
6905 desc->mFrameCount = mFrameCount;
6906 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006907 break;
6908
Eric Laurent73e26b62015-04-27 16:55:58 -07006909 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08006910 default:
6911 break;
6912 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07006913 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08006914}
6915
Glenn Kastendeca2ae2014-02-07 10:25:56 -08006916void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006917{
Eric Laurent81784c32012-11-19 14:55:58 -08006918 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
6919 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Andy Hunge5412692014-05-16 11:25:07 -07006920 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Andy Hungd330ee42015-04-20 13:23:41 -07006921 if (mChannelCount > FCC_8) {
6922 ALOGE("HAL channel count %d > %d", mChannelCount, FCC_8);
6923 }
Andy Hung463be252014-07-10 16:56:07 -07006924 mHALFormat = mInput->stream->common.get_format(&mInput->stream->common);
6925 mFormat = mHALFormat;
Andy Hungd330ee42015-04-20 13:23:41 -07006926 if (!audio_is_linear_pcm(mFormat)) {
6927 ALOGE("HAL format %#x is not linear pcm", mFormat);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07006928 }
Eric Laurent665470b2014-07-03 16:37:08 -07006929 mFrameSize = audio_stream_in_frame_size(mInput->stream);
Glenn Kasten548efc92012-11-29 08:48:51 -08006930 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
6931 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006932 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08006933 // 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 -07006934 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08006935 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006936 // A larger value should allow more old data to be read after a track calls start(),
6937 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07006938 //
6939 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08006940 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07006941 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07006942 free(mRsmpInBuffer);
Andy Hung0a01c2f2015-09-21 12:44:54 -07006943 mRsmpInBuffer = NULL;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006944
6945 // TODO optimize audio capture buffer sizes ...
6946 // Here we calculate the size of the sliding buffer used as a source
6947 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
6948 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
6949 // be better to have it derived from the pipe depth in the long term.
6950 // The current value is higher than necessary. However it should not add to latency.
6951
Glenn Kasten85948432013-08-19 12:09:05 -07006952 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Andy Hung0a01c2f2015-09-21 12:44:54 -07006953 size_t bufferSize = (mRsmpInFramesP2 + mFrameCount - 1) * mFrameSize;
6954 (void)posix_memalign(&mRsmpInBuffer, 32, bufferSize);
6955 memset(mRsmpInBuffer, 0, bufferSize); // if posix_memalign fails, will segv here.
Eric Laurent81784c32012-11-19 14:55:58 -08006956
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006957 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
6958 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08006959}
6960
Glenn Kasten5f972c02014-01-13 09:59:31 -08006961uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08006962{
6963 Mutex::Autolock _l(mLock);
6964 if (initCheck() != NO_ERROR) {
6965 return 0;
6966 }
6967
6968 return mInput->stream->get_input_frames_lost(mInput->stream);
6969}
6970
6971uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
6972{
6973 Mutex::Autolock _l(mLock);
6974 uint32_t result = 0;
6975 if (getEffectChain_l(sessionId) != 0) {
6976 result = EFFECT_SESSION;
6977 }
6978
6979 for (size_t i = 0; i < mTracks.size(); ++i) {
6980 if (sessionId == mTracks[i]->sessionId()) {
6981 result |= TRACK_SESSION;
6982 break;
6983 }
6984 }
6985
6986 return result;
6987}
6988
6989KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
6990{
6991 KeyedVector<int, bool> ids;
6992 Mutex::Autolock _l(mLock);
6993 for (size_t j = 0; j < mTracks.size(); ++j) {
6994 sp<RecordThread::RecordTrack> track = mTracks[j];
6995 int sessionId = track->sessionId();
6996 if (ids.indexOfKey(sessionId) < 0) {
6997 ids.add(sessionId, true);
6998 }
6999 }
7000 return ids;
7001}
7002
7003AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
7004{
7005 Mutex::Autolock _l(mLock);
7006 AudioStreamIn *input = mInput;
7007 mInput = NULL;
7008 return input;
7009}
7010
7011// this method must always be called either with ThreadBase mLock held or inside the thread loop
7012audio_stream_t* AudioFlinger::RecordThread::stream() const
7013{
7014 if (mInput == NULL) {
7015 return NULL;
7016 }
7017 return &mInput->stream->common;
7018}
7019
7020status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7021{
7022 // only one chain per input thread
7023 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07007024 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08007025 return INVALID_OPERATION;
7026 }
7027 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07007028 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08007029 chain->setInBuffer(NULL);
7030 chain->setOutBuffer(NULL);
7031
7032 checkSuspendOnAddEffectChain_l(chain);
7033
Eric Laurent1b928682014-10-02 19:41:47 -07007034 // make sure enabled pre processing effects state is communicated to the HAL as we
7035 // just moved them to a new input stream.
7036 chain->syncHalEffectsState();
7037
Eric Laurent81784c32012-11-19 14:55:58 -08007038 mEffectChains.add(chain);
7039
7040 return NO_ERROR;
7041}
7042
7043size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7044{
7045 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
7046 ALOGW_IF(mEffectChains.size() != 1,
7047 "removeEffectChain_l() %p invalid chain size %d on thread %p",
7048 chain.get(), mEffectChains.size(), this);
7049 if (mEffectChains.size() == 1) {
7050 mEffectChains.removeAt(0);
7051 }
7052 return 0;
7053}
7054
Eric Laurent1c333e22014-05-20 10:48:17 -07007055status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
7056 audio_patch_handle_t *handle)
7057{
7058 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007059
7060 // store new device and send to effects
7061 mInDevice = patch->sources[0].ext.device.type;
Eric Laurent296fb132015-05-01 11:38:42 -07007062 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07007063 for (size_t i = 0; i < mEffectChains.size(); i++) {
7064 mEffectChains[i]->setDevice_l(mInDevice);
7065 }
7066
7067 // disable AEC and NS if the device is a BT SCO headset supporting those
7068 // pre processings
7069 if (mTracks.size() > 0) {
7070 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7071 mAudioFlinger->btNrecIsOff();
7072 for (size_t i = 0; i < mTracks.size(); i++) {
7073 sp<RecordTrack> track = mTracks[i];
7074 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7075 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
7076 }
7077 }
7078
7079 // store new source and send to effects
7080 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7081 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07007082 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07007083 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07007084 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007085 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007086
Eric Laurent054d9d32015-04-24 08:48:48 -07007087 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007088 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
7089 status = hwDevice->create_audio_patch(hwDevice,
7090 patch->num_sources,
7091 patch->sources,
7092 patch->num_sinks,
7093 patch->sinks,
7094 handle);
7095 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007096 char *address;
7097 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
7098 address = audio_device_address_to_parameter(
7099 patch->sources[0].ext.device.type,
7100 patch->sources[0].ext.device.address);
7101 } else {
7102 address = (char *)calloc(1, 1);
7103 }
7104 AudioParameter param = AudioParameter(String8(address));
7105 free(address);
7106 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING),
7107 (int)patch->sources[0].ext.device.type);
7108 param.addInt(String8(AUDIO_PARAMETER_STREAM_INPUT_SOURCE),
7109 (int)patch->sinks[0].ext.mix.usecase.source);
7110 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7111 param.toString().string());
7112 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07007113 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007114
Eric Laurente8726fe2015-06-26 09:39:24 -07007115 if (mInDevice != mPrevInDevice) {
7116 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
7117 mPrevInDevice = mInDevice;
7118 }
Eric Laurent296fb132015-05-01 11:38:42 -07007119
Eric Laurent1c333e22014-05-20 10:48:17 -07007120 return status;
7121}
7122
7123status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
7124{
7125 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007126
7127 mInDevice = AUDIO_DEVICE_NONE;
7128
Eric Laurent1c333e22014-05-20 10:48:17 -07007129 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
7130 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
7131 status = hwDevice->release_audio_patch(hwDevice, handle);
7132 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007133 AudioParameter param;
7134 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
7135 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7136 param.toString().string());
Eric Laurent1c333e22014-05-20 10:48:17 -07007137 }
7138 return status;
7139}
7140
Eric Laurent83b88082014-06-20 18:31:16 -07007141void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
7142{
7143 Mutex::Autolock _l(mLock);
7144 mTracks.add(record);
7145}
7146
7147void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
7148{
7149 Mutex::Autolock _l(mLock);
7150 destroyTrack_l(record);
7151}
7152
7153void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
7154{
7155 ThreadBase::getAudioPortConfig(config);
7156 config->role = AUDIO_PORT_ROLE_SINK;
7157 config->ext.mix.hw_module = mInput->audioHwDev->handle();
7158 config->ext.mix.usecase.source = mAudioSource;
7159}
Eric Laurent1c333e22014-05-20 10:48:17 -07007160
Glenn Kasten63238ef2015-03-02 15:50:29 -08007161} // namespace android