blob: 966fb5cd1855281b483af972fcc6dcf28c525da3 [file] [log] [blame]
Eric Laurent81784c32012-11-19 14:55:58 -08001/*
2**
3** Copyright 2012, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
Alex Ray371eb972012-11-30 11:11:54 -080021#define ATRACE_TAG ATRACE_TAG_AUDIO
Eric Laurent81784c32012-11-19 14:55:58 -080022
Glenn Kasten153b9fe2013-07-15 11:23:36 -070023#include "Configuration.h"
Eric Laurent81784c32012-11-19 14:55:58 -080024#include <math.h>
25#include <fcntl.h>
Glenn Kastenad8510a2015-02-17 16:24:07 -080026#include <linux/futex.h>
Eric Laurent81784c32012-11-19 14:55:58 -080027#include <sys/stat.h>
Glenn Kastenad8510a2015-02-17 16:24:07 -080028#include <sys/syscall.h>
Eric Laurent81784c32012-11-19 14:55:58 -080029#include <cutils/properties.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070030#include <media/AudioParameter.h>
Andy Hungcd044842014-08-07 11:04:34 -070031#include <media/AudioResamplerPublic.h>
Eric Laurent81784c32012-11-19 14:55:58 -080032#include <utils/Log.h>
Alex Ray371eb972012-11-30 11:11:54 -080033#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080034
35#include <private/media/AudioTrackShared.h>
36#include <hardware/audio.h>
37#include <audio_effects/effect_ns.h>
38#include <audio_effects/effect_aec.h>
39#include <audio_utils/primitives.h>
Andy Hung98ef9782014-03-04 14:46:50 -080040#include <audio_utils/format.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070041#include <audio_utils/minifloat.h>
Eric Laurent81784c32012-11-19 14:55:58 -080042
43// NBAIO implementations
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070044#include <media/nbaio/AudioStreamInSource.h>
Eric Laurent81784c32012-11-19 14:55:58 -080045#include <media/nbaio/AudioStreamOutSink.h>
46#include <media/nbaio/MonoPipe.h>
47#include <media/nbaio/MonoPipeReader.h>
48#include <media/nbaio/Pipe.h>
49#include <media/nbaio/PipeReader.h>
50#include <media/nbaio/SourceAudioBufferProvider.h>
51
52#include <powermanager/PowerManager.h>
53
54#include <common_time/cc_helper.h>
55#include <common_time/local_clock.h>
56
57#include "AudioFlinger.h"
58#include "AudioMixer.h"
Andy Hungd330ee42015-04-20 13:23:41 -070059#include "BufferProviders.h"
Eric Laurent81784c32012-11-19 14:55:58 -080060#include "FastMixer.h"
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070061#include "FastCapture.h"
Eric Laurent81784c32012-11-19 14:55:58 -080062#include "ServiceUtilities.h"
63#include "SchedulingPolicyService.h"
64
Eric Laurent81784c32012-11-19 14:55:58 -080065#ifdef ADD_BATTERY_DATA
66#include <media/IMediaPlayerService.h>
67#include <media/IMediaDeathNotifier.h>
68#endif
69
Eric Laurent81784c32012-11-19 14:55:58 -080070#ifdef DEBUG_CPU_USAGE
71#include <cpustats/CentralTendencyStatistics.h>
72#include <cpustats/ThreadCpuUsage.h>
73#endif
74
75// ----------------------------------------------------------------------------
76
77// Note: the following macro is used for extremely verbose logging message. In
78// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
79// 0; but one side effect of this is to turn all LOGV's as well. Some messages
80// are so verbose that we want to suppress them even when we have ALOG_ASSERT
81// turned on. Do not uncomment the #def below unless you really know what you
82// are doing and want to see all of the extremely verbose messages.
83//#define VERY_VERY_VERBOSE_LOGGING
84#ifdef VERY_VERY_VERBOSE_LOGGING
85#define ALOGVV ALOGV
86#else
87#define ALOGVV(a...) do { } while(0)
88#endif
89
Andy Hung6770c6f2015-04-07 13:43:36 -070090// TODO: Move these macro/inlines to a header file.
Glenn Kasten49d00ad2014-07-21 11:22:03 -070091#define max(a, b) ((a) > (b) ? (a) : (b))
Andy Hung6770c6f2015-04-07 13:43:36 -070092template <typename T>
93static inline T min(const T& a, const T& b)
94{
95 return a < b ? a : b;
96}
Glenn Kasten49d00ad2014-07-21 11:22:03 -070097
Andy Hungd330ee42015-04-20 13:23:41 -070098#ifndef ARRAY_SIZE
99#define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
100#endif
101
Eric Laurent81784c32012-11-19 14:55:58 -0800102namespace android {
103
104// retry counts for buffer fill timeout
105// 50 * ~20msecs = 1 second
106static const int8_t kMaxTrackRetries = 50;
107static const int8_t kMaxTrackStartupRetries = 50;
108// allow less retry attempts on direct output thread.
109// direct outputs can be a scarce resource in audio hardware and should
110// be released as quickly as possible.
111static const int8_t kMaxTrackRetriesDirect = 2;
112
113// don't warn about blocked writes or record buffer overflows more often than this
114static const nsecs_t kWarningThrottleNs = seconds(5);
115
116// RecordThread loop sleep time upon application overrun or audio HAL read error
117static const int kRecordThreadSleepUs = 5000;
118
Eric Laurent10351942014-05-08 18:49:52 -0700119// maximum time to wait in sendConfigEvent_l() for a status to be received
120static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800121
122// minimum sleep time for the mixer thread loop when tracks are active but in underrun
123static const uint32_t kMinThreadSleepTimeUs = 5000;
124// maximum divider applied to the active sleep time in the mixer thread loop
125static const uint32_t kMaxThreadSleepTimeShift = 2;
126
Andy Hung09a50072014-02-27 14:30:47 -0800127// minimum normal sink buffer size, expressed in milliseconds rather than frames
128static const uint32_t kMinNormalSinkBufferSizeMs = 20;
129// maximum normal sink buffer size
130static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800131
Eric Laurent972a1732013-09-04 09:42:59 -0700132// Offloaded output thread standby delay: allows track transition without going to standby
133static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
134
Eric Laurent81784c32012-11-19 14:55:58 -0800135// Whether to use fast mixer
136static const enum {
137 FastMixer_Never, // never initialize or use: for debugging only
138 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
139 // normal mixer multiplier is 1
140 FastMixer_Static, // initialize if needed, then use all the time if initialized,
141 // multiplier is calculated based on min & max normal mixer buffer size
142 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
143 // multiplier is calculated based on min & max normal mixer buffer size
144 // FIXME for FastMixer_Dynamic:
145 // Supporting this option will require fixing HALs that can't handle large writes.
146 // For example, one HAL implementation returns an error from a large write,
147 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
148 // We could either fix the HAL implementations, or provide a wrapper that breaks
149 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
150} kUseFastMixer = FastMixer_Static;
151
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700152// Whether to use fast capture
153static const enum {
154 FastCapture_Never, // never initialize or use: for debugging only
155 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
156 FastCapture_Static, // initialize if needed, then use all the time if initialized
157} kUseFastCapture = FastCapture_Static;
158
Eric Laurent81784c32012-11-19 14:55:58 -0800159// Priorities for requestPriority
160static const int kPriorityAudioApp = 2;
161static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700162static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800163
164// IAudioFlinger::createTrack() reports back to client the total size of shared memory area
165// for the track. The client then sub-divides this into smaller buffers for its use.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800166// Currently the client uses N-buffering by default, but doesn't tell us about the value of N.
167// So for now we just assume that client is double-buffered for fast tracks.
168// FIXME It would be better for client to tell AudioFlinger the value of N,
169// so AudioFlinger could allocate the right amount of memory.
Eric Laurent81784c32012-11-19 14:55:58 -0800170// See the client's minBufCount and mNotificationFramesAct calculations for details.
Glenn Kasten03490092014-05-27 12:30:54 -0700171
172// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800173static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800174
Glenn Kasten03490092014-05-27 12:30:54 -0700175// The minimum and maximum allowed values
176static const int kFastTrackMultiplierMin = 1;
177static const int kFastTrackMultiplierMax = 2;
178
179// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
180static int sFastTrackMultiplier = kFastTrackMultiplier;
181
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700182// See Thread::readOnlyHeap().
183// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
184// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
185// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Glenn Kasten9f81de32014-07-27 15:02:23 -0700186static const size_t kRecordThreadReadOnlyHeapSize = 0x2000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700187
Eric Laurent81784c32012-11-19 14:55:58 -0800188// ----------------------------------------------------------------------------
189
Glenn Kasten03490092014-05-27 12:30:54 -0700190static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
191
192static void sFastTrackMultiplierInit()
193{
194 char value[PROPERTY_VALUE_MAX];
195 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
196 char *endptr;
197 unsigned long ul = strtoul(value, &endptr, 0);
198 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
199 sFastTrackMultiplier = (int) ul;
200 }
201 }
202}
203
204// ----------------------------------------------------------------------------
205
Eric Laurent81784c32012-11-19 14:55:58 -0800206#ifdef ADD_BATTERY_DATA
207// To collect the amplifier usage
208static void addBatteryData(uint32_t params) {
209 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
210 if (service == NULL) {
211 // it already logged
212 return;
213 }
214
215 service->addBatteryData(params);
216}
217#endif
218
219
220// ----------------------------------------------------------------------------
221// CPU Stats
222// ----------------------------------------------------------------------------
223
224class CpuStats {
225public:
226 CpuStats();
227 void sample(const String8 &title);
228#ifdef DEBUG_CPU_USAGE
229private:
230 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
231 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
232
233 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
234
235 int mCpuNum; // thread's current CPU number
236 int mCpukHz; // frequency of thread's current CPU in kHz
237#endif
238};
239
240CpuStats::CpuStats()
241#ifdef DEBUG_CPU_USAGE
242 : mCpuNum(-1), mCpukHz(-1)
243#endif
244{
245}
246
Glenn Kasten0f11b512014-01-31 16:18:54 -0800247void CpuStats::sample(const String8 &title
248#ifndef DEBUG_CPU_USAGE
249 __unused
250#endif
251 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800252#ifdef DEBUG_CPU_USAGE
253 // get current thread's delta CPU time in wall clock ns
254 double wcNs;
255 bool valid = mCpuUsage.sampleAndEnable(wcNs);
256
257 // record sample for wall clock statistics
258 if (valid) {
259 mWcStats.sample(wcNs);
260 }
261
262 // get the current CPU number
263 int cpuNum = sched_getcpu();
264
265 // get the current CPU frequency in kHz
266 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
267
268 // check if either CPU number or frequency changed
269 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
270 mCpuNum = cpuNum;
271 mCpukHz = cpukHz;
272 // ignore sample for purposes of cycles
273 valid = false;
274 }
275
276 // if no change in CPU number or frequency, then record sample for cycle statistics
277 if (valid && mCpukHz > 0) {
278 double cycles = wcNs * cpukHz * 0.000001;
279 mHzStats.sample(cycles);
280 }
281
282 unsigned n = mWcStats.n();
283 // mCpuUsage.elapsed() is expensive, so don't call it every loop
284 if ((n & 127) == 1) {
285 long long elapsed = mCpuUsage.elapsed();
286 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
287 double perLoop = elapsed / (double) n;
288 double perLoop100 = perLoop * 0.01;
289 double perLoop1k = perLoop * 0.001;
290 double mean = mWcStats.mean();
291 double stddev = mWcStats.stddev();
292 double minimum = mWcStats.minimum();
293 double maximum = mWcStats.maximum();
294 double meanCycles = mHzStats.mean();
295 double stddevCycles = mHzStats.stddev();
296 double minCycles = mHzStats.minimum();
297 double maxCycles = mHzStats.maximum();
298 mCpuUsage.resetElapsed();
299 mWcStats.reset();
300 mHzStats.reset();
301 ALOGD("CPU usage for %s over past %.1f secs\n"
302 " (%u mixer loops at %.1f mean ms per loop):\n"
303 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
304 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
305 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
306 title.string(),
307 elapsed * .000000001, n, perLoop * .000001,
308 mean * .001,
309 stddev * .001,
310 minimum * .001,
311 maximum * .001,
312 mean / perLoop100,
313 stddev / perLoop100,
314 minimum / perLoop100,
315 maximum / perLoop100,
316 meanCycles / perLoop1k,
317 stddevCycles / perLoop1k,
318 minCycles / perLoop1k,
319 maxCycles / perLoop1k);
320
321 }
322 }
323#endif
324};
325
326// ----------------------------------------------------------------------------
327// ThreadBase
328// ----------------------------------------------------------------------------
329
Glenn Kasten97b7b752014-09-28 13:04:24 -0700330// static
331const char *AudioFlinger::ThreadBase::threadTypeToString(AudioFlinger::ThreadBase::type_t type)
332{
333 switch (type) {
334 case MIXER:
335 return "MIXER";
336 case DIRECT:
337 return "DIRECT";
338 case DUPLICATING:
339 return "DUPLICATING";
340 case RECORD:
341 return "RECORD";
342 case OFFLOAD:
343 return "OFFLOAD";
344 default:
345 return "unknown";
346 }
347}
348
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800349String8 devicesToString(audio_devices_t devices)
350{
351 static const struct mapping {
352 audio_devices_t mDevices;
353 const char * mString;
354 } mappingsOut[] = {
355 AUDIO_DEVICE_OUT_EARPIECE, "EARPIECE",
356 AUDIO_DEVICE_OUT_SPEAKER, "SPEAKER",
357 AUDIO_DEVICE_OUT_WIRED_HEADSET, "WIRED_HEADSET",
358 AUDIO_DEVICE_OUT_WIRED_HEADPHONE, "WIRED_HEADPHONE",
Glenn Kasten84d61ca2015-05-06 18:32:13 -0700359 AUDIO_DEVICE_OUT_BLUETOOTH_SCO, "BLUETOOTH_SCO",
360 AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET, "BLUETOOTH_SCO_HEADSET",
361 AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT, "BLUETOOTH_SCO_CARKIT",
362 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, "BLUETOOTH_A2DP",
363 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES, "BLUETOOTH_A2DP_HEADPHONES",
364 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER, "BLUETOOTH_A2DP_SPEAKER",
365 AUDIO_DEVICE_OUT_AUX_DIGITAL, "AUX_DIGITAL",
366 AUDIO_DEVICE_OUT_HDMI, "HDMI",
367 AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET, "ANLG_DOCK_HEADSET",
368 AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET, "DGTL_DOCK_HEADSET",
369 AUDIO_DEVICE_OUT_USB_ACCESSORY, "USB_ACCESSORY",
370 AUDIO_DEVICE_OUT_USB_DEVICE, "USB_DEVICE",
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800371 AUDIO_DEVICE_OUT_TELEPHONY_TX, "TELEPHONY_TX",
Glenn Kasten84d61ca2015-05-06 18:32:13 -0700372 AUDIO_DEVICE_OUT_LINE, "LINE",
373 AUDIO_DEVICE_OUT_HDMI_ARC, "HDMI_ARC",
374 AUDIO_DEVICE_OUT_SPDIF, "SPDIF",
375 AUDIO_DEVICE_OUT_FM, "FM",
376 AUDIO_DEVICE_OUT_AUX_LINE, "AUX_LINE",
377 AUDIO_DEVICE_OUT_SPEAKER_SAFE, "SPEAKER_SAFE",
Eric Laurentb9d73332015-06-30 17:09:20 -0700378 AUDIO_DEVICE_OUT_IP, "IP",
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800379 AUDIO_DEVICE_NONE, "NONE", // must be last
380 }, mappingsIn[] = {
Glenn Kasten84d61ca2015-05-06 18:32:13 -0700381 AUDIO_DEVICE_IN_COMMUNICATION, "COMMUNICATION",
382 AUDIO_DEVICE_IN_AMBIENT, "AMBIENT",
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800383 AUDIO_DEVICE_IN_BUILTIN_MIC, "BUILTIN_MIC",
Glenn Kasten84d61ca2015-05-06 18:32:13 -0700384 AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET, "BLUETOOTH_SCO_HEADSET",
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800385 AUDIO_DEVICE_IN_WIRED_HEADSET, "WIRED_HEADSET",
Glenn Kasten84d61ca2015-05-06 18:32:13 -0700386 AUDIO_DEVICE_IN_AUX_DIGITAL, "AUX_DIGITAL",
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800387 AUDIO_DEVICE_IN_VOICE_CALL, "VOICE_CALL",
Glenn Kasten84d61ca2015-05-06 18:32:13 -0700388 AUDIO_DEVICE_IN_TELEPHONY_RX, "TELEPHONY_RX",
389 AUDIO_DEVICE_IN_BACK_MIC, "BACK_MIC",
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800390 AUDIO_DEVICE_IN_REMOTE_SUBMIX, "REMOTE_SUBMIX",
Glenn Kasten84d61ca2015-05-06 18:32:13 -0700391 AUDIO_DEVICE_IN_ANLG_DOCK_HEADSET, "ANLG_DOCK_HEADSET",
392 AUDIO_DEVICE_IN_DGTL_DOCK_HEADSET, "DGTL_DOCK_HEADSET",
393 AUDIO_DEVICE_IN_USB_ACCESSORY, "USB_ACCESSORY",
394 AUDIO_DEVICE_IN_USB_DEVICE, "USB_DEVICE",
395 AUDIO_DEVICE_IN_FM_TUNER, "FM_TUNER",
396 AUDIO_DEVICE_IN_TV_TUNER, "TV_TUNER",
397 AUDIO_DEVICE_IN_LINE, "LINE",
398 AUDIO_DEVICE_IN_SPDIF, "SPDIF",
399 AUDIO_DEVICE_IN_BLUETOOTH_A2DP, "BLUETOOTH_A2DP",
400 AUDIO_DEVICE_IN_LOOPBACK, "LOOPBACK",
Eric Laurentb9d73332015-06-30 17:09:20 -0700401 AUDIO_DEVICE_IN_IP, "IP",
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800402 AUDIO_DEVICE_NONE, "NONE", // must be last
403 };
404 String8 result;
405 audio_devices_t allDevices = AUDIO_DEVICE_NONE;
406 const mapping *entry;
407 if (devices & AUDIO_DEVICE_BIT_IN) {
408 devices &= ~AUDIO_DEVICE_BIT_IN;
409 entry = mappingsIn;
410 } else {
411 entry = mappingsOut;
412 }
413 for ( ; entry->mDevices != AUDIO_DEVICE_NONE; entry++) {
414 allDevices = (audio_devices_t) (allDevices | entry->mDevices);
415 if (devices & entry->mDevices) {
416 if (!result.isEmpty()) {
417 result.append("|");
418 }
419 result.append(entry->mString);
420 }
421 }
422 if (devices & ~allDevices) {
423 if (!result.isEmpty()) {
424 result.append("|");
425 }
426 result.appendFormat("0x%X", devices & ~allDevices);
427 }
428 if (result.isEmpty()) {
429 result.append(entry->mString);
430 }
431 return result;
432}
433
434String8 inputFlagsToString(audio_input_flags_t flags)
435{
436 static const struct mapping {
437 audio_input_flags_t mFlag;
438 const char * mString;
439 } mappings[] = {
440 AUDIO_INPUT_FLAG_FAST, "FAST",
441 AUDIO_INPUT_FLAG_HW_HOTWORD, "HW_HOTWORD",
442 AUDIO_INPUT_FLAG_NONE, "NONE", // must be last
443 };
444 String8 result;
445 audio_input_flags_t allFlags = AUDIO_INPUT_FLAG_NONE;
446 const mapping *entry;
447 for (entry = mappings; entry->mFlag != AUDIO_INPUT_FLAG_NONE; entry++) {
448 allFlags = (audio_input_flags_t) (allFlags | entry->mFlag);
449 if (flags & entry->mFlag) {
450 if (!result.isEmpty()) {
451 result.append("|");
452 }
453 result.append(entry->mString);
454 }
455 }
456 if (flags & ~allFlags) {
457 if (!result.isEmpty()) {
458 result.append("|");
459 }
460 result.appendFormat("0x%X", flags & ~allFlags);
461 }
462 if (result.isEmpty()) {
463 result.append(entry->mString);
464 }
465 return result;
466}
467
468String8 outputFlagsToString(audio_output_flags_t flags)
Glenn Kasten97b7b752014-09-28 13:04:24 -0700469{
470 static const struct mapping {
471 audio_output_flags_t mFlag;
472 const char * mString;
473 } mappings[] = {
474 AUDIO_OUTPUT_FLAG_DIRECT, "DIRECT",
475 AUDIO_OUTPUT_FLAG_PRIMARY, "PRIMARY",
476 AUDIO_OUTPUT_FLAG_FAST, "FAST",
477 AUDIO_OUTPUT_FLAG_DEEP_BUFFER, "DEEP_BUFFER",
Glenn Kastendfb0e112015-02-18 14:33:39 -0800478 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD, "COMPRESS_OFFLOAD",
Glenn Kasten97b7b752014-09-28 13:04:24 -0700479 AUDIO_OUTPUT_FLAG_NON_BLOCKING, "NON_BLOCKING",
480 AUDIO_OUTPUT_FLAG_HW_AV_SYNC, "HW_AV_SYNC",
481 AUDIO_OUTPUT_FLAG_NONE, "NONE", // must be last
482 };
483 String8 result;
484 audio_output_flags_t allFlags = AUDIO_OUTPUT_FLAG_NONE;
485 const mapping *entry;
486 for (entry = mappings; entry->mFlag != AUDIO_OUTPUT_FLAG_NONE; entry++) {
487 allFlags = (audio_output_flags_t) (allFlags | entry->mFlag);
488 if (flags & entry->mFlag) {
489 if (!result.isEmpty()) {
490 result.append("|");
491 }
492 result.append(entry->mString);
493 }
494 }
495 if (flags & ~allFlags) {
496 if (!result.isEmpty()) {
497 result.append("|");
498 }
499 result.appendFormat("0x%X", flags & ~allFlags);
500 }
501 if (result.isEmpty()) {
502 result.append(entry->mString);
503 }
504 return result;
505}
506
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800507const char *sourceToString(audio_source_t source)
508{
509 switch (source) {
510 case AUDIO_SOURCE_DEFAULT: return "default";
511 case AUDIO_SOURCE_MIC: return "mic";
512 case AUDIO_SOURCE_VOICE_UPLINK: return "voice uplink";
513 case AUDIO_SOURCE_VOICE_DOWNLINK: return "voice downlink";
514 case AUDIO_SOURCE_VOICE_CALL: return "voice call";
515 case AUDIO_SOURCE_CAMCORDER: return "camcorder";
516 case AUDIO_SOURCE_VOICE_RECOGNITION: return "voice recognition";
517 case AUDIO_SOURCE_VOICE_COMMUNICATION: return "voice communication";
518 case AUDIO_SOURCE_REMOTE_SUBMIX: return "remote submix";
519 case AUDIO_SOURCE_FM_TUNER: return "FM tuner";
520 case AUDIO_SOURCE_HOTWORD: return "hotword";
521 default: return "unknown";
522 }
523}
524
Eric Laurent81784c32012-11-19 14:55:58 -0800525AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -0700526 audio_devices_t outDevice, audio_devices_t inDevice, type_t type, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -0800527 : Thread(false /*canCallJava*/),
528 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700529 mAudioFlinger(audioFlinger),
Glenn Kasten70949c42013-08-06 07:40:12 -0700530 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800531 // are set by PlaybackThread::readOutputParameters_l() or
532 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700533 //FIXME: mStandby should be true here. Is this some kind of hack?
Eric Laurent81784c32012-11-19 14:55:58 -0800534 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
Eric Laurente8726fe2015-06-26 09:39:24 -0700535 mPrevInDevice(AUDIO_DEVICE_NONE), mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Eric Laurent81784c32012-11-19 14:55:58 -0800536 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700537 mDeathRecipient(new PMDeathRecipient(this)),
538 mSystemReady(systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -0800539{
Eric Laurent296fb132015-05-01 11:38:42 -0700540 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800541}
542
543AudioFlinger::ThreadBase::~ThreadBase()
544{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700545 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700546 mConfigEvents.clear();
547
Eric Laurent81784c32012-11-19 14:55:58 -0800548 // do not lock the mutex in destructor
549 releaseWakeLock_l();
550 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800551 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800552 binder->unlinkToDeath(mDeathRecipient);
553 }
554}
555
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700556status_t AudioFlinger::ThreadBase::readyToRun()
557{
558 status_t status = initCheck();
559 if (status == NO_ERROR) {
560 ALOGI("AudioFlinger's thread %p ready to run", this);
561 } else {
562 ALOGE("No working audio driver found.");
563 }
564 return status;
565}
566
Eric Laurent81784c32012-11-19 14:55:58 -0800567void AudioFlinger::ThreadBase::exit()
568{
569 ALOGV("ThreadBase::exit");
570 // do any cleanup required for exit to succeed
571 preExit();
572 {
573 // This lock prevents the following race in thread (uniprocessor for illustration):
574 // if (!exitPending()) {
575 // // context switch from here to exit()
576 // // exit() calls requestExit(), what exitPending() observes
577 // // exit() calls signal(), which is dropped since no waiters
578 // // context switch back from exit() to here
579 // mWaitWorkCV.wait(...);
580 // // now thread is hung
581 // }
582 AutoMutex lock(mLock);
583 requestExit();
584 mWaitWorkCV.broadcast();
585 }
586 // When Thread::requestExitAndWait is made virtual and this method is renamed to
587 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
588 requestExitAndWait();
589}
590
591status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
592{
593 status_t status;
594
595 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
596 Mutex::Autolock _l(mLock);
597
Eric Laurent10351942014-05-08 18:49:52 -0700598 return sendSetParameterConfigEvent_l(keyValuePairs);
599}
600
601// sendConfigEvent_l() must be called with ThreadBase::mLock held
602// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
603status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
604{
605 status_t status = NO_ERROR;
606
Eric Laurent72e3f392015-05-20 14:43:50 -0700607 if (event->mRequiresSystemReady && !mSystemReady) {
608 event->mWaitStatus = false;
609 mPendingConfigEvents.add(event);
610 return status;
611 }
Eric Laurent10351942014-05-08 18:49:52 -0700612 mConfigEvents.add(event);
613 ALOGV("sendConfigEvent_l() num events %d event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800614 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700615 mLock.unlock();
616 {
617 Mutex::Autolock _l(event->mLock);
618 while (event->mWaitStatus) {
619 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
620 event->mStatus = TIMED_OUT;
621 event->mWaitStatus = false;
622 }
623 }
624 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800625 }
Eric Laurent10351942014-05-08 18:49:52 -0700626 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800627 return status;
628}
629
Eric Laurent73e26b62015-04-27 16:55:58 -0700630void AudioFlinger::ThreadBase::sendIoConfigEvent(audio_io_config_event event)
Eric Laurent81784c32012-11-19 14:55:58 -0800631{
632 Mutex::Autolock _l(mLock);
Eric Laurent73e26b62015-04-27 16:55:58 -0700633 sendIoConfigEvent_l(event);
Eric Laurent81784c32012-11-19 14:55:58 -0800634}
635
636// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
Eric Laurent73e26b62015-04-27 16:55:58 -0700637void AudioFlinger::ThreadBase::sendIoConfigEvent_l(audio_io_config_event event)
Eric Laurent81784c32012-11-19 14:55:58 -0800638{
Eric Laurent73e26b62015-04-27 16:55:58 -0700639 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event);
Eric Laurent10351942014-05-08 18:49:52 -0700640 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800641}
642
Eric Laurent72e3f392015-05-20 14:43:50 -0700643void AudioFlinger::ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio)
644{
645 Mutex::Autolock _l(mLock);
646 sendPrioConfigEvent_l(pid, tid, prio);
647}
648
Eric Laurent81784c32012-11-19 14:55:58 -0800649// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
650void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
651{
Eric Laurent10351942014-05-08 18:49:52 -0700652 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio);
653 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800654}
655
Eric Laurent10351942014-05-08 18:49:52 -0700656// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
657status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800658{
Eric Laurent10351942014-05-08 18:49:52 -0700659 sp<ConfigEvent> configEvent = (ConfigEvent *)new SetParameterConfigEvent(keyValuePair);
660 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700661}
662
Eric Laurent1c333e22014-05-20 10:48:17 -0700663status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
664 const struct audio_patch *patch,
665 audio_patch_handle_t *handle)
666{
667 Mutex::Autolock _l(mLock);
668 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
669 status_t status = sendConfigEvent_l(configEvent);
670 if (status == NO_ERROR) {
671 CreateAudioPatchConfigEventData *data =
672 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
673 *handle = data->mHandle;
674 }
675 return status;
676}
677
678status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
679 const audio_patch_handle_t handle)
680{
681 Mutex::Autolock _l(mLock);
682 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
683 return sendConfigEvent_l(configEvent);
684}
685
686
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700687// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700688void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700689{
Eric Laurent10351942014-05-08 18:49:52 -0700690 bool configChanged = false;
691
Eric Laurent81784c32012-11-19 14:55:58 -0800692 while (!mConfigEvents.isEmpty()) {
Eric Laurent10351942014-05-08 18:49:52 -0700693 ALOGV("processConfigEvents_l() remaining events %d", mConfigEvents.size());
694 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800695 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700696 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700697 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700698 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
699 // FIXME Need to understand why this has to be done asynchronously
700 int err = requestPriority(data->mPid, data->mTid, data->mPrio,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700701 true /*asynchronous*/);
702 if (err != 0) {
703 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700704 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700705 }
706 } break;
707 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700708 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent73e26b62015-04-27 16:55:58 -0700709 ioConfigChanged(data->mEvent);
Eric Laurent10351942014-05-08 18:49:52 -0700710 } break;
711 case CFG_EVENT_SET_PARAMETER: {
712 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
713 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
714 configChanged = true;
Glenn Kastend5418eb2013-08-14 13:11:06 -0700715 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700716 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700717 case CFG_EVENT_CREATE_AUDIO_PATCH: {
718 CreateAudioPatchConfigEventData *data =
719 (CreateAudioPatchConfigEventData *)event->mData.get();
720 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
721 } break;
722 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
723 ReleaseAudioPatchConfigEventData *data =
724 (ReleaseAudioPatchConfigEventData *)event->mData.get();
725 event->mStatus = releaseAudioPatch_l(data->mHandle);
726 } break;
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700727 default:
Eric Laurent10351942014-05-08 18:49:52 -0700728 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700729 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800730 }
Eric Laurent10351942014-05-08 18:49:52 -0700731 {
732 Mutex::Autolock _l(event->mLock);
733 if (event->mWaitStatus) {
734 event->mWaitStatus = false;
735 event->mCond.signal();
736 }
737 }
738 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
739 }
740
741 if (configChanged) {
742 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800743 }
Eric Laurent81784c32012-11-19 14:55:58 -0800744}
745
Marco Nelissenb2208842014-02-07 14:00:50 -0800746String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
747 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700748 const audio_channel_representation_t representation =
749 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700750
751 switch (representation) {
752 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
753 if (output) {
754 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
755 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
756 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
757 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
758 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
759 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
760 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
761 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
762 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
763 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
764 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
765 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
766 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
767 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
768 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
769 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
770 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
771 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
772 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
773 } else {
774 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
775 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
776 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
777 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
778 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
779 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
780 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
781 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
782 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
783 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
784 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
785 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
786 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
787 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
788 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
789 }
790 const int len = s.length();
791 if (len > 2) {
792 char *str = s.lockBuffer(len); // needed?
793 s.unlockBuffer(len - 2); // remove trailing ", "
794 }
795 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800796 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700797 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
798 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
799 return s;
800 default:
801 s.appendFormat("unknown mask, representation:%d bits:%#x",
802 representation, audio_channel_mask_get_bits(mask));
803 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800804 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800805}
806
Glenn Kasten0f11b512014-01-31 16:18:54 -0800807void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800808{
809 const size_t SIZE = 256;
810 char buffer[SIZE];
811 String8 result;
812
813 bool locked = AudioFlinger::dumpTryLock(mLock);
814 if (!locked) {
Glenn Kasten97b7b752014-09-28 13:04:24 -0700815 dprintf(fd, "thread %p may be deadlocked\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -0800816 }
817
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800818 dprintf(fd, " Thread name: %s\n", mThreadName);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700819 dprintf(fd, " I/O handle: %d\n", mId);
820 dprintf(fd, " TID: %d\n", getTid());
821 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700822 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700823 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700824 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat));
Elliott Hughes87cebad2014-05-22 10:14:43 -0700825 dprintf(fd, " HAL buffer size: %u bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700826 dprintf(fd, " Channel count: %u\n", mChannelCount);
827 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800828 channelMaskToString(mChannelMask, mType != RECORD).string());
Glenn Kasten97b7b752014-09-28 13:04:24 -0700829 dprintf(fd, " Format: 0x%x (%s)\n", mFormat, formatToString(mFormat));
830 dprintf(fd, " Frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700831 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800832 size_t numConfig = mConfigEvents.size();
833 if (numConfig) {
834 for (size_t i = 0; i < numConfig; i++) {
835 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700836 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800837 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700838 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800839 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700840 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800841 }
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800842 dprintf(fd, " Output device: %#x (%s)\n", mOutDevice, devicesToString(mOutDevice).string());
843 dprintf(fd, " Input device: %#x (%s)\n", mInDevice, devicesToString(mInDevice).string());
844 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, sourceToString(mAudioSource));
Eric Laurent81784c32012-11-19 14:55:58 -0800845
846 if (locked) {
847 mLock.unlock();
848 }
849}
850
851void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
852{
853 const size_t SIZE = 256;
854 char buffer[SIZE];
855 String8 result;
856
Marco Nelissenb2208842014-02-07 14:00:50 -0800857 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000858 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800859 write(fd, buffer, strlen(buffer));
860
Marco Nelissenb2208842014-02-07 14:00:50 -0800861 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800862 sp<EffectChain> chain = mEffectChains[i];
863 if (chain != 0) {
864 chain->dump(fd, args);
865 }
866 }
867}
868
Marco Nelissene14a5d62013-10-03 08:51:24 -0700869void AudioFlinger::ThreadBase::acquireWakeLock(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800870{
871 Mutex::Autolock _l(mLock);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700872 acquireWakeLock_l(uid);
Eric Laurent81784c32012-11-19 14:55:58 -0800873}
874
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100875String16 AudioFlinger::ThreadBase::getWakeLockTag()
876{
877 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -0800878 case MIXER:
879 return String16("AudioMix");
880 case DIRECT:
881 return String16("AudioDirectOut");
882 case DUPLICATING:
883 return String16("AudioDup");
884 case RECORD:
885 return String16("AudioIn");
886 case OFFLOAD:
887 return String16("AudioOffload");
888 default:
889 ALOG_ASSERT(false);
890 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100891 }
892}
893
Marco Nelissene14a5d62013-10-03 08:51:24 -0700894void AudioFlinger::ThreadBase::acquireWakeLock_l(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800895{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800896 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800897 if (mPowerManager != 0) {
898 sp<IBinder> binder = new BBinder();
Marco Nelissene14a5d62013-10-03 08:51:24 -0700899 status_t status;
900 if (uid >= 0) {
Eric Laurent547789d2013-10-04 11:46:55 -0700901 status = mPowerManager->acquireWakeLockWithUid(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700902 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100903 getWakeLockTag(),
Marco Nelissene14a5d62013-10-03 08:51:24 -0700904 String16("media"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700905 uid,
906 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700907 } else {
Eric Laurent547789d2013-10-04 11:46:55 -0700908 status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700909 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100910 getWakeLockTag(),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700911 String16("media"),
912 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700913 }
Eric Laurent81784c32012-11-19 14:55:58 -0800914 if (status == NO_ERROR) {
915 mWakeLockToken = binder;
916 }
Glenn Kastend7dca052015-03-05 16:05:54 -0800917 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Eric Laurent81784c32012-11-19 14:55:58 -0800918 }
919}
920
921void AudioFlinger::ThreadBase::releaseWakeLock()
922{
923 Mutex::Autolock _l(mLock);
924 releaseWakeLock_l();
925}
926
927void AudioFlinger::ThreadBase::releaseWakeLock_l()
928{
929 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800930 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -0800931 if (mPowerManager != 0) {
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700932 mPowerManager->releaseWakeLock(mWakeLockToken, 0,
933 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800934 }
935 mWakeLockToken.clear();
936 }
937}
938
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800939void AudioFlinger::ThreadBase::updateWakeLockUids(const SortedVector<int> &uids) {
940 Mutex::Autolock _l(mLock);
941 updateWakeLockUids_l(uids);
942}
943
944void AudioFlinger::ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -0700945 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800946 // use checkService() to avoid blocking if power service is not up yet
947 sp<IBinder> binder =
948 defaultServiceManager()->checkService(String16("power"));
949 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800950 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800951 } else {
952 mPowerManager = interface_cast<IPowerManager>(binder);
953 binder->linkToDeath(mDeathRecipient);
954 }
955 }
956}
957
958void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<int> &uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800959 getPowerManager_l();
960 if (mWakeLockToken == NULL) {
961 ALOGE("no wake lock to update!");
962 return;
963 }
964 if (mPowerManager != 0) {
965 sp<IBinder> binder = new BBinder();
966 status_t status;
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700967 status = mPowerManager->updateWakeLockUids(mWakeLockToken, uids.size(), uids.array(),
968 true /* FIXME force oneway contrary to .aidl */);
Glenn Kastend7dca052015-03-05 16:05:54 -0800969 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800970 }
971}
972
Eric Laurent81784c32012-11-19 14:55:58 -0800973void AudioFlinger::ThreadBase::clearPowerManager()
974{
975 Mutex::Autolock _l(mLock);
976 releaseWakeLock_l();
977 mPowerManager.clear();
978}
979
Glenn Kasten0f11b512014-01-31 16:18:54 -0800980void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800981{
982 sp<ThreadBase> thread = mThread.promote();
983 if (thread != 0) {
984 thread->clearPowerManager();
985 }
986 ALOGW("power manager service died !!!");
987}
988
989void AudioFlinger::ThreadBase::setEffectSuspended(
990 const effect_uuid_t *type, bool suspend, int sessionId)
991{
992 Mutex::Autolock _l(mLock);
993 setEffectSuspended_l(type, suspend, sessionId);
994}
995
996void AudioFlinger::ThreadBase::setEffectSuspended_l(
997 const effect_uuid_t *type, bool suspend, int sessionId)
998{
999 sp<EffectChain> chain = getEffectChain_l(sessionId);
1000 if (chain != 0) {
1001 if (type != NULL) {
1002 chain->setEffectSuspended_l(type, suspend);
1003 } else {
1004 chain->setEffectSuspendedAll_l(suspend);
1005 }
1006 }
1007
1008 updateSuspendedSessions_l(type, suspend, sessionId);
1009}
1010
1011void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1012{
1013 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1014 if (index < 0) {
1015 return;
1016 }
1017
1018 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1019 mSuspendedSessions.valueAt(index);
1020
1021 for (size_t i = 0; i < sessionEffects.size(); i++) {
1022 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
1023 for (int j = 0; j < desc->mRefCount; j++) {
1024 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1025 chain->setEffectSuspendedAll_l(true);
1026 } else {
1027 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1028 desc->mType.timeLow);
1029 chain->setEffectSuspended_l(&desc->mType, true);
1030 }
1031 }
1032 }
1033}
1034
1035void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1036 bool suspend,
1037 int sessionId)
1038{
1039 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1040
1041 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1042
1043 if (suspend) {
1044 if (index >= 0) {
1045 sessionEffects = mSuspendedSessions.valueAt(index);
1046 } else {
1047 mSuspendedSessions.add(sessionId, sessionEffects);
1048 }
1049 } else {
1050 if (index < 0) {
1051 return;
1052 }
1053 sessionEffects = mSuspendedSessions.valueAt(index);
1054 }
1055
1056
1057 int key = EffectChain::kKeyForSuspendAll;
1058 if (type != NULL) {
1059 key = type->timeLow;
1060 }
1061 index = sessionEffects.indexOfKey(key);
1062
1063 sp<SuspendedSessionDesc> desc;
1064 if (suspend) {
1065 if (index >= 0) {
1066 desc = sessionEffects.valueAt(index);
1067 } else {
1068 desc = new SuspendedSessionDesc();
1069 if (type != NULL) {
1070 desc->mType = *type;
1071 }
1072 sessionEffects.add(key, desc);
1073 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1074 }
1075 desc->mRefCount++;
1076 } else {
1077 if (index < 0) {
1078 return;
1079 }
1080 desc = sessionEffects.valueAt(index);
1081 if (--desc->mRefCount == 0) {
1082 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1083 sessionEffects.removeItemsAt(index);
1084 if (sessionEffects.isEmpty()) {
1085 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1086 sessionId);
1087 mSuspendedSessions.removeItem(sessionId);
1088 }
1089 }
1090 }
1091 if (!sessionEffects.isEmpty()) {
1092 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1093 }
1094}
1095
1096void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1097 bool enabled,
1098 int sessionId)
1099{
1100 Mutex::Autolock _l(mLock);
1101 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1102}
1103
1104void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1105 bool enabled,
1106 int sessionId)
1107{
1108 if (mType != RECORD) {
1109 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1110 // another session. This gives the priority to well behaved effect control panels
1111 // and applications not using global effects.
1112 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1113 // global effects
1114 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
1115 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1116 }
1117 }
1118
1119 sp<EffectChain> chain = getEffectChain_l(sessionId);
1120 if (chain != 0) {
1121 chain->checkSuspendOnEffectEnabled(effect, enabled);
1122 }
1123}
1124
1125// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1126sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1127 const sp<AudioFlinger::Client>& client,
1128 const sp<IEffectClient>& effectClient,
1129 int32_t priority,
1130 int sessionId,
1131 effect_descriptor_t *desc,
1132 int *enabled,
Glenn Kasten9156ef32013-08-06 15:39:08 -07001133 status_t *status)
Eric Laurent81784c32012-11-19 14:55:58 -08001134{
1135 sp<EffectModule> effect;
1136 sp<EffectHandle> handle;
1137 status_t lStatus;
1138 sp<EffectChain> chain;
1139 bool chainCreated = false;
1140 bool effectCreated = false;
1141 bool effectRegistered = false;
1142
1143 lStatus = initCheck();
1144 if (lStatus != NO_ERROR) {
1145 ALOGW("createEffect_l() Audio driver not initialized.");
1146 goto Exit;
1147 }
1148
Andy Hung98ef9782014-03-04 14:46:50 -08001149 // Reject any effect on Direct output threads for now, since the format of
1150 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1151 if (mType == DIRECT) {
1152 ALOGW("createEffect_l() Cannot add effect %s on Direct output type thread %s",
Glenn Kastend7dca052015-03-05 16:05:54 -08001153 desc->name, mThreadName);
Andy Hung98ef9782014-03-04 14:46:50 -08001154 lStatus = BAD_VALUE;
1155 goto Exit;
1156 }
1157
Andy Hung389cfdb2014-08-07 17:49:53 -07001158 // Reject any effect on mixer or duplicating multichannel sinks.
Andy Hung9a592762014-07-21 21:56:01 -07001159 // TODO: fix both format and multichannel issues with effects.
Andy Hung389cfdb2014-08-07 17:49:53 -07001160 if ((mType == MIXER || mType == DUPLICATING) && mChannelCount != FCC_2) {
1161 ALOGW("createEffect_l() Cannot add effect %s for multichannel(%d) %s threads",
1162 desc->name, mChannelCount, mType == MIXER ? "MIXER" : "DUPLICATING");
Andy Hung9a592762014-07-21 21:56:01 -07001163 lStatus = BAD_VALUE;
1164 goto Exit;
1165 }
1166
Eric Laurent5baf2af2013-09-12 17:37:00 -07001167 // Allow global effects only on offloaded and mixer threads
1168 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1169 switch (mType) {
1170 case MIXER:
1171 case OFFLOAD:
1172 break;
1173 case DIRECT:
1174 case DUPLICATING:
1175 case RECORD:
1176 default:
Glenn Kastend7dca052015-03-05 16:05:54 -08001177 ALOGW("createEffect_l() Cannot add global effect %s on thread %s",
1178 desc->name, mThreadName);
Eric Laurent5baf2af2013-09-12 17:37:00 -07001179 lStatus = BAD_VALUE;
1180 goto Exit;
1181 }
Eric Laurent81784c32012-11-19 14:55:58 -08001182 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07001183
Eric Laurent81784c32012-11-19 14:55:58 -08001184 // Only Pre processor effects are allowed on input threads and only on input threads
1185 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
1186 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
1187 desc->name, desc->flags, mType);
1188 lStatus = BAD_VALUE;
1189 goto Exit;
1190 }
1191
1192 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1193
1194 { // scope for mLock
1195 Mutex::Autolock _l(mLock);
1196
1197 // check for existing effect chain with the requested audio session
1198 chain = getEffectChain_l(sessionId);
1199 if (chain == 0) {
1200 // create a new chain for this session
1201 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1202 chain = new EffectChain(this, sessionId);
1203 addEffectChain_l(chain);
1204 chain->setStrategy(getStrategyForSession_l(sessionId));
1205 chainCreated = true;
1206 } else {
1207 effect = chain->getEffectFromDesc_l(desc);
1208 }
1209
1210 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1211
1212 if (effect == 0) {
1213 int id = mAudioFlinger->nextUniqueId();
1214 // Check CPU and memory usage
1215 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
1216 if (lStatus != NO_ERROR) {
1217 goto Exit;
1218 }
1219 effectRegistered = true;
1220 // create a new effect module if none present in the chain
1221 effect = new EffectModule(this, chain, desc, id, sessionId);
1222 lStatus = effect->status();
1223 if (lStatus != NO_ERROR) {
1224 goto Exit;
1225 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07001226 effect->setOffloaded(mType == OFFLOAD, mId);
1227
Eric Laurent81784c32012-11-19 14:55:58 -08001228 lStatus = chain->addEffect_l(effect);
1229 if (lStatus != NO_ERROR) {
1230 goto Exit;
1231 }
1232 effectCreated = true;
1233
1234 effect->setDevice(mOutDevice);
1235 effect->setDevice(mInDevice);
1236 effect->setMode(mAudioFlinger->getMode());
1237 effect->setAudioSource(mAudioSource);
1238 }
1239 // create effect handle and connect it to effect module
1240 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001241 lStatus = handle->initCheck();
1242 if (lStatus == OK) {
1243 lStatus = effect->addHandle(handle.get());
1244 }
Eric Laurent81784c32012-11-19 14:55:58 -08001245 if (enabled != NULL) {
1246 *enabled = (int)effect->isEnabled();
1247 }
1248 }
1249
1250Exit:
1251 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1252 Mutex::Autolock _l(mLock);
1253 if (effectCreated) {
1254 chain->removeEffect_l(effect);
1255 }
1256 if (effectRegistered) {
1257 AudioSystem::unregisterEffect(effect->id());
1258 }
1259 if (chainCreated) {
1260 removeEffectChain_l(chain);
1261 }
1262 handle.clear();
1263 }
1264
Glenn Kasten9156ef32013-08-06 15:39:08 -07001265 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001266 return handle;
1267}
1268
1269sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
1270{
1271 Mutex::Autolock _l(mLock);
1272 return getEffect_l(sessionId, effectId);
1273}
1274
1275sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
1276{
1277 sp<EffectChain> chain = getEffectChain_l(sessionId);
1278 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1279}
1280
1281// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1282// PlaybackThread::mLock held
1283status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1284{
1285 // check for existing effect chain with the requested audio session
1286 int sessionId = effect->sessionId();
1287 sp<EffectChain> chain = getEffectChain_l(sessionId);
1288 bool chainCreated = false;
1289
Eric Laurent5baf2af2013-09-12 17:37:00 -07001290 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
1291 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
1292 this, effect->desc().name, effect->desc().flags);
1293
Eric Laurent81784c32012-11-19 14:55:58 -08001294 if (chain == 0) {
1295 // create a new chain for this session
1296 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1297 chain = new EffectChain(this, sessionId);
1298 addEffectChain_l(chain);
1299 chain->setStrategy(getStrategyForSession_l(sessionId));
1300 chainCreated = true;
1301 }
1302 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1303
1304 if (chain->getEffectFromId_l(effect->id()) != 0) {
1305 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1306 this, effect->desc().name, chain.get());
1307 return BAD_VALUE;
1308 }
1309
Eric Laurent5baf2af2013-09-12 17:37:00 -07001310 effect->setOffloaded(mType == OFFLOAD, mId);
1311
Eric Laurent81784c32012-11-19 14:55:58 -08001312 status_t status = chain->addEffect_l(effect);
1313 if (status != NO_ERROR) {
1314 if (chainCreated) {
1315 removeEffectChain_l(chain);
1316 }
1317 return status;
1318 }
1319
1320 effect->setDevice(mOutDevice);
1321 effect->setDevice(mInDevice);
1322 effect->setMode(mAudioFlinger->getMode());
1323 effect->setAudioSource(mAudioSource);
1324 return NO_ERROR;
1325}
1326
1327void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
1328
1329 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
1330 effect_descriptor_t desc = effect->desc();
1331 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1332 detachAuxEffect_l(effect->id());
1333 }
1334
1335 sp<EffectChain> chain = effect->chain().promote();
1336 if (chain != 0) {
1337 // remove effect chain if removing last effect
1338 if (chain->removeEffect_l(effect) == 0) {
1339 removeEffectChain_l(chain);
1340 }
1341 } else {
1342 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1343 }
1344}
1345
1346void AudioFlinger::ThreadBase::lockEffectChains_l(
1347 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1348{
1349 effectChains = mEffectChains;
1350 for (size_t i = 0; i < mEffectChains.size(); i++) {
1351 mEffectChains[i]->lock();
1352 }
1353}
1354
1355void AudioFlinger::ThreadBase::unlockEffectChains(
1356 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1357{
1358 for (size_t i = 0; i < effectChains.size(); i++) {
1359 effectChains[i]->unlock();
1360 }
1361}
1362
1363sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
1364{
1365 Mutex::Autolock _l(mLock);
1366 return getEffectChain_l(sessionId);
1367}
1368
1369sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const
1370{
1371 size_t size = mEffectChains.size();
1372 for (size_t i = 0; i < size; i++) {
1373 if (mEffectChains[i]->sessionId() == sessionId) {
1374 return mEffectChains[i];
1375 }
1376 }
1377 return 0;
1378}
1379
1380void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1381{
1382 Mutex::Autolock _l(mLock);
1383 size_t size = mEffectChains.size();
1384 for (size_t i = 0; i < size; i++) {
1385 mEffectChains[i]->setMode_l(mode);
1386 }
1387}
1388
Eric Laurent83b88082014-06-20 18:31:16 -07001389void AudioFlinger::ThreadBase::getAudioPortConfig(struct audio_port_config *config)
1390{
1391 config->type = AUDIO_PORT_TYPE_MIX;
1392 config->ext.mix.handle = mId;
1393 config->sample_rate = mSampleRate;
1394 config->format = mFormat;
1395 config->channel_mask = mChannelMask;
1396 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1397 AUDIO_PORT_CONFIG_FORMAT;
1398}
1399
Eric Laurent72e3f392015-05-20 14:43:50 -07001400void AudioFlinger::ThreadBase::systemReady()
1401{
1402 Mutex::Autolock _l(mLock);
1403 if (mSystemReady) {
1404 return;
1405 }
1406 mSystemReady = true;
1407
1408 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1409 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1410 }
1411 mPendingConfigEvents.clear();
1412}
1413
Eric Laurent83b88082014-06-20 18:31:16 -07001414
Eric Laurent81784c32012-11-19 14:55:58 -08001415// ----------------------------------------------------------------------------
1416// Playback
1417// ----------------------------------------------------------------------------
1418
1419AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1420 AudioStreamOut* output,
1421 audio_io_handle_t id,
1422 audio_devices_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07001423 type_t type,
1424 bool systemReady)
1425 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type, systemReady),
Andy Hung2098f272014-02-27 14:00:06 -08001426 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001427 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001428 mMixerBuffer(NULL),
1429 mMixerBufferSize(0),
1430 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1431 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001432 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001433 mEffectBuffer(NULL),
1434 mEffectBufferSize(0),
1435 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1436 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001437 mSuspended(0), mBytesWritten(0),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001438 mActiveTracksGeneration(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001439 // mStreamTypes[] initialized in constructor body
1440 mOutput(output),
1441 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
1442 mMixerStatus(MIXER_IDLE),
1443 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001444 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001445 mBytesRemaining(0),
1446 mCurrentWriteLength(0),
1447 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001448 mWriteAckSequence(0),
1449 mDrainSequence(0),
Eric Laurentede6c3b2013-09-19 14:37:46 -07001450 mSignalPending(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001451 mScreenState(AudioFlinger::mScreenState),
1452 // index 0 is reserved for normal mixer's submix
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001453 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1),
Eric Laurentd1f69b02014-12-15 14:33:13 -08001454 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001455 // mLatchD, mLatchQ,
1456 mLatchDValid(false), mLatchQValid(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001457{
Glenn Kastend7dca052015-03-05 16:05:54 -08001458 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1459 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001460
1461 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1462 // it would be safer to explicitly pass initial masterVolume/masterMute as
1463 // parameter.
1464 //
1465 // If the HAL we are using has support for master volume or master mute,
1466 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1467 // and the mute set to false).
1468 mMasterVolume = audioFlinger->masterVolume_l();
1469 mMasterMute = audioFlinger->masterMute_l();
1470 if (mOutput && mOutput->audioHwDev) {
1471 if (mOutput->audioHwDev->canSetMasterVolume()) {
1472 mMasterVolume = 1.0;
1473 }
1474
1475 if (mOutput->audioHwDev->canSetMasterMute()) {
1476 mMasterMute = false;
1477 }
1478 }
1479
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001480 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001481
Eric Laurent223fd5c2014-11-11 13:43:36 -08001482 // ++ operator does not compile
Glenn Kasten66e46352014-01-16 17:44:23 -08001483 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001484 stream = (audio_stream_type_t) (stream + 1)) {
1485 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1486 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1487 }
Eric Laurent81784c32012-11-19 14:55:58 -08001488}
1489
1490AudioFlinger::PlaybackThread::~PlaybackThread()
1491{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001492 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001493 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001494 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001495 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001496}
1497
1498void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1499{
1500 dumpInternals(fd, args);
1501 dumpTracks(fd, args);
1502 dumpEffectChains(fd, args);
1503}
1504
Glenn Kasten0f11b512014-01-31 16:18:54 -08001505void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001506{
1507 const size_t SIZE = 256;
1508 char buffer[SIZE];
1509 String8 result;
1510
Marco Nelissenb2208842014-02-07 14:00:50 -08001511 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001512 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1513 const stream_type_t *st = &mStreamTypes[i];
1514 if (i > 0) {
1515 result.appendFormat(", ");
1516 }
1517 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1518 if (st->mute) {
1519 result.append("M");
1520 }
1521 }
1522 result.append("\n");
1523 write(fd, result.string(), result.length());
1524 result.clear();
1525
Eric Laurent81784c32012-11-19 14:55:58 -08001526 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1527 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001528 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001529 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001530
1531 size_t numtracks = mTracks.size();
1532 size_t numactive = mActiveTracks.size();
Elliott Hughes87cebad2014-05-22 10:14:43 -07001533 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001534 size_t numactiveseen = 0;
1535 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07001536 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08001537 Track::appendDumpHeader(result);
1538 for (size_t i = 0; i < numtracks; ++i) {
1539 sp<Track> track = mTracks[i];
1540 if (track != 0) {
1541 bool active = mActiveTracks.indexOf(track) >= 0;
1542 if (active) {
1543 numactiveseen++;
1544 }
1545 track->dump(buffer, SIZE, active);
1546 result.append(buffer);
1547 }
1548 }
1549 } else {
1550 result.append("\n");
1551 }
1552 if (numactiveseen != numactive) {
1553 // some tracks in the active list were not in the tracks list
1554 snprintf(buffer, SIZE, " The following tracks are in the active list but"
1555 " not in the track list\n");
1556 result.append(buffer);
1557 Track::appendDumpHeader(result);
1558 for (size_t i = 0; i < numactive; ++i) {
1559 sp<Track> track = mActiveTracks[i].promote();
1560 if (track != 0 && mTracks.indexOf(track) < 0) {
1561 track->dump(buffer, SIZE, true);
1562 result.append(buffer);
1563 }
1564 }
1565 }
1566
1567 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001568}
1569
1570void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1571{
Glenn Kasten97b7b752014-09-28 13:04:24 -07001572 dprintf(fd, "\nOutput thread %p type %d (%s):\n", this, type(), threadTypeToString(type()));
Glenn Kasten44182c22015-03-05 17:12:23 -08001573
1574 dumpBase(fd, args);
1575
Elliott Hughes87cebad2014-05-22 10:14:43 -07001576 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
1577 dprintf(fd, " Last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1578 dprintf(fd, " Total writes: %d\n", mNumWrites);
1579 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1580 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1581 dprintf(fd, " Suspend count: %d\n", mSuspended);
1582 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1583 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1584 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1585 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001586 AudioStreamOut *output = mOutput;
1587 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
1588 String8 flagsAsString = outputFlagsToString(flags);
1589 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n", output, flags, flagsAsString.string());
Eric Laurent81784c32012-11-19 14:55:58 -08001590}
1591
1592// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001593
1594void AudioFlinger::PlaybackThread::onFirstRef()
1595{
Glenn Kastend7dca052015-03-05 16:05:54 -08001596 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001597}
1598
1599// ThreadBase virtuals
1600void AudioFlinger::PlaybackThread::preExit()
1601{
1602 ALOGV(" preExit()");
1603 // FIXME this is using hard-coded strings but in the future, this functionality will be
1604 // converted to use audio HAL extensions required to support tunneling
1605 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1606}
1607
1608// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1609sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1610 const sp<AudioFlinger::Client>& client,
1611 audio_stream_type_t streamType,
1612 uint32_t sampleRate,
1613 audio_format_t format,
1614 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001615 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001616 const sp<IMemory>& sharedBuffer,
1617 int sessionId,
1618 IAudioFlinger::track_flags_t *flags,
1619 pid_t tid,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001620 int uid,
Eric Laurent81784c32012-11-19 14:55:58 -08001621 status_t *status)
1622{
Glenn Kasten74935e42013-12-19 08:56:45 -08001623 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001624 sp<Track> track;
1625 status_t lStatus;
1626
1627 bool isTimed = (*flags & IAudioFlinger::TRACK_TIMED) != 0;
1628
1629 // client expresses a preference for FAST, but we get the final say
1630 if (*flags & IAudioFlinger::TRACK_FAST) {
1631 if (
1632 // not timed
1633 (!isTimed) &&
1634 // either of these use cases:
1635 (
1636 // use case 1: shared buffer with any frame count
1637 (
1638 (sharedBuffer != 0)
1639 ) ||
Glenn Kasten1dfe2f92015-03-09 12:03:14 -07001640 // use case 2: frame count is default or at least as large as HAL
Eric Laurent81784c32012-11-19 14:55:58 -08001641 (
Glenn Kasten1dfe2f92015-03-09 12:03:14 -07001642 // we formerly checked for a callback handler (non-0 tid),
1643 // but that is no longer required for TRANSFER_OBTAIN mode
Eric Laurent81784c32012-11-19 14:55:58 -08001644 ((frameCount == 0) ||
Glenn Kastenb5fed682013-12-03 09:06:43 -08001645 (frameCount >= mFrameCount))
Eric Laurent81784c32012-11-19 14:55:58 -08001646 )
1647 ) &&
1648 // PCM data
1649 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07001650 // TODO: extract as a data library function that checks that a computationally
1651 // expensive downmixer is not required: isFastOutputChannelConversion()
Andy Hung9a592762014-07-21 21:56:01 -07001652 (channelMask == mChannelMask ||
Andy Hung1f439e12015-05-19 12:57:41 -07001653 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
1654 (channelMask == AUDIO_CHANNEL_OUT_MONO
1655 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001656 // hardware sample rate
1657 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001658 // normal mixer has an associated fast mixer
1659 hasFastMixer() &&
1660 // there are sufficient fast track slots available
1661 (mFastTrackAvailMask != 0)
1662 // FIXME test that MixerThread for this fast track has a capable output HAL
1663 // FIXME add a permission test also?
1664 ) {
1665 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1666 if (frameCount == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001667 // read the fast track multiplier property the first time it is needed
1668 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1669 if (ok != 0) {
1670 ALOGE("%s pthread_once failed: %d", __func__, ok);
1671 }
1672 frameCount = mFrameCount * sFastTrackMultiplier;
Eric Laurent81784c32012-11-19 14:55:58 -08001673 }
1674 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
1675 frameCount, mFrameCount);
1676 } else {
1677 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
Andy Hung6146c082014-03-18 11:56:15 -07001678 "mFrameCount=%d format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
1679 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001680 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Andy Hung6146c082014-03-18 11:56:15 -07001681 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001682 audio_is_linear_pcm(format),
1683 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
1684 *flags &= ~IAudioFlinger::TRACK_FAST;
Andy Hung0e48d252015-01-26 11:43:15 -08001685 }
1686 }
1687 // For normal PCM streaming tracks, update minimum frame count.
1688 // For compatibility with AudioTrack calculation, buffer depth is forced
1689 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1690 // This is probably too conservative, but legacy application code may depend on it.
1691 // If you change this calculation, also review the start threshold which is related.
1692 if (!(*flags & IAudioFlinger::TRACK_FAST)
1693 && audio_is_linear_pcm(format) && sharedBuffer == 0) {
Andy Hung8edb8dc2015-03-26 19:13:55 -07001694 // this must match AudioTrack.cpp calculateMinFrameCount().
1695 // TODO: Move to a common library
Eric Laurent81784c32012-11-19 14:55:58 -08001696 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1697 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1698 if (minBufCount < 2) {
1699 minBufCount = 2;
1700 }
Andy Hung8edb8dc2015-03-26 19:13:55 -07001701 // For normal mixing tracks, if speed is > 1.0f (normal), AudioTrack
1702 // or the client should compute and pass in a larger buffer request.
Andy Hung0e48d252015-01-26 11:43:15 -08001703 size_t minFrameCount =
Andy Hung8edb8dc2015-03-26 19:13:55 -07001704 minBufCount * sourceFramesNeededWithTimestretch(
1705 sampleRate, mNormalFrameCount,
1706 mSampleRate, AUDIO_TIMESTRETCH_SPEED_NORMAL /*speed*/);
Andy Hung0e48d252015-01-26 11:43:15 -08001707 if (frameCount < minFrameCount) { // including frameCount == 0
Eric Laurent81784c32012-11-19 14:55:58 -08001708 frameCount = minFrameCount;
1709 }
Eric Laurent81784c32012-11-19 14:55:58 -08001710 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001711 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001712
Glenn Kastenc3df8382014-03-13 15:05:25 -07001713 switch (mType) {
1714
1715 case DIRECT:
Glenn Kasten993fa062014-05-02 11:14:34 -07001716 if (audio_is_linear_pcm(format)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001717 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001718 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1719 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001720 sampleRate, format, channelMask, mOutput, mFormat);
1721 lStatus = BAD_VALUE;
1722 goto Exit;
1723 }
1724 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001725 break;
1726
1727 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001728 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001729 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1730 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001731 sampleRate, format, channelMask, mOutput, mFormat);
1732 lStatus = BAD_VALUE;
1733 goto Exit;
1734 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001735 break;
1736
1737 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07001738 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001739 ALOGE("createTrack_l() Bad parameter: format %#x \""
1740 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001741 format, mOutput, mFormat);
1742 lStatus = BAD_VALUE;
1743 goto Exit;
1744 }
Andy Hungcd044842014-08-07 11:04:34 -07001745 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08001746 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1747 lStatus = BAD_VALUE;
1748 goto Exit;
1749 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001750 break;
1751
Eric Laurent81784c32012-11-19 14:55:58 -08001752 }
1753
1754 lStatus = initCheck();
1755 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07001756 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08001757 goto Exit;
1758 }
1759
1760 { // scope for mLock
1761 Mutex::Autolock _l(mLock);
1762
1763 // all tracks in same audio session must share the same routing strategy otherwise
1764 // conflicts will happen when tracks are moved from one output to another by audio policy
1765 // manager
1766 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1767 for (size_t i = 0; i < mTracks.size(); ++i) {
1768 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07001769 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001770 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1771 if (sessionId == t->sessionId() && strategy != actual) {
1772 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1773 strategy, actual);
1774 lStatus = BAD_VALUE;
1775 goto Exit;
1776 }
1777 }
1778 }
1779
1780 if (!isTimed) {
1781 track = new Track(this, client, streamType, sampleRate, format,
Eric Laurent83b88082014-06-20 18:31:16 -07001782 channelMask, frameCount, NULL, sharedBuffer,
1783 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08001784 } else {
1785 track = TimedTrack::create(this, client, streamType, sampleRate, format,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001786 channelMask, frameCount, sharedBuffer, sessionId, uid);
Eric Laurent81784c32012-11-19 14:55:58 -08001787 }
Glenn Kasten03003332013-08-06 15:40:54 -07001788
1789 // new Track always returns non-NULL,
1790 // but TimedTrack::create() is a factory that could fail by returning NULL
1791 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
1792 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08001793 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001794 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08001795 goto Exit;
1796 }
1797 mTracks.add(track);
1798
1799 sp<EffectChain> chain = getEffectChain_l(sessionId);
1800 if (chain != 0) {
1801 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1802 track->setMainBuffer(chain->inBuffer());
1803 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1804 chain->incTrackCnt();
1805 }
1806
1807 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1808 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1809 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1810 // so ask activity manager to do this on our behalf
1811 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1812 }
1813 }
1814
1815 lStatus = NO_ERROR;
1816
1817Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001818 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001819 return track;
1820}
1821
1822uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1823{
1824 return latency;
1825}
1826
1827uint32_t AudioFlinger::PlaybackThread::latency() const
1828{
1829 Mutex::Autolock _l(mLock);
1830 return latency_l();
1831}
1832uint32_t AudioFlinger::PlaybackThread::latency_l() const
1833{
1834 if (initCheck() == NO_ERROR) {
1835 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
1836 } else {
1837 return 0;
1838 }
1839}
1840
1841void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1842{
1843 Mutex::Autolock _l(mLock);
1844 // Don't apply master volume in SW if our HAL can do it for us.
1845 if (mOutput && mOutput->audioHwDev &&
1846 mOutput->audioHwDev->canSetMasterVolume()) {
1847 mMasterVolume = 1.0;
1848 } else {
1849 mMasterVolume = value;
1850 }
1851}
1852
1853void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1854{
1855 Mutex::Autolock _l(mLock);
1856 // Don't apply master mute in SW if our HAL can do it for us.
1857 if (mOutput && mOutput->audioHwDev &&
1858 mOutput->audioHwDev->canSetMasterMute()) {
1859 mMasterMute = false;
1860 } else {
1861 mMasterMute = muted;
1862 }
1863}
1864
1865void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
1866{
1867 Mutex::Autolock _l(mLock);
1868 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001869 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001870}
1871
1872void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
1873{
1874 Mutex::Autolock _l(mLock);
1875 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001876 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001877}
1878
1879float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
1880{
1881 Mutex::Autolock _l(mLock);
1882 return mStreamTypes[stream].volume;
1883}
1884
1885// addTrack_l() must be called with ThreadBase::mLock held
1886status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1887{
1888 status_t status = ALREADY_EXISTS;
1889
1890 // set retry count for buffer fill
1891 track->mRetryCount = kMaxTrackStartupRetries;
1892 if (mActiveTracks.indexOf(track) < 0) {
1893 // the track is newly added, make sure it fills up all its
1894 // buffers before playing. This is to ensure the client will
1895 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07001896 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001897 TrackBase::track_state state = track->mState;
1898 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08001899 status = AudioSystem::startOutput(mId, track->streamType(),
1900 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001901 mLock.lock();
1902 // abort track was stopped/paused while we released the lock
1903 if (state != track->mState) {
1904 if (status == NO_ERROR) {
1905 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08001906 AudioSystem::stopOutput(mId, track->streamType(),
1907 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001908 mLock.lock();
1909 }
1910 return INVALID_OPERATION;
1911 }
1912 // abort if start is rejected by audio policy manager
1913 if (status != NO_ERROR) {
1914 return PERMISSION_DENIED;
1915 }
1916#ifdef ADD_BATTERY_DATA
1917 // to track the speaker usage
1918 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
1919#endif
1920 }
1921
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001922 track->mFillingUpStatus = track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent81784c32012-11-19 14:55:58 -08001923 track->mResetDone = false;
1924 track->mPresentationCompleteFrames = 0;
1925 mActiveTracks.add(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001926 mWakeLockUids.add(track->uid());
1927 mActiveTracksGeneration++;
Eric Laurentfd477972013-10-25 18:10:40 -07001928 mLatestActiveTrack = track;
Eric Laurentd0107bc2013-06-11 14:38:48 -07001929 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1930 if (chain != 0) {
1931 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
1932 track->sessionId());
1933 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08001934 }
1935
1936 status = NO_ERROR;
1937 }
1938
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08001939 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001940 return status;
1941}
1942
Eric Laurentbfb1b832013-01-07 09:53:42 -08001943bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08001944{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001945 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08001946 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001947 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
1948 track->mState = TrackBase::STOPPED;
1949 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08001950 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07001951 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001952 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08001953 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001954
1955 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08001956}
1957
1958void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1959{
1960 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
1961 mTracks.remove(track);
1962 deleteTrackName_l(track->name());
1963 // redundant as track is about to be destroyed, for dumpsys only
1964 track->mName = -1;
1965 if (track->isFastTrack()) {
1966 int index = track->mFastIndex;
1967 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
1968 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1969 mFastTrackAvailMask |= 1 << index;
1970 // redundant as track is about to be destroyed, for dumpsys only
1971 track->mFastIndex = -1;
1972 }
1973 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1974 if (chain != 0) {
1975 chain->decTrackCnt();
1976 }
1977}
1978
Eric Laurentede6c3b2013-09-19 14:37:46 -07001979void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001980{
1981 // Thread could be blocked waiting for async
1982 // so signal it to handle state changes immediately
1983 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1984 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1985 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001986 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001987}
1988
Eric Laurent81784c32012-11-19 14:55:58 -08001989String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1990{
Eric Laurent81784c32012-11-19 14:55:58 -08001991 Mutex::Autolock _l(mLock);
1992 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07001993 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08001994 }
1995
Glenn Kastend8ea6992013-07-16 14:17:15 -07001996 char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
1997 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08001998 free(s);
1999 return out_s8;
2000}
2001
Eric Laurent73e26b62015-04-27 16:55:58 -07002002void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event) {
2003 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2004 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002005
Eric Laurent73e26b62015-04-27 16:55:58 -07002006 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002007
2008 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002009 case AUDIO_OUTPUT_OPENED:
2010 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002011 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002012 desc->mChannelMask = mChannelMask;
2013 desc->mSamplingRate = mSampleRate;
2014 desc->mFormat = mFormat;
2015 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002016 // AudioFlinger::frameCount(audio_io_handle_t)
Eric Laurent73e26b62015-04-27 16:55:58 -07002017 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002018 break;
2019
Eric Laurent73e26b62015-04-27 16:55:58 -07002020 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002021 default:
2022 break;
2023 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002024 mAudioFlinger->ioConfigChanged(event, desc);
Eric Laurent81784c32012-11-19 14:55:58 -08002025}
2026
Eric Laurentbfb1b832013-01-07 09:53:42 -08002027void AudioFlinger::PlaybackThread::writeCallback()
2028{
2029 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002030 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002031}
2032
2033void AudioFlinger::PlaybackThread::drainCallback()
2034{
2035 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002036 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002037}
2038
Eric Laurent3b4529e2013-09-05 18:09:19 -07002039void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002040{
2041 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002042 // reject out of sequence requests
2043 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2044 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002045 mWaitWorkCV.signal();
2046 }
2047}
2048
Eric Laurent3b4529e2013-09-05 18:09:19 -07002049void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002050{
2051 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002052 // reject out of sequence requests
2053 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
2054 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002055 mWaitWorkCV.signal();
2056 }
2057}
2058
2059// static
2060int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
Glenn Kasten0f11b512014-01-31 16:18:54 -08002061 void *param __unused,
Eric Laurentbfb1b832013-01-07 09:53:42 -08002062 void *cookie)
2063{
2064 AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
2065 ALOGV("asyncCallback() event %d", event);
2066 switch (event) {
2067 case STREAM_CBK_EVENT_WRITE_READY:
2068 me->writeCallback();
2069 break;
2070 case STREAM_CBK_EVENT_DRAIN_READY:
2071 me->drainCallback();
2072 break;
2073 default:
2074 ALOGW("asyncCallback() unknown event %d", event);
2075 break;
2076 }
2077 return 0;
2078}
2079
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002080void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002081{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002082 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Eric Laurent81784c32012-11-19 14:55:58 -08002083 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
2084 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002085 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002086 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002087 }
Andy Hung9a592762014-07-21 21:56:01 -07002088 if ((mType == MIXER || mType == DUPLICATING)
2089 && !isValidPcmSinkChannelMask(mChannelMask)) {
2090 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2091 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002092 }
Andy Hunge5412692014-05-16 11:25:07 -07002093 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Andy Hung463be252014-07-10 16:56:07 -07002094 mHALFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
2095 mFormat = mHALFormat;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002096 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002097 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002098 }
Andy Hung6146c082014-03-18 11:56:15 -07002099 if ((mType == MIXER || mType == DUPLICATING)
2100 && !isValidPcmSinkFormat(mFormat)) {
2101 LOG_FATAL("HAL format %#x not supported for mixed output",
2102 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002103 }
Phil Burk062e67a2015-02-11 13:40:50 -08002104 mFrameSize = mOutput->getFrameSize();
Glenn Kasten70949c42013-08-06 07:40:12 -07002105 mBufferSize = mOutput->stream->common.get_buffer_size(&mOutput->stream->common);
2106 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002107 if (mFrameCount & 15) {
2108 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
2109 mFrameCount);
2110 }
2111
Eric Laurentbfb1b832013-01-07 09:53:42 -08002112 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
2113 (mOutput->stream->set_callback != NULL)) {
2114 if (mOutput->stream->set_callback(mOutput->stream,
2115 AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
2116 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002117 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002118 }
2119 }
2120
Eric Laurentd1f69b02014-12-15 14:33:13 -08002121 mHwSupportsPause = false;
2122 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
2123 if (mOutput->stream->pause != NULL) {
2124 if (mOutput->stream->resume != NULL) {
2125 mHwSupportsPause = true;
2126 } else {
2127 ALOGW("direct output implements pause but not resume");
2128 }
2129 } else if (mOutput->stream->resume != NULL) {
2130 ALOGW("direct output implements resume but not pause");
2131 }
2132 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002133 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2134 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2135 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002136
Andy Hungfbfc3952015-01-15 13:33:51 -08002137 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2138 // For best precision, we use float instead of the associated output
2139 // device format (typically PCM 16 bit).
2140
2141 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2142 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2143 mBufferSize = mFrameSize * mFrameCount;
2144
2145 // TODO: We currently use the associated output device channel mask and sample rate.
2146 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2147 // (if a valid mask) to avoid premature downmix.
2148 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2149 // instead of the output device sample rate to avoid loss of high frequency information.
2150 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2151 }
2152
Andy Hung09a50072014-02-27 14:30:47 -08002153 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002154 double multiplier = 1.0;
2155 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2156 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002157 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2158 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Eric Laurent81784c32012-11-19 14:55:58 -08002159 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2160 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2161 maxNormalFrameCount = maxNormalFrameCount & ~15;
2162 if (maxNormalFrameCount < minNormalFrameCount) {
2163 maxNormalFrameCount = minNormalFrameCount;
2164 }
2165 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2166 if (multiplier <= 1.0) {
2167 multiplier = 1.0;
2168 } else if (multiplier <= 2.0) {
2169 if (2 * mFrameCount <= maxNormalFrameCount) {
2170 multiplier = 2.0;
2171 } else {
2172 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2173 }
2174 } else {
2175 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
Andy Hung09a50072014-02-27 14:30:47 -08002176 // SRC (it would be unusual for the normal sink buffer size to not be a multiple of fast
Eric Laurent81784c32012-11-19 14:55:58 -08002177 // track, but we sometimes have to do this to satisfy the maximum frame count
2178 // constraint)
2179 // FIXME this rounding up should not be done if no HAL SRC
2180 uint32_t truncMult = (uint32_t) multiplier;
2181 if ((truncMult & 1)) {
2182 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
2183 ++truncMult;
2184 }
2185 }
2186 multiplier = (double) truncMult;
2187 }
2188 }
2189 mNormalFrameCount = multiplier * mFrameCount;
2190 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002191 if (mType == MIXER || mType == DUPLICATING) {
2192 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2193 }
Andy Hung09a50072014-02-27 14:30:47 -08002194 ALOGI("HAL output buffer size %u frames, normal sink buffer size %u frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002195 mNormalFrameCount);
2196
Andy Hung08fb1742015-05-31 23:22:10 -07002197 // Check if we want to throttle the processing to no more than 2x normal rate
2198 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002199 mThreadThrottleTimeMs = 0;
2200 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002201 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2202
Andy Hung010a1a12014-03-13 13:57:33 -07002203 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2204 // Originally this was int16_t[] array, need to remove legacy implications.
2205 free(mSinkBuffer);
2206 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002207 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2208 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2209 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002210 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002211
Andy Hung69aed5f2014-02-25 17:24:40 -08002212 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2213 // drives the output.
2214 free(mMixerBuffer);
2215 mMixerBuffer = NULL;
2216 if (mMixerBufferEnabled) {
2217 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2218 mMixerBufferSize = mNormalFrameCount * mChannelCount
2219 * audio_bytes_per_sample(mMixerBufferFormat);
2220 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2221 }
Andy Hung98ef9782014-03-04 14:46:50 -08002222 free(mEffectBuffer);
2223 mEffectBuffer = NULL;
2224 if (mEffectBufferEnabled) {
2225 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
2226 mEffectBufferSize = mNormalFrameCount * mChannelCount
2227 * audio_bytes_per_sample(mEffectBufferFormat);
2228 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2229 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002230
Eric Laurent81784c32012-11-19 14:55:58 -08002231 // force reconfiguration of effect chains and engines to take new buffer size and audio
2232 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002233 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002234 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2235 // matter.
2236 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2237 Vector< sp<EffectChain> > effectChains = mEffectChains;
2238 for (size_t i = 0; i < effectChains.size(); i ++) {
2239 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2240 }
2241}
2242
2243
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002244status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002245{
2246 if (halFrames == NULL || dspFrames == NULL) {
2247 return BAD_VALUE;
2248 }
2249 Mutex::Autolock _l(mLock);
2250 if (initCheck() != NO_ERROR) {
2251 return INVALID_OPERATION;
2252 }
2253 size_t framesWritten = mBytesWritten / mFrameSize;
2254 *halFrames = framesWritten;
2255
2256 if (isSuspended()) {
2257 // return an estimation of rendered frames when the output is suspended
2258 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
2259 *dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0;
2260 return NO_ERROR;
2261 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002262 status_t status;
2263 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002264 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002265 *dspFrames = (size_t)frames;
2266 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002267 }
2268}
2269
2270uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
2271{
2272 Mutex::Autolock _l(mLock);
2273 uint32_t result = 0;
2274 if (getEffectChain_l(sessionId) != 0) {
2275 result = EFFECT_SESSION;
2276 }
2277
2278 for (size_t i = 0; i < mTracks.size(); ++i) {
2279 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002280 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002281 result |= TRACK_SESSION;
2282 break;
2283 }
2284 }
2285
2286 return result;
2287}
2288
2289uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
2290{
2291 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2292 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2293 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2294 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2295 }
2296 for (size_t i = 0; i < mTracks.size(); i++) {
2297 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002298 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002299 return AudioSystem::getStrategyForStream(track->streamType());
2300 }
2301 }
2302 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2303}
2304
2305
Phil Burk062e67a2015-02-11 13:40:50 -08002306AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002307{
2308 Mutex::Autolock _l(mLock);
2309 return mOutput;
2310}
2311
Phil Burk062e67a2015-02-11 13:40:50 -08002312AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002313{
2314 Mutex::Autolock _l(mLock);
2315 AudioStreamOut *output = mOutput;
2316 mOutput = NULL;
2317 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2318 // must push a NULL and wait for ack
2319 mOutputSink.clear();
2320 mPipeSink.clear();
2321 mNormalSink.clear();
2322 return output;
2323}
2324
2325// this method must always be called either with ThreadBase mLock held or inside the thread loop
2326audio_stream_t* AudioFlinger::PlaybackThread::stream() const
2327{
2328 if (mOutput == NULL) {
2329 return NULL;
2330 }
2331 return &mOutput->stream->common;
2332}
2333
2334uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2335{
2336 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2337}
2338
2339status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2340{
2341 if (!isValidSyncEvent(event)) {
2342 return BAD_VALUE;
2343 }
2344
2345 Mutex::Autolock _l(mLock);
2346
2347 for (size_t i = 0; i < mTracks.size(); ++i) {
2348 sp<Track> track = mTracks[i];
2349 if (event->triggerSession() == track->sessionId()) {
2350 (void) track->setSyncEvent(event);
2351 return NO_ERROR;
2352 }
2353 }
2354
2355 return NAME_NOT_FOUND;
2356}
2357
2358bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2359{
2360 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2361}
2362
2363void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2364 const Vector< sp<Track> >& tracksToRemove)
2365{
2366 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002367 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002368 for (size_t i = 0 ; i < count ; i++) {
2369 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002370 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002371 AudioSystem::stopOutput(mId, track->streamType(),
2372 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002373#ifdef ADD_BATTERY_DATA
2374 // to track the speaker usage
2375 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2376#endif
2377 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002378 AudioSystem::releaseOutput(mId, track->streamType(),
2379 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002380 }
Eric Laurent81784c32012-11-19 14:55:58 -08002381 }
2382 }
2383 }
Eric Laurent81784c32012-11-19 14:55:58 -08002384}
2385
2386void AudioFlinger::PlaybackThread::checkSilentMode_l()
2387{
2388 if (!mMasterMute) {
2389 char value[PROPERTY_VALUE_MAX];
2390 if (property_get("ro.audio.silent", value, "0") > 0) {
2391 char *endptr;
2392 unsigned long ul = strtoul(value, &endptr, 0);
2393 if (*endptr == '\0' && ul != 0) {
2394 ALOGD("Silence is golden");
2395 // The setprop command will not allow a property to be changed after
2396 // the first time it is set, so we don't have to worry about un-muting.
2397 setMasterMute_l(true);
2398 }
2399 }
2400 }
2401}
2402
2403// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002404ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002405{
2406 // FIXME rewrite to reduce number of system calls
2407 mLastWriteTime = systemTime();
2408 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002409 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002410 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002411
2412 // If an NBAIO sink is present, use it to write the normal mixer's submix
2413 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002414
Andy Hung010a1a12014-03-13 13:57:33 -07002415 const size_t count = mBytesRemaining / mFrameSize;
2416
Simon Wilson2d590962012-11-29 15:18:50 -08002417 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002418 // update the setpoint when AudioFlinger::mScreenState changes
2419 uint32_t screenState = AudioFlinger::mScreenState;
2420 if (screenState != mScreenState) {
2421 mScreenState = screenState;
2422 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2423 if (pipe != NULL) {
2424 pipe->setAvgFrames((mScreenState & 1) ?
2425 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2426 }
2427 }
Andy Hung010a1a12014-03-13 13:57:33 -07002428 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002429 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002430 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002431 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002432 } else {
2433 bytesWritten = framesWritten;
2434 }
Glenn Kastenefaa7ab2014-08-20 08:48:54 -07002435 mLatchDValid = false;
Glenn Kasten767094d2013-08-23 13:51:43 -07002436 status_t status = mNormalSink->getTimestamp(mLatchD.mTimestamp);
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002437 if (status == NO_ERROR) {
2438 size_t totalFramesWritten = mNormalSink->framesWritten();
2439 if (totalFramesWritten >= mLatchD.mTimestamp.mPosition) {
2440 mLatchD.mUnpresentedFrames = totalFramesWritten - mLatchD.mTimestamp.mPosition;
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002441 // mLatchD.mFramesReleased is set immediately before D is clocked into Q
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002442 mLatchDValid = true;
2443 }
2444 }
Eric Laurent81784c32012-11-19 14:55:58 -08002445 // otherwise use the HAL / AudioStreamOut directly
2446 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002447 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002448
Eric Laurentbfb1b832013-01-07 09:53:42 -08002449 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002450 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2451 mWriteAckSequence += 2;
2452 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002453 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002454 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002455 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002456 // FIXME We should have an implementation of timestamps for direct output threads.
2457 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002458 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002459 if (mUseAsyncWrite &&
2460 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2461 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002462 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002463 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002464 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002465 }
Eric Laurent81784c32012-11-19 14:55:58 -08002466 }
2467
Eric Laurent81784c32012-11-19 14:55:58 -08002468 mNumWrites++;
2469 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002470 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002471 return bytesWritten;
2472}
2473
2474void AudioFlinger::PlaybackThread::threadLoop_drain()
2475{
2476 if (mOutput->stream->drain) {
2477 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2478 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002479 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2480 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002481 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002482 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002483 }
2484 mOutput->stream->drain(mOutput->stream,
2485 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
2486 : AUDIO_DRAIN_ALL);
2487 }
2488}
2489
2490void AudioFlinger::PlaybackThread::threadLoop_exit()
2491{
Eric Laurent275e8e92014-11-30 15:14:47 -08002492 {
2493 Mutex::Autolock _l(mLock);
2494 for (size_t i = 0; i < mTracks.size(); i++) {
2495 sp<Track> track = mTracks[i];
2496 track->invalidate();
2497 }
2498 }
Eric Laurent81784c32012-11-19 14:55:58 -08002499}
2500
2501/*
2502The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002503 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002504 - mActiveSleepTimeUs from activeSleepTimeUs()
2505 - mIdleSleepTimeUs from idleSleepTimeUs()
2506 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only)
Eric Laurent81784c32012-11-19 14:55:58 -08002507 - maxPeriod from frame count and sample rate (MIXER only)
2508
2509The parameters that affect these derived values are:
2510 - frame count
2511 - frame size
2512 - sample rate
2513 - device type: A2DP or not
2514 - device latency
2515 - format: PCM or not
2516 - active sleep time
2517 - idle sleep time
2518*/
2519
2520void AudioFlinger::PlaybackThread::cacheParameters_l()
2521{
Andy Hung25c2dac2014-02-27 14:56:00 -08002522 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002523 mActiveSleepTimeUs = activeSleepTimeUs();
2524 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent81784c32012-11-19 14:55:58 -08002525}
2526
2527void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2528{
Glenn Kasten7c027242012-12-26 14:43:16 -08002529 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurent81784c32012-11-19 14:55:58 -08002530 this, streamType, mTracks.size());
2531 Mutex::Autolock _l(mLock);
2532
2533 size_t size = mTracks.size();
2534 for (size_t i = 0; i < size; i++) {
2535 sp<Track> t = mTracks[i];
2536 if (t->streamType() == streamType) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002537 t->invalidate();
Eric Laurent81784c32012-11-19 14:55:58 -08002538 }
2539 }
2540}
2541
2542status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2543{
2544 int session = chain->sessionId();
Andy Hung010a1a12014-03-13 13:57:33 -07002545 int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled
2546 ? mEffectBuffer : mSinkBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002547 bool ownsBuffer = false;
2548
2549 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
2550 if (session > 0) {
2551 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002552 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002553 if (mType != DIRECT) {
2554 size_t numSamples = mNormalFrameCount * mChannelCount;
2555 buffer = new int16_t[numSamples];
2556 memset(buffer, 0, numSamples * sizeof(int16_t));
2557 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2558 ownsBuffer = true;
2559 }
2560
2561 // Attach all tracks with same session ID to this chain.
2562 for (size_t i = 0; i < mTracks.size(); ++i) {
2563 sp<Track> track = mTracks[i];
2564 if (session == track->sessionId()) {
2565 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2566 buffer);
2567 track->setMainBuffer(buffer);
2568 chain->incTrackCnt();
2569 }
2570 }
2571
2572 // indicate all active tracks in the chain
2573 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2574 sp<Track> track = mActiveTracks[i].promote();
2575 if (track == 0) {
2576 continue;
2577 }
2578 if (session == track->sessionId()) {
2579 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2580 chain->incActiveTrackCnt();
2581 }
2582 }
2583 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002584 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08002585 chain->setInBuffer(buffer, ownsBuffer);
Andy Hung010a1a12014-03-13 13:57:33 -07002586 chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled
2587 ? mEffectBuffer : mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002588 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
2589 // chains list in order to be processed last as it contains output stage effects
2590 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2591 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
2592 // after track specific effects and before output stage
2593 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
2594 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
2595 // Effect chain for other sessions are inserted at beginning of effect
2596 // chains list to be processed before output mix effects. Relative order between other
2597 // sessions is not important
2598 size_t size = mEffectChains.size();
2599 size_t i = 0;
2600 for (i = 0; i < size; i++) {
2601 if (mEffectChains[i]->sessionId() < session) {
2602 break;
2603 }
2604 }
2605 mEffectChains.insertAt(chain, i);
2606 checkSuspendOnAddEffectChain_l(chain);
2607
2608 return NO_ERROR;
2609}
2610
2611size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2612{
2613 int session = chain->sessionId();
2614
2615 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2616
2617 for (size_t i = 0; i < mEffectChains.size(); i++) {
2618 if (chain == mEffectChains[i]) {
2619 mEffectChains.removeAt(i);
2620 // detach all active tracks from the chain
2621 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2622 sp<Track> track = mActiveTracks[i].promote();
2623 if (track == 0) {
2624 continue;
2625 }
2626 if (session == track->sessionId()) {
2627 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2628 chain.get(), session);
2629 chain->decActiveTrackCnt();
2630 }
2631 }
2632
2633 // detach all tracks with same session ID from this chain
2634 for (size_t i = 0; i < mTracks.size(); ++i) {
2635 sp<Track> track = mTracks[i];
2636 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002637 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002638 chain->decTrackCnt();
2639 }
2640 }
2641 break;
2642 }
2643 }
2644 return mEffectChains.size();
2645}
2646
2647status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2648 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2649{
2650 Mutex::Autolock _l(mLock);
2651 return attachAuxEffect_l(track, EffectId);
2652}
2653
2654status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2655 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2656{
2657 status_t status = NO_ERROR;
2658
2659 if (EffectId == 0) {
2660 track->setAuxBuffer(0, NULL);
2661 } else {
2662 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2663 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2664 if (effect != 0) {
2665 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2666 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2667 } else {
2668 status = INVALID_OPERATION;
2669 }
2670 } else {
2671 status = BAD_VALUE;
2672 }
2673 }
2674 return status;
2675}
2676
2677void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2678{
2679 for (size_t i = 0; i < mTracks.size(); ++i) {
2680 sp<Track> track = mTracks[i];
2681 if (track->auxEffectId() == effectId) {
2682 attachAuxEffect_l(track, 0);
2683 }
2684 }
2685}
2686
2687bool AudioFlinger::PlaybackThread::threadLoop()
2688{
2689 Vector< sp<Track> > tracksToRemove;
2690
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002691 mStandbyTimeNs = systemTime();
Eric Laurent81784c32012-11-19 14:55:58 -08002692
2693 // MIXER
2694 nsecs_t lastWarning = 0;
2695
2696 // DUPLICATING
2697 // FIXME could this be made local to while loop?
2698 writeFrames = 0;
2699
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002700 int lastGeneration = 0;
2701
Eric Laurent81784c32012-11-19 14:55:58 -08002702 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002703 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08002704
2705 if (mType == MIXER) {
2706 sleepTimeShift = 0;
2707 }
2708
2709 CpuStats cpuStats;
2710 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2711
2712 acquireWakeLock();
2713
Glenn Kasten9e58b552013-01-18 15:09:48 -08002714 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2715 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2716 // and then that string will be logged at the next convenient opportunity.
2717 const char *logString = NULL;
2718
Eric Laurent664539d2013-09-23 18:24:31 -07002719 checkSilentMode_l();
2720
Eric Laurent81784c32012-11-19 14:55:58 -08002721 while (!exitPending())
2722 {
2723 cpuStats.sample(myName);
2724
2725 Vector< sp<EffectChain> > effectChains;
2726
Eric Laurent81784c32012-11-19 14:55:58 -08002727 { // scope for mLock
2728
2729 Mutex::Autolock _l(mLock);
2730
Eric Laurent021cf962014-05-13 10:18:14 -07002731 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07002732
Glenn Kasten9e58b552013-01-18 15:09:48 -08002733 if (logString != NULL) {
2734 mNBLogWriter->logTimestamp();
2735 mNBLogWriter->log(logString);
2736 logString = NULL;
2737 }
2738
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002739 // Gather the framesReleased counters for all active tracks,
2740 // and latch them atomically with the timestamp.
2741 // FIXME We're using raw pointers as indices. A unique track ID would be a better index.
2742 mLatchD.mFramesReleased.clear();
2743 size_t size = mActiveTracks.size();
2744 for (size_t i = 0; i < size; i++) {
2745 sp<Track> t = mActiveTracks[i].promote();
2746 if (t != 0) {
2747 mLatchD.mFramesReleased.add(t.get(),
2748 t->mAudioTrackServerProxy->framesReleased());
2749 }
2750 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002751 if (mLatchDValid) {
2752 mLatchQ = mLatchD;
2753 mLatchDValid = false;
2754 mLatchQValid = true;
2755 }
2756
Eric Laurent81784c32012-11-19 14:55:58 -08002757 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002758 if (mSignalPending) {
2759 // A signal was raised while we were unlocked
2760 mSignalPending = false;
2761 } else if (waitingAsyncCallback_l()) {
2762 if (exitPending()) {
2763 break;
2764 }
Marco Nelissen078538c2015-05-12 09:17:57 -07002765 bool released = false;
2766 // The following works around a bug in the offload driver. Ideally we would release
2767 // the wake lock every time, but that causes the last offload buffer(s) to be
2768 // dropped while the device is on battery, so we need to hold a wake lock during
2769 // the drain phase.
2770 if (mBytesRemaining && !(mDrainSequence & 1)) {
2771 releaseWakeLock_l();
2772 released = true;
2773 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002774 mWakeLockUids.clear();
2775 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002776 ALOGV("wait async completion");
2777 mWaitWorkCV.wait(mLock);
2778 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07002779 if (released) {
2780 acquireWakeLock_l();
2781 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002782 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
2783 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002784
2785 continue;
2786 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002787 if ((!mActiveTracks.size() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08002788 isSuspended()) {
2789 // put audio hardware into standby after short delay
2790 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002791
2792 threadLoop_standby();
2793
2794 mStandby = true;
2795 }
2796
2797 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2798 // we're about to wait, flush the binder command buffer
2799 IPCThreadState::self()->flushCommands();
2800
2801 clearOutputTracks();
2802
2803 if (exitPending()) {
2804 break;
2805 }
2806
2807 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002808 mWakeLockUids.clear();
2809 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002810 // wait until we have something to do...
2811 ALOGV("%s going to sleep", myName.string());
2812 mWaitWorkCV.wait(mLock);
2813 ALOGV("%s waking up", myName.string());
2814 acquireWakeLock_l();
2815
2816 mMixerStatus = MIXER_IDLE;
2817 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2818 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002819 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002820 checkSilentMode_l();
2821
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002822 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
2823 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08002824 if (mType == MIXER) {
2825 sleepTimeShift = 0;
2826 }
2827
2828 continue;
2829 }
2830 }
Eric Laurent81784c32012-11-19 14:55:58 -08002831 // mMixerStatusIgnoringFastTracks is also updated internally
2832 mMixerStatus = prepareTracks_l(&tracksToRemove);
2833
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002834 // compare with previously applied list
2835 if (lastGeneration != mActiveTracksGeneration) {
2836 // update wakelock
2837 updateWakeLockUids_l(mWakeLockUids);
2838 lastGeneration = mActiveTracksGeneration;
2839 }
2840
Eric Laurent81784c32012-11-19 14:55:58 -08002841 // prevent any changes in effect chain list and in each effect chain
2842 // during mixing and effect process as the audio buffers could be deleted
2843 // or modified if an effect is created or deleted
2844 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002845 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08002846
Eric Laurentbfb1b832013-01-07 09:53:42 -08002847 if (mBytesRemaining == 0) {
2848 mCurrentWriteLength = 0;
2849 if (mMixerStatus == MIXER_TRACKS_READY) {
2850 // threadLoop_mix() sets mCurrentWriteLength
2851 threadLoop_mix();
2852 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
2853 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002854 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08002855 // must be written to HAL
2856 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002857 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08002858 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002859 }
2860 }
Andy Hung98ef9782014-03-04 14:46:50 -08002861 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002862 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08002863 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
2864 // or mSinkBuffer (if there are no effects).
2865 //
2866 // This is done pre-effects computation; if effects change to
2867 // support higher precision, this needs to move.
2868 //
2869 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002870 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08002871 if (mMixerBufferValid) {
2872 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
2873 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
2874
2875 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
2876 mNormalFrameCount * mChannelCount);
2877 }
2878
Eric Laurentbfb1b832013-01-07 09:53:42 -08002879 mBytesRemaining = mCurrentWriteLength;
2880 if (isSuspended()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002881 mSleepTimeUs = suspendSleepTimeUs();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002882 // simulate write to HAL when suspended
Andy Hung25c2dac2014-02-27 14:56:00 -08002883 mBytesWritten += mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002884 mBytesRemaining = 0;
2885 }
Eric Laurent81784c32012-11-19 14:55:58 -08002886
Eric Laurentbfb1b832013-01-07 09:53:42 -08002887 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002888 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002889 for (size_t i = 0; i < effectChains.size(); i ++) {
2890 effectChains[i]->process_l();
2891 }
Eric Laurent81784c32012-11-19 14:55:58 -08002892 }
2893 }
Eric Laurent59fe0102013-09-27 18:48:26 -07002894 // Process effect chains for offloaded thread even if no audio
2895 // was read from audio track: process only updates effect state
2896 // and thus does have to be synchronized with audio writes but may have
2897 // to be called while waiting for async write callback
2898 if (mType == OFFLOAD) {
2899 for (size_t i = 0; i < effectChains.size(); i ++) {
2900 effectChains[i]->process_l();
2901 }
2902 }
Eric Laurent81784c32012-11-19 14:55:58 -08002903
Andy Hung98ef9782014-03-04 14:46:50 -08002904 // Only if the Effects buffer is enabled and there is data in the
2905 // Effects buffer (buffer valid), we need to
2906 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002907 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08002908 if (mEffectBufferValid) {
2909 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
2910 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
2911 mNormalFrameCount * mChannelCount);
2912 }
2913
Eric Laurent81784c32012-11-19 14:55:58 -08002914 // enable changes in effect chain
2915 unlockEffectChains(effectChains);
2916
Eric Laurentbfb1b832013-01-07 09:53:42 -08002917 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002918 // mSleepTimeUs == 0 means we must write to audio hardware
2919 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07002920 ssize_t ret = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002921 if (mBytesRemaining) {
Andy Hung08fb1742015-05-31 23:22:10 -07002922 ret = threadLoop_write();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002923 if (ret < 0) {
2924 mBytesRemaining = 0;
2925 } else {
2926 mBytesWritten += ret;
2927 mBytesRemaining -= ret;
2928 }
2929 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
2930 (mMixerStatus == MIXER_DRAIN_ALL)) {
2931 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08002932 }
Andy Hung08fb1742015-05-31 23:22:10 -07002933 if (mType == MIXER && !mStandby) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07002934 // write blocked detection
2935 nsecs_t now = systemTime();
2936 nsecs_t delta = now - mLastWriteTime;
Andy Hung08fb1742015-05-31 23:22:10 -07002937 if (delta > maxPeriod) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07002938 mNumDelayedWrites++;
2939 if ((now - lastWarning) > kWarningThrottleNs) {
2940 ATRACE_NAME("underrun");
2941 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2942 ns2ms(delta), mNumDelayedWrites, this);
2943 lastWarning = now;
2944 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002945 }
Andy Hung08fb1742015-05-31 23:22:10 -07002946
2947 if (mThreadThrottle
2948 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
2949 && ret > 0) { // we wrote something
2950 // Limit MixerThread data processing to no more than twice the
2951 // expected processing rate.
2952 //
2953 // This helps prevent underruns with NuPlayer and other applications
2954 // which may set up buffers that are close to the minimum size, or use
2955 // deep buffers, and rely on a double-buffering sleep strategy to fill.
2956 //
2957 // The throttle smooths out sudden large data drains from the device,
2958 // e.g. when it comes out of standby, which often causes problems with
2959 // (1) mixer threads without a fast mixer (which has its own warm-up)
2960 // (2) minimum buffer sized tracks (even if the track is full,
2961 // the app won't fill fast enough to handle the sudden draw).
2962
2963 const int32_t deltaMs = delta / 1000000;
2964 const int32_t throttleMs = mHalfBufferMs - deltaMs;
2965 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
2966 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07002967 // notify of throttle start on verbose log
2968 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
2969 "mixer(%p) throttle begin:"
2970 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07002971 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07002972 mThreadThrottleTimeMs += throttleMs;
2973 } else {
2974 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
2975 if (diff > 0) {
2976 // notify of throttle end on debug log
2977 ALOGD("mixer(%p) throttle end: throttle time(%u)", this, diff);
2978 mThreadThrottleEndMs = mThreadThrottleTimeMs;
2979 }
Andy Hung08fb1742015-05-31 23:22:10 -07002980 }
2981 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002982 }
Eric Laurent81784c32012-11-19 14:55:58 -08002983
Eric Laurentbfb1b832013-01-07 09:53:42 -08002984 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07002985 ATRACE_BEGIN("sleep");
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002986 usleep(mSleepTimeUs);
Glenn Kastene7754022014-10-31 12:11:26 -07002987 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002988 }
Eric Laurent81784c32012-11-19 14:55:58 -08002989 }
2990
2991 // Finally let go of removed track(s), without the lock held
2992 // since we can't guarantee the destructors won't acquire that
2993 // same lock. This will also mutate and push a new fast mixer state.
2994 threadLoop_removeTracks(tracksToRemove);
2995 tracksToRemove.clear();
2996
2997 // FIXME I don't understand the need for this here;
2998 // it was in the original code but maybe the
2999 // assignment in saveOutputTracks() makes this unnecessary?
3000 clearOutputTracks();
3001
3002 // Effect chains will be actually deleted here if they were removed from
3003 // mEffectChains list during mixing or effects processing
3004 effectChains.clear();
3005
3006 // FIXME Note that the above .clear() is no longer necessary since effectChains
3007 // is now local to this block, but will keep it for now (at least until merge done).
3008 }
3009
Eric Laurentbfb1b832013-01-07 09:53:42 -08003010 threadLoop_exit();
3011
Eric Laurentcf817a22014-08-04 20:36:31 -07003012 if (!mStandby) {
3013 threadLoop_standby();
3014 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003015 }
3016
3017 releaseWakeLock();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003018 mWakeLockUids.clear();
3019 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08003020
3021 ALOGV("Thread %p type %d exiting", this, mType);
3022 return false;
3023}
3024
Eric Laurentbfb1b832013-01-07 09:53:42 -08003025// removeTracks_l() must be called with ThreadBase::mLock held
3026void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3027{
3028 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07003029 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003030 for (size_t i=0 ; i<count ; i++) {
3031 const sp<Track>& track = tracksToRemove.itemAt(i);
3032 mActiveTracks.remove(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003033 mWakeLockUids.remove(track->uid());
3034 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003035 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
3036 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3037 if (chain != 0) {
3038 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
3039 track->sessionId());
3040 chain->decActiveTrackCnt();
3041 }
3042 if (track->isTerminated()) {
3043 removeTrack_l(track);
3044 }
3045 }
3046 }
3047
3048}
Eric Laurent81784c32012-11-19 14:55:58 -08003049
Eric Laurentaccc1472013-09-20 09:36:34 -07003050status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3051{
3052 if (mNormalSink != 0) {
3053 return mNormalSink->getTimestamp(timestamp);
3054 }
Andy Hung9a1c8892014-12-03 11:37:42 -08003055 if ((mType == OFFLOAD || mType == DIRECT)
3056 && mOutput != NULL && mOutput->stream->get_presentation_position) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003057 uint64_t position64;
Phil Burk062e67a2015-02-11 13:40:50 -08003058 int ret = mOutput->getPresentationPosition(&position64, &timestamp.mTime);
Eric Laurentaccc1472013-09-20 09:36:34 -07003059 if (ret == 0) {
3060 timestamp.mPosition = (uint32_t)position64;
3061 return NO_ERROR;
3062 }
3063 }
3064 return INVALID_OPERATION;
3065}
Eric Laurent1c333e22014-05-20 10:48:17 -07003066
Eric Laurent054d9d32015-04-24 08:48:48 -07003067status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
3068 audio_patch_handle_t *handle)
3069{
3070 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3071 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3072 if (mFastMixer != 0) {
3073 FastMixerStateQueue *sq = mFastMixer->sq();
3074 FastMixerState *state = sq->begin();
3075 if (!(state->mCommand & FastMixerState::IDLE)) {
3076 previousCommand = state->mCommand;
3077 state->mCommand = FastMixerState::HOT_IDLE;
3078 sq->end();
3079 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3080 } else {
3081 sq->end(false /*didModify*/);
3082 }
3083 }
3084 status_t status = PlaybackThread::createAudioPatch_l(patch, handle);
3085
3086 if (!(previousCommand & FastMixerState::IDLE)) {
3087 ALOG_ASSERT(mFastMixer != 0);
3088 FastMixerStateQueue *sq = mFastMixer->sq();
3089 FastMixerState *state = sq->begin();
3090 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3091 state->mCommand = previousCommand;
3092 sq->end();
3093 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3094 }
3095
3096 return status;
3097}
3098
Eric Laurent1c333e22014-05-20 10:48:17 -07003099status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3100 audio_patch_handle_t *handle)
3101{
3102 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003103
3104 // store new device and send to effects
3105 audio_devices_t type = AUDIO_DEVICE_NONE;
3106 for (unsigned int i = 0; i < patch->num_sinks; i++) {
3107 type |= patch->sinks[i].ext.device.type;
3108 }
3109
3110#ifdef ADD_BATTERY_DATA
3111 // when changing the audio output device, call addBatteryData to notify
3112 // the change
3113 if (mOutDevice != type) {
3114 uint32_t params = 0;
3115 // check whether speaker is on
3116 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3117 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003118 }
3119
Eric Laurent054d9d32015-04-24 08:48:48 -07003120 audio_devices_t deviceWithoutSpeaker
3121 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3122 // check if any other device (except speaker) is on
3123 if (type & deviceWithoutSpeaker) {
3124 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3125 }
3126
3127 if (params != 0) {
3128 addBatteryData(params);
3129 }
3130 }
3131#endif
3132
3133 for (size_t i = 0; i < mEffectChains.size(); i++) {
3134 mEffectChains[i]->setDevice_l(type);
3135 }
Eric Laurente8726fe2015-06-26 09:39:24 -07003136 bool configChanged = mOutDevice != type;
Eric Laurent054d9d32015-04-24 08:48:48 -07003137 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003138 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003139
3140 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003141 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
3142 status = hwDevice->create_audio_patch(hwDevice,
3143 patch->num_sources,
3144 patch->sources,
3145 patch->num_sinks,
3146 patch->sinks,
3147 handle);
3148 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003149 char *address;
3150 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3151 //FIXME: we only support address on first sink with HAL version < 3.0
3152 address = audio_device_address_to_parameter(
3153 patch->sinks[0].ext.device.type,
3154 patch->sinks[0].ext.device.address);
3155 } else {
3156 address = (char *)calloc(1, 1);
3157 }
3158 AudioParameter param = AudioParameter(String8(address));
3159 free(address);
3160 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), (int)type);
3161 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3162 param.toString().string());
3163 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003164 }
Eric Laurente8726fe2015-06-26 09:39:24 -07003165 if (configChanged) {
3166 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
3167 }
Eric Laurent1c333e22014-05-20 10:48:17 -07003168 return status;
3169}
3170
Eric Laurent054d9d32015-04-24 08:48:48 -07003171status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3172{
3173 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3174 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3175 if (mFastMixer != 0) {
3176 FastMixerStateQueue *sq = mFastMixer->sq();
3177 FastMixerState *state = sq->begin();
3178 if (!(state->mCommand & FastMixerState::IDLE)) {
3179 previousCommand = state->mCommand;
3180 state->mCommand = FastMixerState::HOT_IDLE;
3181 sq->end();
3182 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3183 } else {
3184 sq->end(false /*didModify*/);
3185 }
3186 }
3187
3188 status_t status = PlaybackThread::releaseAudioPatch_l(handle);
3189
3190 if (!(previousCommand & FastMixerState::IDLE)) {
3191 ALOG_ASSERT(mFastMixer != 0);
3192 FastMixerStateQueue *sq = mFastMixer->sq();
3193 FastMixerState *state = sq->begin();
3194 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3195 state->mCommand = previousCommand;
3196 sq->end();
3197 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3198 }
3199
3200 return status;
3201}
3202
Eric Laurent1c333e22014-05-20 10:48:17 -07003203status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3204{
3205 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003206
3207 mOutDevice = AUDIO_DEVICE_NONE;
3208
Eric Laurent1c333e22014-05-20 10:48:17 -07003209 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
3210 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
3211 status = hwDevice->release_audio_patch(hwDevice, handle);
3212 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003213 AudioParameter param;
3214 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
3215 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3216 param.toString().string());
Eric Laurent1c333e22014-05-20 10:48:17 -07003217 }
3218 return status;
3219}
3220
Eric Laurent83b88082014-06-20 18:31:16 -07003221void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3222{
3223 Mutex::Autolock _l(mLock);
3224 mTracks.add(track);
3225}
3226
3227void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3228{
3229 Mutex::Autolock _l(mLock);
3230 destroyTrack_l(track);
3231}
3232
3233void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
3234{
3235 ThreadBase::getAudioPortConfig(config);
3236 config->role = AUDIO_PORT_ROLE_SOURCE;
3237 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3238 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
3239}
3240
Eric Laurent81784c32012-11-19 14:55:58 -08003241// ----------------------------------------------------------------------------
3242
3243AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurent72e3f392015-05-20 14:43:50 -07003244 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
3245 : PlaybackThread(audioFlinger, output, id, device, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08003246 // mAudioMixer below
3247 // mFastMixer below
3248 mFastMixerFutex(0)
3249 // mOutputSink below
3250 // mPipeSink below
3251 // mNormalSink below
3252{
3253 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07003254 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, "
Eric Laurent81784c32012-11-19 14:55:58 -08003255 "mFrameCount=%d, mNormalFrameCount=%d",
3256 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3257 mNormalFrameCount);
3258 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3259
Andy Hungfbfc3952015-01-15 13:33:51 -08003260 if (type == DUPLICATING) {
3261 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3262 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3263 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3264 return;
3265 }
Eric Laurent81784c32012-11-19 14:55:58 -08003266 // create an NBAIO sink for the HAL output stream, and negotiate
3267 mOutputSink = new AudioStreamOutSink(output->stream);
3268 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003269 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Eric Laurent81784c32012-11-19 14:55:58 -08003270 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
3271 ALOG_ASSERT(index == 0);
3272
3273 // initialize fast mixer depending on configuration
3274 bool initFastMixer;
3275 switch (kUseFastMixer) {
3276 case FastMixer_Never:
3277 initFastMixer = false;
3278 break;
3279 case FastMixer_Always:
3280 initFastMixer = true;
3281 break;
3282 case FastMixer_Static:
3283 case FastMixer_Dynamic:
3284 initFastMixer = mFrameCount < mNormalFrameCount;
3285 break;
3286 }
3287 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003288 audio_format_t fastMixerFormat;
3289 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3290 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3291 } else {
3292 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3293 }
3294 if (mFormat != fastMixerFormat) {
3295 // change our Sink format to accept our intermediate precision
3296 mFormat = fastMixerFormat;
3297 free(mSinkBuffer);
3298 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3299 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3300 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3301 }
Eric Laurent81784c32012-11-19 14:55:58 -08003302
3303 // create a MonoPipe to connect our submix to FastMixer
3304 NBAIO_Format format = mOutputSink->format();
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003305 NBAIO_Format origformat = format;
Andy Hung1258c1a2014-05-23 21:22:17 -07003306 // adjust format to match that of the Fast Mixer
Glenn Kasten97b7b752014-09-28 13:04:24 -07003307 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003308 format.mFormat = fastMixerFormat;
3309 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3310
Eric Laurent81784c32012-11-19 14:55:58 -08003311 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3312 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3313 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3314 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3315 const NBAIO_Format offers[1] = {format};
3316 size_t numCounterOffers = 0;
3317 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
3318 ALOG_ASSERT(index == 0);
3319 monoPipe->setAvgFrames((mScreenState & 1) ?
3320 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3321 mPipeSink = monoPipe;
3322
Glenn Kasten46909e72013-02-26 09:20:22 -08003323#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08003324 if (mTeeSinkOutputEnabled) {
3325 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003326 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
3327 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08003328 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003329 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003330 ALOG_ASSERT(index == 0);
3331 mTeeSink = teeSink;
3332 PipeReader *teeSource = new PipeReader(*teeSink);
3333 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003334 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003335 ALOG_ASSERT(index == 0);
3336 mTeeSource = teeSource;
3337 }
Glenn Kasten46909e72013-02-26 09:20:22 -08003338#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003339
3340 // create fast mixer and configure it initially with just one fast track for our submix
3341 mFastMixer = new FastMixer();
3342 FastMixerStateQueue *sq = mFastMixer->sq();
3343#ifdef STATE_QUEUE_DUMP
3344 sq->setObserverDump(&mStateQueueObserverDump);
3345 sq->setMutatorDump(&mStateQueueMutatorDump);
3346#endif
3347 FastMixerState *state = sq->begin();
3348 FastTrack *fastTrack = &state->mFastTracks[0];
3349 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3350 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3351 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003352 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3353 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003354 fastTrack->mGeneration++;
3355 state->mFastTracksGen++;
3356 state->mTrackMask = 1;
3357 // fast mixer will use the HAL output sink
3358 state->mOutputSink = mOutputSink.get();
3359 state->mOutputSinkGen++;
3360 state->mFrameCount = mFrameCount;
3361 state->mCommand = FastMixerState::COLD_IDLE;
3362 // already done in constructor initialization list
3363 //mFastMixerFutex = 0;
3364 state->mColdFutexAddr = &mFastMixerFutex;
3365 state->mColdGen++;
3366 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08003367#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003368 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08003369#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08003370 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3371 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003372 sq->end();
3373 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3374
3375 // start the fast mixer
3376 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3377 pid_t tid = mFastMixer->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003378 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003379
3380#ifdef AUDIO_WATCHDOG
3381 // create and start the watchdog
3382 mAudioWatchdog = new AudioWatchdog();
3383 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3384 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3385 tid = mAudioWatchdog->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003386 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003387#endif
3388
Eric Laurent81784c32012-11-19 14:55:58 -08003389 }
3390
3391 switch (kUseFastMixer) {
3392 case FastMixer_Never:
3393 case FastMixer_Dynamic:
3394 mNormalSink = mOutputSink;
3395 break;
3396 case FastMixer_Always:
3397 mNormalSink = mPipeSink;
3398 break;
3399 case FastMixer_Static:
3400 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3401 break;
3402 }
3403}
3404
3405AudioFlinger::MixerThread::~MixerThread()
3406{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003407 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003408 FastMixerStateQueue *sq = mFastMixer->sq();
3409 FastMixerState *state = sq->begin();
3410 if (state->mCommand == FastMixerState::COLD_IDLE) {
3411 int32_t old = android_atomic_inc(&mFastMixerFutex);
3412 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003413 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003414 }
3415 }
3416 state->mCommand = FastMixerState::EXIT;
3417 sq->end();
3418 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3419 mFastMixer->join();
3420 // Though the fast mixer thread has exited, it's state queue is still valid.
3421 // We'll use that extract the final state which contains one remaining fast track
3422 // corresponding to our sub-mix.
3423 state = sq->begin();
3424 ALOG_ASSERT(state->mTrackMask == 1);
3425 FastTrack *fastTrack = &state->mFastTracks[0];
3426 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3427 delete fastTrack->mBufferProvider;
3428 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003429 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003430#ifdef AUDIO_WATCHDOG
3431 if (mAudioWatchdog != 0) {
3432 mAudioWatchdog->requestExit();
3433 mAudioWatchdog->requestExitAndWait();
3434 mAudioWatchdog.clear();
3435 }
3436#endif
3437 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003438 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003439 delete mAudioMixer;
3440}
3441
3442
3443uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3444{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003445 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003446 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3447 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3448 }
3449 return latency;
3450}
3451
3452
3453void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3454{
3455 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3456}
3457
Eric Laurentbfb1b832013-01-07 09:53:42 -08003458ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003459{
3460 // FIXME we should only do one push per cycle; confirm this is true
3461 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003462 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003463 FastMixerStateQueue *sq = mFastMixer->sq();
3464 FastMixerState *state = sq->begin();
3465 if (state->mCommand != FastMixerState::MIX_WRITE &&
3466 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3467 if (state->mCommand == FastMixerState::COLD_IDLE) {
3468 int32_t old = android_atomic_inc(&mFastMixerFutex);
3469 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003470 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003471 }
3472#ifdef AUDIO_WATCHDOG
3473 if (mAudioWatchdog != 0) {
3474 mAudioWatchdog->resume();
3475 }
3476#endif
3477 }
3478 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08003479#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003480 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08003481 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08003482#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003483 sq->end();
3484 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3485 if (kUseFastMixer == FastMixer_Dynamic) {
3486 mNormalSink = mPipeSink;
3487 }
3488 } else {
3489 sq->end(false /*didModify*/);
3490 }
3491 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003492 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003493}
3494
3495void AudioFlinger::MixerThread::threadLoop_standby()
3496{
3497 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003498 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003499 FastMixerStateQueue *sq = mFastMixer->sq();
3500 FastMixerState *state = sq->begin();
3501 if (!(state->mCommand & FastMixerState::IDLE)) {
3502 state->mCommand = FastMixerState::COLD_IDLE;
3503 state->mColdFutexAddr = &mFastMixerFutex;
3504 state->mColdGen++;
3505 mFastMixerFutex = 0;
3506 sq->end();
3507 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3508 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3509 if (kUseFastMixer == FastMixer_Dynamic) {
3510 mNormalSink = mOutputSink;
3511 }
3512#ifdef AUDIO_WATCHDOG
3513 if (mAudioWatchdog != 0) {
3514 mAudioWatchdog->pause();
3515 }
3516#endif
3517 } else {
3518 sq->end(false /*didModify*/);
3519 }
3520 }
3521 PlaybackThread::threadLoop_standby();
3522}
3523
Eric Laurentbfb1b832013-01-07 09:53:42 -08003524bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3525{
3526 return false;
3527}
3528
3529bool AudioFlinger::PlaybackThread::shouldStandby_l()
3530{
3531 return !mStandby;
3532}
3533
3534bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3535{
3536 Mutex::Autolock _l(mLock);
3537 return waitingAsyncCallback_l();
3538}
3539
Eric Laurent81784c32012-11-19 14:55:58 -08003540// shared by MIXER and DIRECT, overridden by DUPLICATING
3541void AudioFlinger::PlaybackThread::threadLoop_standby()
3542{
3543 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08003544 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003545 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003546 // discard any pending drain or write ack by incrementing sequence
3547 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3548 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003549 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003550 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3551 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003552 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003553 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003554}
3555
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003556void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3557{
3558 ALOGV("signal playback thread");
3559 broadcast_l();
3560}
3561
Eric Laurent81784c32012-11-19 14:55:58 -08003562void AudioFlinger::MixerThread::threadLoop_mix()
3563{
3564 // obtain the presentation timestamp of the next output buffer
3565 int64_t pts;
3566 status_t status = INVALID_OPERATION;
3567
3568 if (mNormalSink != 0) {
3569 status = mNormalSink->getNextWriteTimestamp(&pts);
3570 } else {
3571 status = mOutputSink->getNextWriteTimestamp(&pts);
3572 }
3573
3574 if (status != NO_ERROR) {
3575 pts = AudioBufferProvider::kInvalidPTS;
3576 }
3577
3578 // mix buffers...
3579 mAudioMixer->process(pts);
Andy Hung25c2dac2014-02-27 14:56:00 -08003580 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003581 // increase sleep time progressively when application underrun condition clears.
3582 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3583 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3584 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003585 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003586 sleepTimeShift--;
3587 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003588 mSleepTimeUs = 0;
3589 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08003590 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003591
Eric Laurent81784c32012-11-19 14:55:58 -08003592}
3593
3594void AudioFlinger::MixerThread::threadLoop_sleepTime()
3595{
3596 // If no tracks are ready, sleep once for the duration of an output
3597 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003598 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003599 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003600 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
3601 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
3602 mSleepTimeUs = kMinThreadSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003603 }
3604 // reduce sleep time in case of consecutive application underruns to avoid
3605 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3606 // duration we would end up writing less data than needed by the audio HAL if
3607 // the condition persists.
3608 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3609 sleepTimeShift++;
3610 }
3611 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003612 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003613 }
3614 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003615 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3616 // before effects processing or output.
3617 if (mMixerBufferValid) {
3618 memset(mMixerBuffer, 0, mMixerBufferSize);
3619 } else {
3620 memset(mSinkBuffer, 0, mSinkBufferSize);
3621 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003622 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003623 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3624 "anticipated start");
3625 }
3626 // TODO add standby time extension fct of effect tail
3627}
3628
3629// prepareTracks_l() must be called with ThreadBase::mLock held
3630AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3631 Vector< sp<Track> > *tracksToRemove)
3632{
3633
3634 mixer_state mixerStatus = MIXER_IDLE;
3635 // find out which tracks need to be processed
3636 size_t count = mActiveTracks.size();
3637 size_t mixedTracks = 0;
3638 size_t tracksWithEffect = 0;
3639 // counts only _active_ fast tracks
3640 size_t fastTracks = 0;
3641 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
3642
3643 float masterVolume = mMasterVolume;
3644 bool masterMute = mMasterMute;
3645
3646 if (masterMute) {
3647 masterVolume = 0;
3648 }
3649 // Delegate master volume control to effect in output mix effect chain if needed
3650 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3651 if (chain != 0) {
3652 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
3653 chain->setVolume_l(&v, &v);
3654 masterVolume = (float)((v + (1 << 23)) >> 24);
3655 chain.clear();
3656 }
3657
3658 // prepare a new state to push
3659 FastMixerStateQueue *sq = NULL;
3660 FastMixerState *state = NULL;
3661 bool didModify = false;
3662 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003663 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003664 sq = mFastMixer->sq();
3665 state = sq->begin();
3666 }
3667
Andy Hung69aed5f2014-02-25 17:24:40 -08003668 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08003669 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08003670
Eric Laurent81784c32012-11-19 14:55:58 -08003671 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003672 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003673 if (t == 0) {
3674 continue;
3675 }
3676
3677 // this const just means the local variable doesn't change
3678 Track* const track = t.get();
3679
3680 // process fast tracks
3681 if (track->isFastTrack()) {
3682
3683 // It's theoretically possible (though unlikely) for a fast track to be created
3684 // and then removed within the same normal mix cycle. This is not a problem, as
3685 // the track never becomes active so it's fast mixer slot is never touched.
3686 // The converse, of removing an (active) track and then creating a new track
3687 // at the identical fast mixer slot within the same normal mix cycle,
3688 // is impossible because the slot isn't marked available until the end of each cycle.
3689 int j = track->mFastIndex;
3690 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
3691 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
3692 FastTrack *fastTrack = &state->mFastTracks[j];
3693
3694 // Determine whether the track is currently in underrun condition,
3695 // and whether it had a recent underrun.
3696 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
3697 FastTrackUnderruns underruns = ftDump->mUnderruns;
3698 uint32_t recentFull = (underruns.mBitFields.mFull -
3699 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
3700 uint32_t recentPartial = (underruns.mBitFields.mPartial -
3701 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
3702 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
3703 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
3704 uint32_t recentUnderruns = recentPartial + recentEmpty;
3705 track->mObservedUnderruns = underruns;
3706 // don't count underruns that occur while stopping or pausing
3707 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07003708 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
3709 recentUnderruns > 0) {
3710 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
3711 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003712 }
3713
3714 // This is similar to the state machine for normal tracks,
3715 // with a few modifications for fast tracks.
3716 bool isActive = true;
3717 switch (track->mState) {
3718 case TrackBase::STOPPING_1:
3719 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08003720 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003721 track->mState = TrackBase::STOPPING_2;
3722 }
3723 break;
3724 case TrackBase::PAUSING:
3725 // ramp down is not yet implemented
3726 track->setPaused();
3727 break;
3728 case TrackBase::RESUMING:
3729 // ramp up is not yet implemented
3730 track->mState = TrackBase::ACTIVE;
3731 break;
3732 case TrackBase::ACTIVE:
3733 if (recentFull > 0 || recentPartial > 0) {
3734 // track has provided at least some frames recently: reset retry count
3735 track->mRetryCount = kMaxTrackRetries;
3736 }
3737 if (recentUnderruns == 0) {
3738 // no recent underruns: stay active
3739 break;
3740 }
3741 // there has recently been an underrun of some kind
3742 if (track->sharedBuffer() == 0) {
3743 // were any of the recent underruns "empty" (no frames available)?
3744 if (recentEmpty == 0) {
3745 // no, then ignore the partial underruns as they are allowed indefinitely
3746 break;
3747 }
3748 // there has recently been an "empty" underrun: decrement the retry counter
3749 if (--(track->mRetryCount) > 0) {
3750 break;
3751 }
3752 // indicate to client process that the track was disabled because of underrun;
3753 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003754 android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003755 // remove from active list, but state remains ACTIVE [confusing but true]
3756 isActive = false;
3757 break;
3758 }
3759 // fall through
3760 case TrackBase::STOPPING_2:
3761 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003762 case TrackBase::STOPPED:
3763 case TrackBase::FLUSHED: // flush() while active
3764 // Check for presentation complete if track is inactive
3765 // We have consumed all the buffers of this track.
3766 // This would be incomplete if we auto-paused on underrun
3767 {
3768 size_t audioHALFrames =
3769 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3770 size_t framesWritten = mBytesWritten / mFrameSize;
3771 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
3772 // track stays in active list until presentation is complete
3773 break;
3774 }
3775 }
3776 if (track->isStopping_2()) {
3777 track->mState = TrackBase::STOPPED;
3778 }
3779 if (track->isStopped()) {
3780 // Can't reset directly, as fast mixer is still polling this track
3781 // track->reset();
3782 // So instead mark this track as needing to be reset after push with ack
3783 resetMask |= 1 << i;
3784 }
3785 isActive = false;
3786 break;
3787 case TrackBase::IDLE:
3788 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08003789 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08003790 }
3791
3792 if (isActive) {
3793 // was it previously inactive?
3794 if (!(state->mTrackMask & (1 << j))) {
3795 ExtendedAudioBufferProvider *eabp = track;
3796 VolumeProvider *vp = track;
3797 fastTrack->mBufferProvider = eabp;
3798 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08003799 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003800 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08003801 fastTrack->mGeneration++;
3802 state->mTrackMask |= 1 << j;
3803 didModify = true;
3804 // no acknowledgement required for newly active tracks
3805 }
3806 // cache the combined master volume and stream type volume for fast mixer; this
3807 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08003808 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08003809 ++fastTracks;
3810 } else {
3811 // was it previously active?
3812 if (state->mTrackMask & (1 << j)) {
3813 fastTrack->mBufferProvider = NULL;
3814 fastTrack->mGeneration++;
3815 state->mTrackMask &= ~(1 << j);
3816 didModify = true;
3817 // If any fast tracks were removed, we must wait for acknowledgement
3818 // because we're about to decrement the last sp<> on those tracks.
3819 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3820 } else {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003821 LOG_ALWAYS_FATAL("fast track %d should have been active", j);
Eric Laurent81784c32012-11-19 14:55:58 -08003822 }
3823 tracksToRemove->add(track);
3824 // Avoids a misleading display in dumpsys
3825 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
3826 }
3827 continue;
3828 }
3829
3830 { // local variable scope to avoid goto warning
3831
3832 audio_track_cblk_t* cblk = track->cblk();
3833
3834 // The first time a track is added we wait
3835 // for all its buffers to be filled before processing it
3836 int name = track->name();
3837 // make sure that we have enough frames to mix one full buffer.
3838 // enforce this condition only once to enable draining the buffer in case the client
3839 // app does not call stop() and relies on underrun to stop:
3840 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
3841 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003842 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07003843 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07003844 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07003845
3846 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07003847 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07003848 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
3849 // add frames already consumed but not yet released by the resampler
3850 // because mAudioTrackServerProxy->framesReady() will include these frames
3851 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
3852
Eric Laurent81784c32012-11-19 14:55:58 -08003853 uint32_t minFrames = 1;
3854 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
3855 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003856 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08003857 }
Eric Laurent13e4c962013-12-20 17:36:01 -08003858
3859 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07003860 if (ATRACE_ENABLED()) {
3861 // I wish we had formatted trace names
3862 char traceName[16];
3863 strcpy(traceName, "nRdy");
3864 int name = track->name();
3865 if (AudioMixer::TRACK0 <= name &&
3866 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
3867 name -= AudioMixer::TRACK0;
3868 traceName[4] = (name / 10) + '0';
3869 traceName[5] = (name % 10) + '0';
3870 } else {
3871 traceName[4] = '?';
3872 traceName[5] = '?';
3873 }
3874 traceName[6] = '\0';
3875 ATRACE_INT(traceName, framesReady);
3876 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003877 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08003878 !track->isPaused() && !track->isTerminated())
3879 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003880 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003881
3882 mixedTracks++;
3883
Andy Hung69aed5f2014-02-25 17:24:40 -08003884 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
3885 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08003886 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08003887 if (track->mainBuffer() != mSinkBuffer &&
3888 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08003889 if (mEffectBufferEnabled) {
3890 mEffectBufferValid = true; // Later can set directly.
3891 }
Eric Laurent81784c32012-11-19 14:55:58 -08003892 chain = getEffectChain_l(track->sessionId());
3893 // Delegate volume control to effect in track effect chain if needed
3894 if (chain != 0) {
3895 tracksWithEffect++;
3896 } else {
3897 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
3898 "session %d",
3899 name, track->sessionId());
3900 }
3901 }
3902
3903
3904 int param = AudioMixer::VOLUME;
3905 if (track->mFillingUpStatus == Track::FS_FILLED) {
3906 // no ramp for the first volume setting
3907 track->mFillingUpStatus = Track::FS_ACTIVE;
3908 if (track->mState == TrackBase::RESUMING) {
3909 track->mState = TrackBase::ACTIVE;
3910 param = AudioMixer::RAMP_VOLUME;
3911 }
3912 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003913 // FIXME should not make a decision based on mServer
3914 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003915 // If the track is stopped before the first frame was mixed,
3916 // do not apply ramp
3917 param = AudioMixer::RAMP_VOLUME;
3918 }
3919
3920 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07003921 uint32_t vl, vr; // in U8.24 integer format
3922 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08003923 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07003924 vl = vr = 0;
3925 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08003926 if (track->isPausing()) {
3927 track->setPaused();
3928 }
3929 } else {
3930
3931 // read original volumes with volume control
3932 float typeVolume = mStreamTypes[track->streamType()].volume;
3933 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003934 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07003935 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07003936 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
3937 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08003938 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07003939 if (vlf > GAIN_FLOAT_UNITY) {
3940 ALOGV("Track left volume out of range: %.3g", vlf);
3941 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003942 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07003943 if (vrf > GAIN_FLOAT_UNITY) {
3944 ALOGV("Track right volume out of range: %.3g", vrf);
3945 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003946 }
3947 // now apply the master volume and stream type volume
Andy Hung6be49402014-05-30 10:42:03 -07003948 vlf *= v;
3949 vrf *= v;
Eric Laurent81784c32012-11-19 14:55:58 -08003950 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07003951 // then derive vl and vr as U8.24 versions for the effect chain
3952 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
3953 vl = (uint32_t) (scaleto8_24 * vlf);
3954 vr = (uint32_t) (scaleto8_24 * vrf);
3955 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08003956 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08003957 // send level comes from shared memory and so may be corrupt
3958 if (sendLevel > MAX_GAIN_INT) {
3959 ALOGV("Track send level out of range: %04X", sendLevel);
3960 sendLevel = MAX_GAIN_INT;
3961 }
Andy Hung6be49402014-05-30 10:42:03 -07003962 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
3963 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08003964 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003965
Eric Laurent81784c32012-11-19 14:55:58 -08003966 // Delegate volume control to effect in track effect chain if needed
3967 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3968 // Do not ramp volume if volume is controlled by effect
3969 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08003970 // Update remaining floating point volume levels
3971 vlf = (float)vl / (1 << 24);
3972 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08003973 track->mHasVolumeController = true;
3974 } else {
3975 // force no volume ramp when volume controller was just disabled or removed
3976 // from effect chain to avoid volume spike
3977 if (track->mHasVolumeController) {
3978 param = AudioMixer::VOLUME;
3979 }
3980 track->mHasVolumeController = false;
3981 }
3982
Eric Laurent81784c32012-11-19 14:55:58 -08003983 // XXX: these things DON'T need to be done each time
3984 mAudioMixer->setBufferProvider(name, track);
3985 mAudioMixer->enable(name);
3986
Andy Hung6be49402014-05-30 10:42:03 -07003987 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
3988 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
3989 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08003990 mAudioMixer->setParameter(
3991 name,
3992 AudioMixer::TRACK,
3993 AudioMixer::FORMAT, (void *)track->format());
3994 mAudioMixer->setParameter(
3995 name,
3996 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003997 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07003998 mAudioMixer->setParameter(
3999 name,
4000 AudioMixer::TRACK,
4001 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08004002 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07004003 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004004 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08004005 if (reqSampleRate == 0) {
4006 reqSampleRate = mSampleRate;
4007 } else if (reqSampleRate > maxSampleRate) {
4008 reqSampleRate = maxSampleRate;
4009 }
Eric Laurent81784c32012-11-19 14:55:58 -08004010 mAudioMixer->setParameter(
4011 name,
4012 AudioMixer::RESAMPLE,
4013 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004014 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004015
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004016 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004017 mAudioMixer->setParameter(
4018 name,
4019 AudioMixer::TIMESTRETCH,
4020 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004021 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004022
Andy Hung69aed5f2014-02-25 17:24:40 -08004023 /*
4024 * Select the appropriate output buffer for the track.
4025 *
Andy Hung98ef9782014-03-04 14:46:50 -08004026 * Tracks with effects go into their own effects chain buffer
4027 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08004028 *
4029 * Other tracks can use mMixerBuffer for higher precision
4030 * channel accumulation. If this buffer is enabled
4031 * (mMixerBufferEnabled true), then selected tracks will accumulate
4032 * into it.
4033 *
4034 */
4035 if (mMixerBufferEnabled
4036 && (track->mainBuffer() == mSinkBuffer
4037 || track->mainBuffer() == mMixerBuffer)) {
4038 mAudioMixer->setParameter(
4039 name,
4040 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004041 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08004042 mAudioMixer->setParameter(
4043 name,
4044 AudioMixer::TRACK,
4045 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
4046 // TODO: override track->mainBuffer()?
4047 mMixerBufferValid = true;
4048 } else {
4049 mAudioMixer->setParameter(
4050 name,
4051 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004052 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08004053 mAudioMixer->setParameter(
4054 name,
4055 AudioMixer::TRACK,
4056 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
4057 }
Eric Laurent81784c32012-11-19 14:55:58 -08004058 mAudioMixer->setParameter(
4059 name,
4060 AudioMixer::TRACK,
4061 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
4062
4063 // reset retry count
4064 track->mRetryCount = kMaxTrackRetries;
4065
4066 // If one track is ready, set the mixer ready if:
4067 // - the mixer was not ready during previous round OR
4068 // - no other track is not ready
4069 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
4070 mixerStatus != MIXER_TRACKS_ENABLED) {
4071 mixerStatus = MIXER_TRACKS_READY;
4072 }
4073 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004074 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hung08fb1742015-05-31 23:22:10 -07004075 ALOGV("track(%p) underrun, framesReady(%zu) < framesDesired(%zd)",
4076 track, framesReady, desiredFrames);
Glenn Kasten82aaf942013-07-17 16:05:07 -07004077 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004078 }
Eric Laurent81784c32012-11-19 14:55:58 -08004079 // clear effect chain input buffer if an active track underruns to avoid sending
4080 // previous audio buffer again to effects
4081 chain = getEffectChain_l(track->sessionId());
4082 if (chain != 0) {
4083 chain->clearInputBuffer();
4084 }
4085
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004086 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004087 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
4088 track->isStopped() || track->isPaused()) {
4089 // We have consumed all the buffers of this track.
4090 // Remove it from the list of active tracks.
4091 // TODO: use actual buffer filling status instead of latency when available from
4092 // audio HAL
4093 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
4094 size_t framesWritten = mBytesWritten / mFrameSize;
4095 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
4096 if (track->isStopped()) {
4097 track->reset();
4098 }
4099 tracksToRemove->add(track);
4100 }
4101 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08004102 // No buffers for this track. Give it a few chances to
4103 // fill a buffer, then remove it from active list.
4104 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004105 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004106 tracksToRemove->add(track);
4107 // indicate to client process that the track was disabled because of underrun;
4108 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07004109 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08004110 // If one track is not ready, mark the mixer also not ready if:
4111 // - the mixer was ready during previous round OR
4112 // - no other track is ready
4113 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
4114 mixerStatus != MIXER_TRACKS_READY) {
4115 mixerStatus = MIXER_TRACKS_ENABLED;
4116 }
4117 }
4118 mAudioMixer->disable(name);
4119 }
4120
4121 } // local variable scope to avoid goto warning
4122track_is_ready: ;
4123
4124 }
4125
4126 // Push the new FastMixer state if necessary
4127 bool pauseAudioWatchdog = false;
4128 if (didModify) {
4129 state->mFastTracksGen++;
4130 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4131 if (kUseFastMixer == FastMixer_Dynamic &&
4132 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4133 state->mCommand = FastMixerState::COLD_IDLE;
4134 state->mColdFutexAddr = &mFastMixerFutex;
4135 state->mColdGen++;
4136 mFastMixerFutex = 0;
4137 if (kUseFastMixer == FastMixer_Dynamic) {
4138 mNormalSink = mOutputSink;
4139 }
4140 // If we go into cold idle, need to wait for acknowledgement
4141 // so that fast mixer stops doing I/O.
4142 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4143 pauseAudioWatchdog = true;
4144 }
Eric Laurent81784c32012-11-19 14:55:58 -08004145 }
4146 if (sq != NULL) {
4147 sq->end(didModify);
4148 sq->push(block);
4149 }
4150#ifdef AUDIO_WATCHDOG
4151 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4152 mAudioWatchdog->pause();
4153 }
4154#endif
4155
4156 // Now perform the deferred reset on fast tracks that have stopped
4157 while (resetMask != 0) {
4158 size_t i = __builtin_ctz(resetMask);
4159 ALOG_ASSERT(i < count);
4160 resetMask &= ~(1 << i);
4161 sp<Track> t = mActiveTracks[i].promote();
4162 if (t == 0) {
4163 continue;
4164 }
4165 Track* track = t.get();
4166 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
4167 track->reset();
4168 }
4169
4170 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004171 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004172
Eric Laurent97d547d2014-09-02 14:45:53 -07004173 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
4174 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07004175 }
4176
4177 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07004178 // as long as there are effects we should clear the effects buffer, to avoid
4179 // passing a non-clean buffer to the effect chain
4180 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07004181 }
Andy Hung69aed5f2014-02-25 17:24:40 -08004182 // sink or mix buffer must be cleared if all tracks are connected to an
4183 // effect chain as in this case the mixer will not write to the sink or mix buffer
4184 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08004185 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4186 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08004187 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08004188 if (mMixerBufferValid) {
4189 memset(mMixerBuffer, 0, mMixerBufferSize);
4190 // TODO: In testing, mSinkBuffer below need not be cleared because
4191 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
4192 // after mixing.
4193 //
4194 // To enforce this guarantee:
4195 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4196 // (mixedTracks == 0 && fastTracks > 0))
4197 // must imply MIXER_TRACKS_READY.
4198 // Later, we may clear buffers regardless, and skip much of this logic.
4199 }
Andy Hung98ef9782014-03-04 14:46:50 -08004200 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07004201 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004202 }
4203
4204 // if any fast tracks, then status is ready
4205 mMixerStatusIgnoringFastTracks = mixerStatus;
4206 if (fastTracks > 0) {
4207 mixerStatus = MIXER_TRACKS_READY;
4208 }
4209 return mixerStatus;
4210}
4211
4212// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07004213int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
4214 audio_format_t format, int sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08004215{
Andy Hunge8a1ced2014-05-09 15:02:21 -07004216 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08004217}
4218
4219// deleteTrackName_l() must be called with ThreadBase::mLock held
4220void AudioFlinger::MixerThread::deleteTrackName_l(int name)
4221{
4222 ALOGV("remove track (%d) and delete from mixer", name);
4223 mAudioMixer->deleteTrackName(name);
4224}
4225
Eric Laurent10351942014-05-08 18:49:52 -07004226// checkForNewParameter_l() must be called with ThreadBase::mLock held
4227bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
4228 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004229{
Eric Laurent81784c32012-11-19 14:55:58 -08004230 bool reconfig = false;
4231
Eric Laurent10351942014-05-08 18:49:52 -07004232 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004233
Eric Laurent10351942014-05-08 18:49:52 -07004234 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
4235 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004236 if (mFastMixer != 0) {
Eric Laurent10351942014-05-08 18:49:52 -07004237 FastMixerStateQueue *sq = mFastMixer->sq();
4238 FastMixerState *state = sq->begin();
4239 if (!(state->mCommand & FastMixerState::IDLE)) {
4240 previousCommand = state->mCommand;
4241 state->mCommand = FastMixerState::HOT_IDLE;
4242 sq->end();
4243 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
4244 } else {
4245 sq->end(false /*didModify*/);
Eric Laurent81784c32012-11-19 14:55:58 -08004246 }
Eric Laurent10351942014-05-08 18:49:52 -07004247 }
Eric Laurent81784c32012-11-19 14:55:58 -08004248
Eric Laurent10351942014-05-08 18:49:52 -07004249 AudioParameter param = AudioParameter(keyValuePair);
4250 int value;
4251 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4252 reconfig = true;
4253 }
4254 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004255 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004256 status = BAD_VALUE;
4257 } else {
4258 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08004259 reconfig = true;
4260 }
Eric Laurent10351942014-05-08 18:49:52 -07004261 }
4262 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004263 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004264 status = BAD_VALUE;
4265 } else {
4266 // no need to save value, since it's constant
4267 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004268 }
Eric Laurent10351942014-05-08 18:49:52 -07004269 }
4270 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4271 // do not accept frame count changes if tracks are open as the track buffer
4272 // size depends on frame count and correct behavior would not be guaranteed
4273 // if frame count is changed after track creation
4274 if (!mTracks.isEmpty()) {
4275 status = INVALID_OPERATION;
4276 } else {
4277 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004278 }
Eric Laurent10351942014-05-08 18:49:52 -07004279 }
4280 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004281#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07004282 // when changing the audio output device, call addBatteryData to notify
4283 // the change
4284 if (mOutDevice != value) {
4285 uint32_t params = 0;
4286 // check whether speaker is on
4287 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
4288 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08004289 }
Eric Laurent10351942014-05-08 18:49:52 -07004290
4291 audio_devices_t deviceWithoutSpeaker
4292 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
4293 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07004294 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07004295 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4296 }
4297
4298 if (params != 0) {
4299 addBatteryData(params);
4300 }
4301 }
Eric Laurent81784c32012-11-19 14:55:58 -08004302#endif
4303
Eric Laurent10351942014-05-08 18:49:52 -07004304 // forward device change to effects that have requested to be
4305 // aware of attached audio device.
4306 if (value != AUDIO_DEVICE_NONE) {
4307 mOutDevice = value;
4308 for (size_t i = 0; i < mEffectChains.size(); i++) {
4309 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08004310 }
4311 }
Eric Laurent10351942014-05-08 18:49:52 -07004312 }
Eric Laurent81784c32012-11-19 14:55:58 -08004313
Eric Laurent10351942014-05-08 18:49:52 -07004314 if (status == NO_ERROR) {
4315 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4316 keyValuePair.string());
4317 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004318 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004319 mStandby = true;
4320 mBytesWritten = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004321 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Eric Laurent10351942014-05-08 18:49:52 -07004322 keyValuePair.string());
Eric Laurent81784c32012-11-19 14:55:58 -08004323 }
Eric Laurent10351942014-05-08 18:49:52 -07004324 if (status == NO_ERROR && reconfig) {
4325 readOutputParameters_l();
4326 delete mAudioMixer;
4327 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4328 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07004329 int name = getTrackName_l(mTracks[i]->mChannelMask,
4330 mTracks[i]->mFormat, mTracks[i]->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07004331 if (name < 0) {
4332 break;
4333 }
4334 mTracks[i]->mName = name;
4335 }
Eric Laurent73e26b62015-04-27 16:55:58 -07004336 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004337 }
Eric Laurent81784c32012-11-19 14:55:58 -08004338 }
4339
4340 if (!(previousCommand & FastMixerState::IDLE)) {
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004341 ALOG_ASSERT(mFastMixer != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08004342 FastMixerStateQueue *sq = mFastMixer->sq();
4343 FastMixerState *state = sq->begin();
4344 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
4345 state->mCommand = previousCommand;
4346 sq->end();
4347 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4348 }
4349
4350 return reconfig;
4351}
4352
4353
4354void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
4355{
4356 const size_t SIZE = 256;
4357 char buffer[SIZE];
4358 String8 result;
4359
4360 PlaybackThread::dumpInternals(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07004361 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Elliott Hughes87cebad2014-05-22 10:14:43 -07004362 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Eric Laurent81784c32012-11-19 14:55:58 -08004363
4364 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten4182c4e2013-07-15 14:45:07 -07004365 const FastMixerDumpState copy(mFastMixerDumpState);
Eric Laurent81784c32012-11-19 14:55:58 -08004366 copy.dump(fd);
4367
4368#ifdef STATE_QUEUE_DUMP
4369 // Similar for state queue
4370 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4371 observerCopy.dump(fd);
4372 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4373 mutatorCopy.dump(fd);
4374#endif
4375
Glenn Kasten46909e72013-02-26 09:20:22 -08004376#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08004377 // Write the tee output to a .wav file
4378 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08004379#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004380
4381#ifdef AUDIO_WATCHDOG
4382 if (mAudioWatchdog != 0) {
4383 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4384 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4385 wdCopy.dump(fd);
4386 }
4387#endif
4388}
4389
4390uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4391{
4392 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4393}
4394
4395uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4396{
4397 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4398}
4399
4400void AudioFlinger::MixerThread::cacheParameters_l()
4401{
4402 PlaybackThread::cacheParameters_l();
4403
4404 // FIXME: Relaxed timing because of a certain device that can't meet latency
4405 // Should be reduced to 2x after the vendor fixes the driver issue
4406 // increase threshold again due to low power audio mode. The way this warning
4407 // threshold is calculated and its usefulness should be reconsidered anyway.
4408 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4409}
4410
4411// ----------------------------------------------------------------------------
4412
4413AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07004414 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device, bool systemReady)
4415 : PlaybackThread(audioFlinger, output, id, device, DIRECT, systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08004416 // mLeftVolFloat, mRightVolFloat
4417{
4418}
4419
Eric Laurentbfb1b832013-01-07 09:53:42 -08004420AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4421 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07004422 ThreadBase::type_t type, bool systemReady)
4423 : PlaybackThread(audioFlinger, output, id, device, type, systemReady)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004424 // mLeftVolFloat, mRightVolFloat
4425{
4426}
4427
Eric Laurent81784c32012-11-19 14:55:58 -08004428AudioFlinger::DirectOutputThread::~DirectOutputThread()
4429{
4430}
4431
Eric Laurentbfb1b832013-01-07 09:53:42 -08004432void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
4433{
4434 audio_track_cblk_t* cblk = track->cblk();
4435 float left, right;
4436
4437 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4438 left = right = 0;
4439 } else {
4440 float typeVolume = mStreamTypes[track->streamType()].volume;
4441 float v = mMasterVolume * typeVolume;
4442 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004443 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4444 left = float_from_gain(gain_minifloat_unpack_left(vlr));
4445 if (left > GAIN_FLOAT_UNITY) {
4446 left = GAIN_FLOAT_UNITY;
4447 }
4448 left *= v;
4449 right = float_from_gain(gain_minifloat_unpack_right(vlr));
4450 if (right > GAIN_FLOAT_UNITY) {
4451 right = GAIN_FLOAT_UNITY;
4452 }
4453 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004454 }
4455
4456 if (lastTrack) {
4457 if (left != mLeftVolFloat || right != mRightVolFloat) {
4458 mLeftVolFloat = left;
4459 mRightVolFloat = right;
4460
4461 // Convert volumes from float to 8.24
4462 uint32_t vl = (uint32_t)(left * (1 << 24));
4463 uint32_t vr = (uint32_t)(right * (1 << 24));
4464
4465 // Delegate volume control to effect in track effect chain if needed
4466 // only one effect chain can be present on DirectOutputThread, so if
4467 // there is one, the track is connected to it
4468 if (!mEffectChains.isEmpty()) {
4469 mEffectChains[0]->setVolume_l(&vl, &vr);
4470 left = (float)vl / (1 << 24);
4471 right = (float)vr / (1 << 24);
4472 }
4473 if (mOutput->stream->set_volume) {
4474 mOutput->stream->set_volume(mOutput->stream, left, right);
4475 }
4476 }
4477 }
4478}
4479
Phil Burk43b4dcc2015-06-09 16:53:44 -07004480void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
4481{
4482 sp<Track> previousTrack = mPreviousTrack.promote();
4483 sp<Track> latestTrack = mLatestActiveTrack.promote();
4484
Eric Laurent0f0631e2015-07-06 18:01:25 -07004485 if (previousTrack != 0 && latestTrack != 0) {
4486 if (mType == DIRECT) {
4487 if (previousTrack.get() != latestTrack.get()) {
4488 mFlushPending = true;
4489 }
4490 } else /* mType == OFFLOAD */ {
4491 if (previousTrack->sessionId() != latestTrack->sessionId()) {
4492 mFlushPending = true;
4493 }
4494 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004495 }
4496 PlaybackThread::onAddNewTrack_l();
4497}
Eric Laurentbfb1b832013-01-07 09:53:42 -08004498
Eric Laurent81784c32012-11-19 14:55:58 -08004499AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4500 Vector< sp<Track> > *tracksToRemove
4501)
4502{
Eric Laurentd595b7c2013-04-03 17:27:56 -07004503 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08004504 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004505 bool doHwPause = false;
4506 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004507
4508 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07004509 for (size_t i = 0; i < count; i++) {
4510 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08004511 // The track died recently
4512 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004513 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08004514 }
4515
Phil Burk43b4dcc2015-06-09 16:53:44 -07004516 if (t->isInvalid()) {
4517 ALOGW("An invalidated track shouldn't be in active list");
4518 tracksToRemove->add(t);
4519 continue;
4520 }
4521
Eric Laurent81784c32012-11-19 14:55:58 -08004522 Track* const track = t.get();
4523 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07004524 // Only consider last track started for volume and mixer state control.
4525 // In theory an older track could underrun and restart after the new one starts
4526 // but as we only care about the transition phase between two tracks on a
4527 // direct output, it is not a problem to ignore the underrun case.
4528 sp<Track> l = mLatestActiveTrack.promote();
4529 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08004530
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004531 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004532 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004533 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004534 doHwPause = true;
4535 mHwPaused = true;
4536 }
4537 tracksToRemove->add(track);
4538 } else if (track->isFlushPending()) {
4539 track->flushAck();
4540 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004541 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004542 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004543 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004544 track->resumeAck();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004545 if (last && mHwPaused) {
4546 doHwResume = true;
4547 mHwPaused = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004548 }
4549 }
4550
Eric Laurent81784c32012-11-19 14:55:58 -08004551 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08004552 // for all its buffers to be filled before processing it.
4553 // Allow draining the buffer in case the client
4554 // app does not call stop() and relies on underrun to stop:
4555 // hence the test on (track->mRetryCount > 1).
4556 // If retryCount<=1 then track is about to underrun and be removed.
Eric Laurent81784c32012-11-19 14:55:58 -08004557 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08004558 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
4559 && (track->mRetryCount > 1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004560 minFrames = mNormalFrameCount;
4561 } else {
4562 minFrames = 1;
4563 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004564
Eric Laurentab5cdba2014-06-09 17:22:27 -07004565 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4566 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08004567 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004568 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08004569
4570 if (track->mFillingUpStatus == Track::FS_FILLED) {
4571 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004572 // make sure processVolume_l() will apply new volume even if 0
4573 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004574 if (!mHwSupportsPause) {
4575 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08004576 }
4577 }
4578
4579 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004580 processVolume_l(track, last);
4581 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004582 sp<Track> previousTrack = mPreviousTrack.promote();
4583 if (previousTrack != 0) {
4584 if (track != previousTrack.get()) {
4585 // Flush any data still being written from last track
4586 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07004587 // Invalidate previous track to force a seek when resuming.
4588 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004589 }
4590 }
4591 mPreviousTrack = track;
4592
Eric Laurentd595b7c2013-04-03 17:27:56 -07004593 // reset retry count
4594 track->mRetryCount = kMaxTrackRetriesDirect;
4595 mActiveTrack = t;
4596 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07004597 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004598 doHwResume = true;
4599 mHwPaused = false;
4600 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004601 }
Eric Laurent81784c32012-11-19 14:55:58 -08004602 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004603 // clear effect chain input buffer if the last active track started underruns
4604 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07004605 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004606 mEffectChains[0]->clearInputBuffer();
4607 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004608 if (track->isStopping_1()) {
4609 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07004610 if (last && mHwPaused) {
4611 doHwResume = true;
4612 mHwPaused = false;
4613 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004614 }
4615 if ((track->sharedBuffer() != 0) || track->isStopped() ||
4616 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004617 // We have consumed all the buffers of this track.
4618 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07004619 size_t audioHALFrames;
4620 if (audio_is_linear_pcm(mFormat)) {
4621 audioHALFrames = (latency_l() * mSampleRate) / 1000;
4622 } else {
4623 audioHALFrames = 0;
4624 }
4625
Eric Laurent81784c32012-11-19 14:55:58 -08004626 size_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07004627 if (mStandby || !last ||
4628 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004629 if (track->isStopping_2()) {
4630 track->mState = TrackBase::STOPPED;
4631 }
Eric Laurent81784c32012-11-19 14:55:58 -08004632 if (track->isStopped()) {
4633 track->reset();
4634 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004635 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08004636 }
4637 } else {
4638 // No buffers for this track. Give it a few chances to
4639 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07004640 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08004641 if (--(track->mRetryCount) <= 0) {
4642 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07004643 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004644 // indicate to client process that the track was disabled because of underrun;
4645 // it will then automatically call start() when data is available
4646 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004647 } else if (last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004648 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07004649 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004650 doHwPause = true;
4651 mHwPaused = true;
4652 }
Eric Laurent81784c32012-11-19 14:55:58 -08004653 }
4654 }
4655 }
4656 }
4657
Eric Laurentd1f69b02014-12-15 14:33:13 -08004658 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07004659 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004660 for (size_t i = 0; i < mTracks.size(); i++) {
4661 if (mTracks[i]->isFlushPending()) {
4662 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004663 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004664 }
4665 }
4666 }
4667
4668 // make sure the pause/flush/resume sequence is executed in the right order.
4669 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4670 // before flush and then resume HW. This can happen in case of pause/flush/resume
4671 // if resume is received before pause is executed.
4672 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07004673 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004674 mOutput->stream->pause(mOutput->stream);
4675 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004676 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004677 flushHw_l();
4678 }
4679 if (mHwSupportsPause && !mStandby && doHwResume) {
4680 mOutput->stream->resume(mOutput->stream);
4681 }
Eric Laurent81784c32012-11-19 14:55:58 -08004682 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004683 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004684
4685 return mixerStatus;
4686}
4687
4688void AudioFlinger::DirectOutputThread::threadLoop_mix()
4689{
Eric Laurent81784c32012-11-19 14:55:58 -08004690 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08004691 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004692 // output audio to hardware
4693 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07004694 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004695 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08004696 status_t status = mActiveTrack->getNextBuffer(&buffer);
4697 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08004698 memset(curBuf, 0, frameCount * mFrameSize);
4699 break;
4700 }
4701 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
4702 frameCount -= buffer.frameCount;
4703 curBuf += buffer.frameCount * mFrameSize;
4704 mActiveTrack->releaseBuffer(&buffer);
4705 }
Andy Hung2098f272014-02-27 14:00:06 -08004706 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004707 mSleepTimeUs = 0;
4708 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08004709 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004710}
4711
4712void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
4713{
Eric Laurentd1f69b02014-12-15 14:33:13 -08004714 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004715 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004716 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004717 return;
4718 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004719 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004720 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004721 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004722 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004723 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004724 }
4725 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08004726 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004727 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004728 }
4729}
4730
Eric Laurentd1f69b02014-12-15 14:33:13 -08004731void AudioFlinger::DirectOutputThread::threadLoop_exit()
4732{
4733 {
4734 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08004735 for (size_t i = 0; i < mTracks.size(); i++) {
4736 if (mTracks[i]->isFlushPending()) {
4737 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004738 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004739 }
4740 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004741 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004742 flushHw_l();
4743 }
4744 }
4745 PlaybackThread::threadLoop_exit();
4746}
4747
4748// must be called with thread mutex locked
4749bool AudioFlinger::DirectOutputThread::shouldStandby_l()
4750{
4751 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07004752 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004753
4754 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4755 // after a timeout and we will enter standby then.
4756 if (mTracks.size() > 0) {
4757 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07004758 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
4759 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004760 }
4761
Eric Laurent5cff4032015-05-26 13:49:58 -07004762 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08004763}
4764
Eric Laurent81784c32012-11-19 14:55:58 -08004765// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004766int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Andy Hunge8a1ced2014-05-09 15:02:21 -07004767 audio_format_t format __unused, int sessionId __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004768{
4769 return 0;
4770}
4771
4772// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004773void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004774{
4775}
4776
Eric Laurent10351942014-05-08 18:49:52 -07004777// checkForNewParameter_l() must be called with ThreadBase::mLock held
4778bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
4779 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004780{
4781 bool reconfig = false;
4782
Eric Laurent10351942014-05-08 18:49:52 -07004783 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004784
Eric Laurent10351942014-05-08 18:49:52 -07004785 AudioParameter param = AudioParameter(keyValuePair);
4786 int value;
4787 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4788 // forward device change to effects that have requested to be
4789 // aware of attached audio device.
4790 if (value != AUDIO_DEVICE_NONE) {
4791 mOutDevice = value;
4792 for (size_t i = 0; i < mEffectChains.size(); i++) {
4793 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07004794 }
4795 }
Eric Laurent81784c32012-11-19 14:55:58 -08004796 }
Eric Laurent10351942014-05-08 18:49:52 -07004797 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4798 // do not accept frame count changes if tracks are open as the track buffer
4799 // size depends on frame count and correct behavior would not be garantied
4800 // if frame count is changed after track creation
4801 if (!mTracks.isEmpty()) {
4802 status = INVALID_OPERATION;
4803 } else {
4804 reconfig = true;
4805 }
4806 }
4807 if (status == NO_ERROR) {
4808 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4809 keyValuePair.string());
4810 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004811 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004812 mStandby = true;
4813 mBytesWritten = 0;
4814 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4815 keyValuePair.string());
4816 }
4817 if (status == NO_ERROR && reconfig) {
4818 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07004819 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004820 }
4821 }
4822
Eric Laurent81784c32012-11-19 14:55:58 -08004823 return reconfig;
4824}
4825
4826uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
4827{
4828 uint32_t time;
4829 if (audio_is_linear_pcm(mFormat)) {
4830 time = PlaybackThread::activeSleepTimeUs();
4831 } else {
4832 time = 10000;
4833 }
4834 return time;
4835}
4836
4837uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
4838{
4839 uint32_t time;
4840 if (audio_is_linear_pcm(mFormat)) {
4841 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
4842 } else {
4843 time = 10000;
4844 }
4845 return time;
4846}
4847
4848uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
4849{
4850 uint32_t time;
4851 if (audio_is_linear_pcm(mFormat)) {
4852 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
4853 } else {
4854 time = 10000;
4855 }
4856 return time;
4857}
4858
4859void AudioFlinger::DirectOutputThread::cacheParameters_l()
4860{
4861 PlaybackThread::cacheParameters_l();
4862
4863 // use shorter standby delay as on normal output to release
4864 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07004865 // no delay on outputs with HW A/V sync
4866 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004867 mStandbyDelayNs = 0;
Eric Laurent5cff4032015-05-26 13:49:58 -07004868 } else if ((mType == OFFLOAD) && !audio_is_linear_pcm(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004869 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07004870 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004871 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07004872 }
Eric Laurent81784c32012-11-19 14:55:58 -08004873}
4874
Eric Laurente659ef42014-09-29 13:06:46 -07004875void AudioFlinger::DirectOutputThread::flushHw_l()
4876{
Phil Burk062e67a2015-02-11 13:40:50 -08004877 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08004878 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07004879 mFlushPending = false;
Eric Laurente659ef42014-09-29 13:06:46 -07004880}
4881
Eric Laurent81784c32012-11-19 14:55:58 -08004882// ----------------------------------------------------------------------------
4883
Eric Laurentbfb1b832013-01-07 09:53:42 -08004884AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07004885 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004886 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07004887 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07004888 mWriteAckSequence(0),
4889 mDrainSequence(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004890{
4891}
4892
4893AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
4894{
4895}
4896
4897void AudioFlinger::AsyncCallbackThread::onFirstRef()
4898{
4899 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
4900}
4901
4902bool AudioFlinger::AsyncCallbackThread::threadLoop()
4903{
4904 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004905 uint32_t writeAckSequence;
4906 uint32_t drainSequence;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004907
4908 {
4909 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08004910 while (!((mWriteAckSequence & 1) ||
4911 (mDrainSequence & 1) ||
4912 exitPending())) {
4913 mWaitWorkCV.wait(mLock);
4914 }
4915
Eric Laurentbfb1b832013-01-07 09:53:42 -08004916 if (exitPending()) {
4917 break;
4918 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004919 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
4920 mWriteAckSequence, mDrainSequence);
4921 writeAckSequence = mWriteAckSequence;
4922 mWriteAckSequence &= ~1;
4923 drainSequence = mDrainSequence;
4924 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004925 }
4926 {
Eric Laurent4de95592013-09-26 15:28:21 -07004927 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
4928 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004929 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004930 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004931 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004932 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004933 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004934 }
4935 }
4936 }
4937 }
4938 return false;
4939}
4940
4941void AudioFlinger::AsyncCallbackThread::exit()
4942{
4943 ALOGV("AsyncCallbackThread::exit");
4944 Mutex::Autolock _l(mLock);
4945 requestExit();
4946 mWaitWorkCV.broadcast();
4947}
4948
Eric Laurent3b4529e2013-09-05 18:09:19 -07004949void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004950{
4951 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004952 // bit 0 is cleared
4953 mWriteAckSequence = sequence << 1;
4954}
4955
4956void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
4957{
4958 Mutex::Autolock _l(mLock);
4959 // ignore unexpected callbacks
4960 if (mWriteAckSequence & 2) {
4961 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004962 mWaitWorkCV.signal();
4963 }
4964}
4965
Eric Laurent3b4529e2013-09-05 18:09:19 -07004966void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004967{
4968 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004969 // bit 0 is cleared
4970 mDrainSequence = sequence << 1;
4971}
4972
4973void AudioFlinger::AsyncCallbackThread::resetDraining()
4974{
4975 Mutex::Autolock _l(mLock);
4976 // ignore unexpected callbacks
4977 if (mDrainSequence & 2) {
4978 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004979 mWaitWorkCV.signal();
4980 }
4981}
4982
4983
4984// ----------------------------------------------------------------------------
4985AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07004986 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady)
4987 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady),
Eric Laurentd7e59222013-11-15 12:02:28 -08004988 mPausedBytesRemaining(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004989{
Eric Laurentfd477972013-10-25 18:10:40 -07004990 //FIXME: mStandby should be set to true by ThreadBase constructor
4991 mStandby = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004992}
4993
Eric Laurentbfb1b832013-01-07 09:53:42 -08004994void AudioFlinger::OffloadThread::threadLoop_exit()
4995{
4996 if (mFlushPending || mHwPaused) {
4997 // If a flush is pending or track was paused, just discard buffered data
4998 flushHw_l();
4999 } else {
5000 mMixerStatus = MIXER_DRAIN_ALL;
5001 threadLoop_drain();
5002 }
Uday Gupta56604aa2014-05-13 11:19:17 -07005003 if (mUseAsyncWrite) {
5004 ALOG_ASSERT(mCallbackThread != 0);
5005 mCallbackThread->exit();
5006 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005007 PlaybackThread::threadLoop_exit();
5008}
5009
5010AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
5011 Vector< sp<Track> > *tracksToRemove
5012)
5013{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005014 size_t count = mActiveTracks.size();
5015
5016 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07005017 bool doHwPause = false;
5018 bool doHwResume = false;
5019
Eric Laurentede6c3b2013-09-19 14:37:46 -07005020 ALOGV("OffloadThread::prepareTracks_l active tracks %d", count);
5021
Eric Laurentbfb1b832013-01-07 09:53:42 -08005022 // find out which tracks need to be processed
5023 for (size_t i = 0; i < count; i++) {
5024 sp<Track> t = mActiveTracks[i].promote();
5025 // The track died recently
5026 if (t == 0) {
5027 continue;
5028 }
5029 Track* const track = t.get();
5030 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07005031 // Only consider last track started for volume and mixer state control.
5032 // In theory an older track could underrun and restart after the new one starts
5033 // but as we only care about the transition phase between two tracks on a
5034 // direct output, it is not a problem to ignore the underrun case.
5035 sp<Track> l = mLatestActiveTrack.promote();
5036 bool last = l.get() == track;
5037
Haynes Mathew George7844f672014-01-15 12:32:55 -08005038 if (track->isInvalid()) {
5039 ALOGW("An invalidated track shouldn't be in active list");
5040 tracksToRemove->add(track);
5041 continue;
5042 }
5043
5044 if (track->mState == TrackBase::IDLE) {
5045 ALOGW("An idle track shouldn't be in active list");
5046 continue;
5047 }
5048
Eric Laurentbfb1b832013-01-07 09:53:42 -08005049 if (track->isPausing()) {
5050 track->setPaused();
5051 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07005052 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07005053 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005054 mHwPaused = true;
5055 }
5056 // If we were part way through writing the mixbuffer to
5057 // the HAL we must save this until we resume
5058 // BUG - this will be wrong if a different track is made active,
5059 // in that case we want to discard the pending data in the
5060 // mixbuffer and tell the client to present it again when the
5061 // track is resumed
5062 mPausedWriteLength = mCurrentWriteLength;
5063 mPausedBytesRemaining = mBytesRemaining;
5064 mBytesRemaining = 0; // stop writing
5065 }
5066 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08005067 } else if (track->isFlushPending()) {
5068 track->flushAck();
5069 if (last) {
5070 mFlushPending = true;
5071 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005072 } else if (track->isResumePending()){
5073 track->resumeAck();
5074 if (last) {
5075 if (mPausedBytesRemaining) {
5076 // Need to continue write that was interrupted
5077 mCurrentWriteLength = mPausedWriteLength;
5078 mBytesRemaining = mPausedBytesRemaining;
5079 mPausedBytesRemaining = 0;
5080 }
5081 if (mHwPaused) {
5082 doHwResume = true;
5083 mHwPaused = false;
5084 // threadLoop_mix() will handle the case that we need to
5085 // resume an interrupted write
5086 }
5087 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005088 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005089
5090 // Do not handle new data in this iteration even if track->framesReady()
5091 mixerStatus = MIXER_TRACKS_ENABLED;
5092 }
5093 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07005094 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005095 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005096 if (track->mFillingUpStatus == Track::FS_FILLED) {
5097 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07005098 // make sure processVolume_l() will apply new volume even if 0
5099 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005100 }
5101
5102 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08005103 sp<Track> previousTrack = mPreviousTrack.promote();
5104 if (previousTrack != 0) {
5105 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08005106 // Flush any data still being written from last track
5107 mBytesRemaining = 0;
5108 if (mPausedBytesRemaining) {
5109 // Last track was paused so we also need to flush saved
5110 // mixbuffer state and invalidate track so that it will
5111 // re-submit that unwritten data when it is next resumed
5112 mPausedBytesRemaining = 0;
5113 // Invalidate is a bit drastic - would be more efficient
5114 // to have a flag to tell client that some of the
5115 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08005116 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005117 }
5118 // flush data already sent to the DSP if changing audio session as audio
5119 // comes from a different source. Also invalidate previous track to force a
5120 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08005121 if (previousTrack->sessionId() != track->sessionId()) {
5122 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005123 }
5124 }
5125 }
5126 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005127 // reset retry count
5128 track->mRetryCount = kMaxTrackRetriesOffload;
5129 mActiveTrack = t;
5130 mixerStatus = MIXER_TRACKS_READY;
5131 }
5132 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005133 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005134 if (track->isStopping_1()) {
5135 // Hardware buffer can hold a large amount of audio so we must
5136 // wait for all current track's data to drain before we say
5137 // that the track is stopped.
5138 if (mBytesRemaining == 0) {
5139 // Only start draining when all data in mixbuffer
5140 // has been written
5141 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
5142 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005143 // do not drain if no data was ever sent to HAL (mStandby == true)
5144 if (last && !mStandby) {
Eric Laurent1b9f9b12013-11-12 19:10:17 -08005145 // do not modify drain sequence if we are already draining. This happens
5146 // when resuming from pause after drain.
5147 if ((mDrainSequence & 1) == 0) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005148 mSleepTimeUs = 0;
5149 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent1b9f9b12013-11-12 19:10:17 -08005150 mixerStatus = MIXER_DRAIN_TRACK;
5151 mDrainSequence += 2;
5152 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005153 if (mHwPaused) {
5154 // It is possible to move from PAUSED to STOPPING_1 without
5155 // a resume so we must ensure hardware is running
Eric Laurent1b9f9b12013-11-12 19:10:17 -08005156 doHwResume = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005157 mHwPaused = false;
5158 }
5159 }
5160 }
5161 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005162 // Drain has completed or we are in standby, signal presentation complete
5163 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005164 track->mState = TrackBase::STOPPED;
5165 size_t audioHALFrames =
5166 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
5167 size_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08005168 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005169 track->presentationComplete(framesWritten, audioHALFrames);
5170 track->reset();
5171 tracksToRemove->add(track);
5172 }
5173 } else {
5174 // No buffers for this track. Give it a few chances to
5175 // fill a buffer, then remove it from active list.
5176 if (--(track->mRetryCount) <= 0) {
5177 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
5178 track->name());
5179 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08005180 // indicate to client process that the track was disabled because of underrun;
5181 // it will then automatically call start() when data is available
5182 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005183 } else if (last){
5184 mixerStatus = MIXER_TRACKS_ENABLED;
5185 }
5186 }
5187 }
5188 // compute volume for this track
5189 processVolume_l(track, last);
5190 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005191
Eric Laurentea0fade2013-10-04 16:23:48 -07005192 // make sure the pause/flush/resume sequence is executed in the right order.
5193 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5194 // before flush and then resume HW. This can happen in case of pause/flush/resume
5195 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07005196 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurent972a1732013-09-04 09:42:59 -07005197 mOutput->stream->pause(mOutput->stream);
5198 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005199 if (mFlushPending) {
5200 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005201 }
Eric Laurentfd477972013-10-25 18:10:40 -07005202 if (!mStandby && doHwResume) {
Eric Laurent972a1732013-09-04 09:42:59 -07005203 mOutput->stream->resume(mOutput->stream);
5204 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005205
Eric Laurentbfb1b832013-01-07 09:53:42 -08005206 // remove all the tracks that need to be...
5207 removeTracks_l(*tracksToRemove);
5208
5209 return mixerStatus;
5210}
5211
Eric Laurentbfb1b832013-01-07 09:53:42 -08005212// must be called with thread mutex locked
5213bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
5214{
Eric Laurent3b4529e2013-09-05 18:09:19 -07005215 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
5216 mWriteAckSequence, mDrainSequence);
5217 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005218 return true;
5219 }
5220 return false;
5221}
5222
Eric Laurentbfb1b832013-01-07 09:53:42 -08005223bool AudioFlinger::OffloadThread::waitingAsyncCallback()
5224{
5225 Mutex::Autolock _l(mLock);
5226 return waitingAsyncCallback_l();
5227}
5228
5229void AudioFlinger::OffloadThread::flushHw_l()
5230{
Eric Laurente659ef42014-09-29 13:06:46 -07005231 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005232 // Flush anything still waiting in the mixbuffer
5233 mCurrentWriteLength = 0;
5234 mBytesRemaining = 0;
5235 mPausedWriteLength = 0;
5236 mPausedBytesRemaining = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08005237
Eric Laurentbfb1b832013-01-07 09:53:42 -08005238 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005239 // discard any pending drain or write ack by incrementing sequence
5240 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5241 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005242 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005243 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5244 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005245 }
5246}
5247
5248// ----------------------------------------------------------------------------
5249
Eric Laurent81784c32012-11-19 14:55:58 -08005250AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07005251 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08005252 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
Eric Laurent72e3f392015-05-20 14:43:50 -07005253 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08005254 mWaitTimeMs(UINT_MAX)
5255{
5256 addOutputTrack(mainThread);
5257}
5258
5259AudioFlinger::DuplicatingThread::~DuplicatingThread()
5260{
5261 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5262 mOutputTracks[i]->destroy();
5263 }
5264}
5265
5266void AudioFlinger::DuplicatingThread::threadLoop_mix()
5267{
5268 // mix buffers...
5269 if (outputsReady(outputTracks)) {
5270 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
5271 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08005272 if (mMixerBufferValid) {
5273 memset(mMixerBuffer, 0, mMixerBufferSize);
5274 } else {
5275 memset(mSinkBuffer, 0, mSinkBufferSize);
5276 }
Eric Laurent81784c32012-11-19 14:55:58 -08005277 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005278 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005279 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005280 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005281 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005282}
5283
5284void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
5285{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005286 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005287 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005288 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005289 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005290 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005291 }
5292 } else if (mBytesWritten != 0) {
5293 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5294 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005295 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005296 } else {
5297 // flush remaining overflow buffers in output tracks
5298 writeFrames = 0;
5299 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005300 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005301 }
5302}
5303
Eric Laurentbfb1b832013-01-07 09:53:42 -08005304ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005305{
5306 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08005307 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005308 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07005309 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08005310 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005311}
5312
5313void AudioFlinger::DuplicatingThread::threadLoop_standby()
5314{
5315 // DuplicatingThread implements standby by stopping all tracks
5316 for (size_t i = 0; i < outputTracks.size(); i++) {
5317 outputTracks[i]->stop();
5318 }
5319}
5320
5321void AudioFlinger::DuplicatingThread::saveOutputTracks()
5322{
5323 outputTracks = mOutputTracks;
5324}
5325
5326void AudioFlinger::DuplicatingThread::clearOutputTracks()
5327{
5328 outputTracks.clear();
5329}
5330
5331void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
5332{
5333 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08005334 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
5335 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
5336 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
5337 const size_t frameCount =
5338 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
5339 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
5340 // from different OutputTracks and their associated MixerThreads (e.g. one may
5341 // nearly empty and the other may be dropping data).
5342
5343 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08005344 this,
5345 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08005346 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08005347 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005348 frameCount,
5349 IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08005350 if (outputTrack->cblk() != NULL) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005351 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
Eric Laurent81784c32012-11-19 14:55:58 -08005352 mOutputTracks.add(outputTrack);
Andy Hungc25b84a2015-01-14 19:04:10 -08005353 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005354 updateWaitTime_l();
5355 }
5356}
5357
5358void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
5359{
5360 Mutex::Autolock _l(mLock);
5361 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5362 if (mOutputTracks[i]->thread() == thread) {
5363 mOutputTracks[i]->destroy();
5364 mOutputTracks.removeAt(i);
5365 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07005366 if (thread->getOutput() == mOutput) {
5367 mOutput = NULL;
5368 }
Eric Laurent81784c32012-11-19 14:55:58 -08005369 return;
5370 }
5371 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07005372 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005373}
5374
5375// caller must hold mLock
5376void AudioFlinger::DuplicatingThread::updateWaitTime_l()
5377{
5378 mWaitTimeMs = UINT_MAX;
5379 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5380 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
5381 if (strong != 0) {
5382 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
5383 if (waitTimeMs < mWaitTimeMs) {
5384 mWaitTimeMs = waitTimeMs;
5385 }
5386 }
5387 }
5388}
5389
5390
5391bool AudioFlinger::DuplicatingThread::outputsReady(
5392 const SortedVector< sp<OutputTrack> > &outputTracks)
5393{
5394 for (size_t i = 0; i < outputTracks.size(); i++) {
5395 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
5396 if (thread == 0) {
5397 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
5398 outputTracks[i].get());
5399 return false;
5400 }
5401 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5402 // see note at standby() declaration
5403 if (playbackThread->standby() && !playbackThread->isSuspended()) {
5404 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
5405 thread.get());
5406 return false;
5407 }
5408 }
5409 return true;
5410}
5411
5412uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
5413{
5414 return (mWaitTimeMs * 1000) / 2;
5415}
5416
5417void AudioFlinger::DuplicatingThread::cacheParameters_l()
5418{
5419 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
5420 updateWaitTime_l();
5421
5422 MixerThread::cacheParameters_l();
5423}
5424
5425// ----------------------------------------------------------------------------
5426// Record
5427// ----------------------------------------------------------------------------
5428
5429AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5430 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08005431 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08005432 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07005433 audio_devices_t inDevice,
5434 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08005435#ifdef TEE_SINK
5436 , const sp<NBAIO_Sink>& teeSink
5437#endif
5438 ) :
Eric Laurent72e3f392015-05-20 14:43:50 -07005439 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005440 mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005441 // mRsmpInFrames and mRsmpInFramesP2 are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005442 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08005443#ifdef TEE_SINK
5444 , mTeeSink(teeSink)
5445#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07005446 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
5447 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005448 // mFastCapture below
5449 , mFastCaptureFutex(0)
5450 // mInputSource
5451 // mPipeSink
5452 // mPipeSource
5453 , mPipeFramesP2(0)
5454 // mPipeMemory
5455 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005456 , mFastTrackAvail(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005457{
Glenn Kastend7dca052015-03-05 16:05:54 -08005458 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
5459 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08005460
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005461 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005462
5463 // create an NBAIO source for the HAL input stream, and negotiate
5464 mInputSource = new AudioStreamInSource(input->stream);
5465 size_t numCounterOffers = 0;
5466 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
5467 ssize_t index = mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
5468 ALOG_ASSERT(index == 0);
5469
5470 // initialize fast capture depending on configuration
5471 bool initFastCapture;
5472 switch (kUseFastCapture) {
5473 case FastCapture_Never:
5474 initFastCapture = false;
5475 break;
5476 case FastCapture_Always:
5477 initFastCapture = true;
5478 break;
5479 case FastCapture_Static:
5480 uint32_t primaryOutputSampleRate;
5481 {
5482 AutoMutex _l(audioFlinger->mHardwareLock);
5483 primaryOutputSampleRate = audioFlinger->mPrimaryOutputSampleRate;
5484 }
5485 initFastCapture =
5486 // either capture sample rate is same as (a reasonable) primary output sample rate
Andy Hungdb4c0312015-05-06 08:46:52 -07005487 ((isMusicRate(primaryOutputSampleRate) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005488 (mSampleRate == primaryOutputSampleRate)) ||
5489 // or primary output sample rate is unknown, and capture sample rate is reasonable
5490 ((primaryOutputSampleRate == 0) &&
Andy Hungdb4c0312015-05-06 08:46:52 -07005491 isMusicRate(mSampleRate))) &&
Glenn Kasten9f81de32014-07-27 15:02:23 -07005492 // and the buffer size is < 12 ms
5493 (mFrameCount * 1000) / mSampleRate < 12;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005494 break;
5495 // case FastCapture_Dynamic:
5496 }
5497
5498 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07005499 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005500 NBAIO_Format format = mInputSource->format();
Glenn Kasten49d00ad2014-07-21 11:22:03 -07005501 size_t pipeFramesP2 = roundup(mSampleRate / 25); // double-buffering of 20 ms each
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005502 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
5503 void *pipeBuffer;
5504 const sp<MemoryDealer> roHeap(readOnlyHeap());
5505 sp<IMemory> pipeMemory;
5506 if ((roHeap == 0) ||
5507 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
5508 (pipeBuffer = pipeMemory->pointer()) == NULL) {
5509 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
5510 goto failed;
5511 }
5512 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
5513 memset(pipeBuffer, 0, pipeSize);
5514 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
5515 const NBAIO_Format offers[1] = {format};
5516 size_t numCounterOffers = 0;
5517 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
5518 ALOG_ASSERT(index == 0);
5519 mPipeSink = pipe;
5520 PipeReader *pipeReader = new PipeReader(*pipe);
5521 numCounterOffers = 0;
5522 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
5523 ALOG_ASSERT(index == 0);
5524 mPipeSource = pipeReader;
5525 mPipeFramesP2 = pipeFramesP2;
5526 mPipeMemory = pipeMemory;
5527
5528 // create fast capture
5529 mFastCapture = new FastCapture();
5530 FastCaptureStateQueue *sq = mFastCapture->sq();
5531#ifdef STATE_QUEUE_DUMP
5532 // FIXME
5533#endif
5534 FastCaptureState *state = sq->begin();
5535 state->mCblk = NULL;
5536 state->mInputSource = mInputSource.get();
5537 state->mInputSourceGen++;
5538 state->mPipeSink = pipe;
5539 state->mPipeSinkGen++;
5540 state->mFrameCount = mFrameCount;
5541 state->mCommand = FastCaptureState::COLD_IDLE;
5542 // already done in constructor initialization list
5543 //mFastCaptureFutex = 0;
5544 state->mColdFutexAddr = &mFastCaptureFutex;
5545 state->mColdGen++;
5546 state->mDumpState = &mFastCaptureDumpState;
5547#ifdef TEE_SINK
5548 // FIXME
5549#endif
5550 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
5551 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
5552 sq->end();
5553 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5554
5555 // start the fast capture
5556 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
5557 pid_t tid = mFastCapture->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07005558 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005559#ifdef AUDIO_WATCHDOG
5560 // FIXME
5561#endif
5562
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005563 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005564 }
5565failed: ;
5566
5567 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08005568}
5569
Eric Laurent81784c32012-11-19 14:55:58 -08005570AudioFlinger::RecordThread::~RecordThread()
5571{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005572 if (mFastCapture != 0) {
5573 FastCaptureStateQueue *sq = mFastCapture->sq();
5574 FastCaptureState *state = sq->begin();
5575 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5576 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5577 if (old == -1) {
5578 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5579 }
5580 }
5581 state->mCommand = FastCaptureState::EXIT;
5582 sq->end();
5583 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5584 mFastCapture->join();
5585 mFastCapture.clear();
5586 }
5587 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07005588 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07005589 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08005590}
5591
5592void AudioFlinger::RecordThread::onFirstRef()
5593{
Glenn Kastend7dca052015-03-05 16:05:54 -08005594 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08005595}
5596
Eric Laurent81784c32012-11-19 14:55:58 -08005597bool AudioFlinger::RecordThread::threadLoop()
5598{
Eric Laurent81784c32012-11-19 14:55:58 -08005599 nsecs_t lastWarning = 0;
5600
5601 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08005602
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005603reacquire_wakelock:
5604 sp<RecordTrack> activeTrack;
Glenn Kasten2b806402013-11-20 16:37:38 -08005605 int activeTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005606 {
5607 Mutex::Autolock _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005608 size_t size = mActiveTracks.size();
5609 activeTracksGen = mActiveTracksGen;
5610 if (size > 0) {
5611 // FIXME an arbitrary choice
5612 activeTrack = mActiveTracks[0];
5613 acquireWakeLock_l(activeTrack->uid());
5614 if (size > 1) {
5615 SortedVector<int> tmp;
5616 for (size_t i = 0; i < size; i++) {
5617 tmp.add(mActiveTracks[i]->uid());
5618 }
5619 updateWakeLockUids_l(tmp);
5620 }
5621 } else {
5622 acquireWakeLock_l(-1);
5623 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005624 }
5625
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005626 // used to request a deferred sleep, to be executed later while mutex is unlocked
5627 uint32_t sleepUs = 0;
5628
5629 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005630 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005631 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07005632
Glenn Kasten5edadd42013-08-14 16:30:49 -07005633 // sleep with mutex unlocked
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005634 if (sleepUs > 0) {
Glenn Kastene7754022014-10-31 12:11:26 -07005635 ATRACE_BEGIN("sleep");
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005636 usleep(sleepUs);
Glenn Kastene7754022014-10-31 12:11:26 -07005637 ATRACE_END();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005638 sleepUs = 0;
Glenn Kasten5edadd42013-08-14 16:30:49 -07005639 }
5640
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005641 // activeTracks accumulates a copy of a subset of mActiveTracks
5642 Vector< sp<RecordTrack> > activeTracks;
5643
Glenn Kasten735f45f2014-08-18 15:51:59 -07005644 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005645 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07005646
Glenn Kasten735f45f2014-08-18 15:51:59 -07005647 // reference to a fast track which is about to be removed
5648 sp<RecordTrack> fastTrackToRemove;
5649
Eric Laurent81784c32012-11-19 14:55:58 -08005650 { // scope for mLock
5651 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08005652
Eric Laurent021cf962014-05-13 10:18:14 -07005653 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005654
Eric Laurent000a4192014-01-29 15:17:32 -08005655 // check exitPending here because checkForNewParameters_l() and
5656 // checkForNewParameters_l() can temporarily release mLock
5657 if (exitPending()) {
5658 break;
5659 }
5660
Glenn Kasten2b806402013-11-20 16:37:38 -08005661 // if no active track(s), then standby and release wakelock
5662 size_t size = mActiveTracks.size();
5663 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07005664 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005665 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08005666 releaseWakeLock_l();
5667 ALOGV("RecordThread: loop stopping");
5668 // go to sleep
5669 mWaitWorkCV.wait(mLock);
5670 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005671 goto reacquire_wakelock;
5672 }
5673
Glenn Kasten2b806402013-11-20 16:37:38 -08005674 if (mActiveTracksGen != activeTracksGen) {
5675 activeTracksGen = mActiveTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005676 SortedVector<int> tmp;
Glenn Kasten2b806402013-11-20 16:37:38 -08005677 for (size_t i = 0; i < size; i++) {
5678 tmp.add(mActiveTracks[i]->uid());
5679 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005680 updateWakeLockUids_l(tmp);
Eric Laurent81784c32012-11-19 14:55:58 -08005681 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005682
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005683 bool doBroadcast = false;
5684 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07005685
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005686 activeTrack = mActiveTracks[i];
5687 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07005688 if (activeTrack->isFastTrack()) {
5689 ALOG_ASSERT(fastTrackToRemove == 0);
5690 fastTrackToRemove = activeTrack;
5691 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005692 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08005693 mActiveTracks.remove(activeTrack);
5694 mActiveTracksGen++;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005695 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07005696 continue;
5697 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005698
5699 TrackBase::track_state activeTrackState = activeTrack->mState;
5700 switch (activeTrackState) {
5701
5702 case TrackBase::PAUSING:
5703 mActiveTracks.remove(activeTrack);
5704 mActiveTracksGen++;
5705 doBroadcast = true;
5706 size--;
5707 continue;
5708
5709 case TrackBase::STARTING_1:
5710 sleepUs = 10000;
5711 i++;
5712 continue;
5713
5714 case TrackBase::STARTING_2:
5715 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005716 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07005717 activeTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005718 break;
5719
5720 case TrackBase::ACTIVE:
5721 break;
5722
5723 case TrackBase::IDLE:
5724 i++;
5725 continue;
5726
5727 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08005728 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07005729 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005730
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005731 activeTracks.add(activeTrack);
5732 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07005733
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005734 if (activeTrack->isFastTrack()) {
5735 ALOG_ASSERT(!mFastTrackAvail);
5736 ALOG_ASSERT(fastTrack == 0);
5737 fastTrack = activeTrack;
5738 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005739 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005740 if (doBroadcast) {
5741 mStartStopCond.broadcast();
5742 }
5743
5744 // sleep if there are no active tracks to process
5745 if (activeTracks.size() == 0) {
5746 if (sleepUs == 0) {
5747 sleepUs = kRecordThreadSleepUs;
5748 }
5749 continue;
5750 }
5751 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07005752
Eric Laurent81784c32012-11-19 14:55:58 -08005753 lockEffectChains_l(effectChains);
5754 }
5755
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005756 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07005757
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005758 size_t size = effectChains.size();
5759 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005760 // thread mutex is not locked, but effect chain is locked
5761 effectChains[i]->process_l();
5762 }
5763
Glenn Kasten735f45f2014-08-18 15:51:59 -07005764 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005765 if (mFastCapture != 0) {
5766 FastCaptureStateQueue *sq = mFastCapture->sq();
5767 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07005768 bool didModify = false;
5769 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005770 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
5771 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
5772 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5773 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5774 if (old == -1) {
5775 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5776 }
5777 }
5778 state->mCommand = FastCaptureState::READ_WRITE;
5779#if 0 // FIXME
5780 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08005781 FastThreadDumpState::kSamplingNforLowRamDevice :
5782 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005783#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07005784 didModify = true;
5785 }
5786 audio_track_cblk_t *cblkOld = state->mCblk;
5787 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
5788 if (cblkNew != cblkOld) {
5789 state->mCblk = cblkNew;
5790 // block until acked if removing a fast track
5791 if (cblkOld != NULL) {
5792 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
5793 }
5794 didModify = true;
5795 }
5796 sq->end(didModify);
5797 if (didModify) {
5798 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005799#if 0
5800 if (kUseFastCapture == FastCapture_Dynamic) {
5801 mNormalSource = mPipeSource;
5802 }
5803#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005804 }
5805 }
5806
Glenn Kasten735f45f2014-08-18 15:51:59 -07005807 // now run the fast track destructor with thread mutex unlocked
5808 fastTrackToRemove.clear();
5809
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005810 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
5811 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
5812 // slow, then this RecordThread will overrun by not calling HAL read often enough.
5813 // If destination is non-contiguous, first read past the nominal end of buffer, then
5814 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005815
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005816 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005817 ssize_t framesRead;
5818
5819 // If an NBAIO source is present, use it to read the normal capture's data
5820 if (mPipeSource != 0) {
5821 size_t framesToRead = mBufferSize / mFrameSize;
Andy Hung57446612015-04-19 23:56:46 -07005822 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005823 framesToRead, AudioBufferProvider::kInvalidPTS);
5824 if (framesRead == 0) {
5825 // since pipe is non-blocking, simulate blocking input
5826 sleepUs = (framesToRead * 1000000LL) / mSampleRate;
5827 }
5828 // otherwise use the HAL / AudioStreamIn directly
5829 } else {
5830 ssize_t bytesRead = mInput->stream->read(mInput->stream,
Andy Hung57446612015-04-19 23:56:46 -07005831 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005832 if (bytesRead < 0) {
5833 framesRead = bytesRead;
5834 } else {
5835 framesRead = bytesRead / mFrameSize;
5836 }
5837 }
5838
5839 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
5840 ALOGE("read failed: framesRead=%d", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005841 // Force input into standby so that it tries to recover at next read attempt
5842 inputStandBy();
5843 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005844 }
5845 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005846 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005847 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005848 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005849
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005850 if (mTeeSink != 0) {
Andy Hung57446612015-04-19 23:56:46 -07005851 (void) mTeeSink->write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005852 }
5853 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005854 {
5855 size_t part1 = mRsmpInFramesP2 - rear;
5856 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07005857 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005858 (framesRead - part1) * mFrameSize);
5859 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005860 }
5861 rear = mRsmpInRear += framesRead;
5862
5863 size = activeTracks.size();
5864 // loop over each active track
5865 for (size_t i = 0; i < size; i++) {
5866 activeTrack = activeTracks[i];
5867
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005868 // skip fast tracks, as those are handled directly by FastCapture
5869 if (activeTrack->isFastTrack()) {
5870 continue;
5871 }
5872
Andy Hung73c02e42015-03-29 01:13:58 -07005873 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07005874 // TODO: Update the activeTrack buffer converter in case of reconfigure.
5875
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005876 enum {
5877 OVERRUN_UNKNOWN,
5878 OVERRUN_TRUE,
5879 OVERRUN_FALSE
5880 } overrun = OVERRUN_UNKNOWN;
5881
5882 // loop over getNextBuffer to handle circular sink
5883 for (;;) {
5884
5885 activeTrack->mSink.frameCount = ~0;
5886 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
5887 size_t framesOut = activeTrack->mSink.frameCount;
5888 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
5889
Andy Hung73c02e42015-03-29 01:13:58 -07005890 // check available frames and handle overrun conditions
5891 // if the record track isn't draining fast enough.
5892 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005893 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07005894 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
5895 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005896 overrun = OVERRUN_TRUE;
5897 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005898 if (framesOut == 0 || framesIn == 0) {
5899 break;
5900 }
5901
Andy Hung6770c6f2015-04-07 13:43:36 -07005902 // Don't allow framesOut to be larger than what is possible with resampling
5903 // from framesIn.
5904 // This isn't strictly necessary but helps limit buffer resizing in
5905 // RecordBufferConverter. TODO: remove when no longer needed.
5906 framesOut = min(framesOut,
5907 destinationFramesPossible(
5908 framesIn, mSampleRate, activeTrack->mSampleRate));
Andy Hung97a893e2015-03-29 01:03:07 -07005909 // process frames from the RecordThread buffer provider to the RecordTrack buffer
5910 framesOut = activeTrack->mRecordBufferConverter->convert(
5911 activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005912
5913 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
5914 overrun = OVERRUN_FALSE;
5915 }
5916
5917 if (activeTrack->mFramesToDrop == 0) {
5918 if (framesOut > 0) {
5919 activeTrack->mSink.frameCount = framesOut;
5920 activeTrack->releaseBuffer(&activeTrack->mSink);
5921 }
5922 } else {
5923 // FIXME could do a partial drop of framesOut
5924 if (activeTrack->mFramesToDrop > 0) {
5925 activeTrack->mFramesToDrop -= framesOut;
5926 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005927 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005928 }
5929 } else {
5930 activeTrack->mFramesToDrop += framesOut;
5931 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
5932 activeTrack->mSyncStartEvent->isCancelled()) {
5933 ALOGW("Synced record %s, session %d, trigger session %d",
5934 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
5935 activeTrack->sessionId(),
5936 (activeTrack->mSyncStartEvent != 0) ?
5937 activeTrack->mSyncStartEvent->triggerSession() : 0);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005938 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005939 }
5940 }
5941 }
5942
5943 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005944 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005945 }
5946 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005947
5948 switch (overrun) {
5949 case OVERRUN_TRUE:
5950 // client isn't retrieving buffers fast enough
5951 if (!activeTrack->setOverflow()) {
5952 nsecs_t now = systemTime();
5953 // FIXME should lastWarning per track?
5954 if ((now - lastWarning) > kWarningThrottleNs) {
5955 ALOGW("RecordThread: buffer overflow");
5956 lastWarning = now;
5957 }
5958 }
5959 break;
5960 case OVERRUN_FALSE:
5961 activeTrack->clearOverflow();
5962 break;
5963 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005964 break;
5965 }
5966
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005967 }
5968
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005969unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08005970 // enable changes in effect chain
5971 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005972 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08005973 }
5974
Glenn Kasten93e471f2013-08-19 08:40:07 -07005975 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08005976
5977 {
5978 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07005979 for (size_t i = 0; i < mTracks.size(); i++) {
5980 sp<RecordTrack> track = mTracks[i];
5981 track->invalidate();
5982 }
Glenn Kasten2b806402013-11-20 16:37:38 -08005983 mActiveTracks.clear();
5984 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08005985 mStartStopCond.broadcast();
5986 }
5987
5988 releaseWakeLock();
5989
5990 ALOGV("RecordThread %p exiting", this);
5991 return false;
5992}
5993
Glenn Kasten93e471f2013-08-19 08:40:07 -07005994void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08005995{
5996 if (!mStandby) {
5997 inputStandBy();
5998 mStandby = true;
5999 }
6000}
6001
6002void AudioFlinger::RecordThread::inputStandBy()
6003{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006004 // Idle the fast capture if it's currently running
6005 if (mFastCapture != 0) {
6006 FastCaptureStateQueue *sq = mFastCapture->sq();
6007 FastCaptureState *state = sq->begin();
6008 if (!(state->mCommand & FastCaptureState::IDLE)) {
6009 state->mCommand = FastCaptureState::COLD_IDLE;
6010 state->mColdFutexAddr = &mFastCaptureFutex;
6011 state->mColdGen++;
6012 mFastCaptureFutex = 0;
6013 sq->end();
6014 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
6015 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
6016#if 0
6017 if (kUseFastCapture == FastCapture_Dynamic) {
6018 // FIXME
6019 }
6020#endif
6021#ifdef AUDIO_WATCHDOG
6022 // FIXME
6023#endif
6024 } else {
6025 sq->end(false /*didModify*/);
6026 }
6027 }
Eric Laurent81784c32012-11-19 14:55:58 -08006028 mInput->stream->common.standby(&mInput->stream->common);
6029}
6030
Glenn Kasten05997e22014-03-13 15:08:33 -07006031// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07006032sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08006033 const sp<AudioFlinger::Client>& client,
6034 uint32_t sampleRate,
6035 audio_format_t format,
6036 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08006037 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08006038 int sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07006039 size_t *notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08006040 int uid,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07006041 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08006042 pid_t tid,
6043 status_t *status)
6044{
Glenn Kasten74935e42013-12-19 08:56:45 -08006045 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08006046 sp<RecordTrack> track;
6047 status_t lStatus;
6048
Glenn Kasten90e58b12013-07-31 16:16:02 -07006049 // client expresses a preference for FAST, but we get the final say
6050 if (*flags & IAudioFlinger::TRACK_FAST) {
6051 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07006052 // we formerly checked for a callback handler (non-0 tid),
6053 // but that is no longer required for TRANSFER_OBTAIN mode
6054 //
Glenn Kasten74105912014-07-03 12:28:53 -07006055 // frame count is not specified, or is exactly the pipe depth
6056 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006057 // PCM data
6058 audio_is_linear_pcm(format) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006059 // native format
6060 (format == mFormat) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006061 // native channel mask
6062 (channelMask == mChannelMask) &&
6063 // native hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07006064 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006065 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006066 hasFastCapture() &&
6067 // there are sufficient fast track slots available
6068 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07006069 ) {
Glenn Kasten74105912014-07-03 12:28:53 -07006070 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%u mFrameCount=%u",
Glenn Kasten90e58b12013-07-31 16:16:02 -07006071 frameCount, mFrameCount);
6072 } else {
Glenn Kasten74105912014-07-03 12:28:53 -07006073 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%u mFrameCount=%u mPipeFramesP2=%u "
6074 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006075 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Glenn Kasten74105912014-07-03 12:28:53 -07006076 frameCount, mFrameCount, mPipeFramesP2,
6077 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
6078 hasFastCapture(), tid, mFastTrackAvail);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006079 *flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kasten74105912014-07-03 12:28:53 -07006080 }
6081 }
6082
6083 // compute track buffer size in frames, and suggest the notification frame count
6084 if (*flags & IAudioFlinger::TRACK_FAST) {
6085 // fast track: frame count is exactly the pipe depth
6086 frameCount = mPipeFramesP2;
6087 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
6088 *notificationFrames = mFrameCount;
6089 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006090 // not fast track: max notification period is resampled equivalent of one HAL buffer time
6091 // or 20 ms if there is a fast capture
6092 // TODO This could be a roundupRatio inline, and const
6093 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
6094 * sampleRate + mSampleRate - 1) / mSampleRate;
6095 // minimum number of notification periods is at least kMinNotifications,
6096 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
6097 static const size_t kMinNotifications = 3;
6098 static const uint32_t kMinMs = 30;
6099 // TODO This could be a roundupRatio inline
6100 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
6101 // TODO This could be a roundupRatio inline
6102 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
6103 maxNotificationFrames;
6104 const size_t minFrameCount = maxNotificationFrames *
6105 max(kMinNotifications, minNotificationsByMs);
6106 frameCount = max(frameCount, minFrameCount);
6107 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
6108 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07006109 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07006110 }
Glenn Kasten74935e42013-12-19 08:56:45 -08006111 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07006112
Glenn Kasten15e57982013-09-24 11:52:37 -07006113 lStatus = initCheck();
6114 if (lStatus != NO_ERROR) {
6115 ALOGE("createRecordTrack_l() audio driver not initialized");
6116 goto Exit;
6117 }
Eric Laurent81784c32012-11-19 14:55:58 -08006118
6119 { // scope for mLock
6120 Mutex::Autolock _l(mLock);
6121
6122 track = new RecordTrack(this, client, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07006123 format, channelMask, frameCount, NULL, sessionId, uid,
6124 *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08006125
Glenn Kasten03003332013-08-06 15:40:54 -07006126 lStatus = track->initCheck();
6127 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07006128 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08006129 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08006130 goto Exit;
6131 }
6132 mTracks.add(track);
6133
6134 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6135 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6136 mAudioFlinger->btNrecIsOff();
6137 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6138 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006139
6140 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
6141 pid_t callingPid = IPCThreadState::self()->getCallingPid();
6142 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
6143 // so ask activity manager to do this on our behalf
6144 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
6145 }
Eric Laurent81784c32012-11-19 14:55:58 -08006146 }
Glenn Kasten05997e22014-03-13 15:08:33 -07006147
Eric Laurent81784c32012-11-19 14:55:58 -08006148 lStatus = NO_ERROR;
6149
6150Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07006151 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08006152 return track;
6153}
6154
6155status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
6156 AudioSystem::sync_event_t event,
6157 int triggerSession)
6158{
6159 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
6160 sp<ThreadBase> strongMe = this;
6161 status_t status = NO_ERROR;
6162
6163 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006164 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006165 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006166 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08006167 triggerSession,
6168 recordTrack->sessionId(),
6169 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006170 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08006171 // Sync event can be cancelled by the trigger session if the track is not in a
6172 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006173 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006174 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006175 } else {
6176 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006177 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006178 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08006179 }
6180 }
6181
6182 {
Glenn Kasten47c20702013-08-13 15:37:35 -07006183 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08006184 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006185 if (mActiveTracks.indexOf(recordTrack) >= 0) {
6186 if (recordTrack->mState == TrackBase::PAUSING) {
6187 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006188 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006189 } else {
6190 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08006191 }
6192 return status;
6193 }
6194
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006195 // TODO consider other ways of handling this, such as changing the state to :STARTING and
6196 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
6197 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006198 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08006199 mActiveTracks.add(recordTrack);
6200 mActiveTracksGen++;
Eric Laurent83b88082014-06-20 18:31:16 -07006201 status_t status = NO_ERROR;
6202 if (recordTrack->isExternalTrack()) {
6203 mLock.unlock();
Eric Laurent4dc68062014-07-28 17:26:49 -07006204 status = AudioSystem::startInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006205 mLock.lock();
6206 // FIXME should verify that recordTrack is still in mActiveTracks
6207 if (status != NO_ERROR) {
6208 mActiveTracks.remove(recordTrack);
6209 mActiveTracksGen++;
6210 recordTrack->clearSyncStartEvent();
6211 ALOGV("RecordThread::start error %d", status);
6212 return status;
6213 }
Eric Laurent81784c32012-11-19 14:55:58 -08006214 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006215 // Catch up with current buffer indices if thread is already running.
6216 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
6217 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
6218 // see previously buffered data before it called start(), but with greater risk of overrun.
6219
Andy Hung73c02e42015-03-29 01:13:58 -07006220 recordTrack->mResamplerBufferProvider->reset();
Andy Hung97a893e2015-03-29 01:03:07 -07006221 // clear any converter state as new data will be discontinuous
6222 recordTrack->mRecordBufferConverter->reset();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006223 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08006224 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08006225 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08006226 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006227 ALOGV("Record failed to start");
6228 status = BAD_VALUE;
6229 goto startError;
6230 }
Eric Laurent81784c32012-11-19 14:55:58 -08006231 return status;
6232 }
Glenn Kasten7c027242012-12-26 14:43:16 -08006233
Eric Laurent81784c32012-11-19 14:55:58 -08006234startError:
Eric Laurent83b88082014-06-20 18:31:16 -07006235 if (recordTrack->isExternalTrack()) {
Eric Laurent4dc68062014-07-28 17:26:49 -07006236 AudioSystem::stopInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006237 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006238 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006239 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08006240 return status;
6241}
6242
Eric Laurent81784c32012-11-19 14:55:58 -08006243void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6244{
6245 sp<SyncEvent> strongEvent = event.promote();
6246
6247 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08006248 sp<RefBase> ptr = strongEvent->cookie().promote();
6249 if (ptr != 0) {
6250 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
6251 recordTrack->handleSyncStartEvent(strongEvent);
6252 }
Eric Laurent81784c32012-11-19 14:55:58 -08006253 }
6254}
6255
Glenn Kastena8356f62013-07-25 14:37:52 -07006256bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08006257 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07006258 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006259 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08006260 return false;
6261 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006262 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08006263 recordTrack->mState = TrackBase::PAUSING;
6264 // do not wait for mStartStopCond if exiting
6265 if (exitPending()) {
6266 return true;
6267 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006268 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08006269 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006270 // if we have been restarted, recordTrack is in mActiveTracks here
6271 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006272 ALOGV("Record stopped OK");
6273 return true;
6274 }
6275 return false;
6276}
6277
Glenn Kasten0f11b512014-01-31 16:18:54 -08006278bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08006279{
6280 return false;
6281}
6282
Glenn Kasten0f11b512014-01-31 16:18:54 -08006283status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006284{
6285#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
6286 if (!isValidSyncEvent(event)) {
6287 return BAD_VALUE;
6288 }
6289
6290 int eventSession = event->triggerSession();
6291 status_t ret = NAME_NOT_FOUND;
6292
6293 Mutex::Autolock _l(mLock);
6294
6295 for (size_t i = 0; i < mTracks.size(); i++) {
6296 sp<RecordTrack> track = mTracks[i];
6297 if (eventSession == track->sessionId()) {
6298 (void) track->setSyncEvent(event);
6299 ret = NO_ERROR;
6300 }
6301 }
6302 return ret;
6303#else
6304 return BAD_VALUE;
6305#endif
6306}
6307
6308// destroyTrack_l() must be called with ThreadBase::mLock held
6309void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6310{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006311 track->terminate();
6312 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08006313 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08006314 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006315 removeTrack_l(track);
6316 }
6317}
6318
6319void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6320{
6321 mTracks.remove(track);
6322 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006323 if (track->isFastTrack()) {
6324 ALOG_ASSERT(!mFastTrackAvail);
6325 mFastTrackAvail = true;
6326 }
Eric Laurent81784c32012-11-19 14:55:58 -08006327}
6328
6329void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6330{
6331 dumpInternals(fd, args);
6332 dumpTracks(fd, args);
6333 dumpEffectChains(fd, args);
6334}
6335
6336void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6337{
Elliott Hughes87cebad2014-05-22 10:14:43 -07006338 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08006339
Glenn Kasten44182c22015-03-05 17:12:23 -08006340 dumpBase(fd, args);
6341
6342 if (mActiveTracks.size() == 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006343 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006344 }
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006345 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006346 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08006347
6348 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
6349 const FastCaptureDumpState copy(mFastCaptureDumpState);
6350 copy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006351}
6352
Glenn Kasten0f11b512014-01-31 16:18:54 -08006353void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006354{
6355 const size_t SIZE = 256;
6356 char buffer[SIZE];
6357 String8 result;
6358
Marco Nelissenb2208842014-02-07 14:00:50 -08006359 size_t numtracks = mTracks.size();
6360 size_t numactive = mActiveTracks.size();
6361 size_t numactiveseen = 0;
Elliott Hughes87cebad2014-05-22 10:14:43 -07006362 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08006363 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006364 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08006365 RecordTrack::appendDumpHeader(result);
6366 for (size_t i = 0; i < numtracks ; ++i) {
6367 sp<RecordTrack> track = mTracks[i];
6368 if (track != 0) {
6369 bool active = mActiveTracks.indexOf(track) >= 0;
6370 if (active) {
6371 numactiveseen++;
6372 }
6373 track->dump(buffer, SIZE, active);
6374 result.append(buffer);
6375 }
Eric Laurent81784c32012-11-19 14:55:58 -08006376 }
Marco Nelissenb2208842014-02-07 14:00:50 -08006377 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006378 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006379 }
6380
Marco Nelissenb2208842014-02-07 14:00:50 -08006381 if (numactiveseen != numactive) {
6382 snprintf(buffer, SIZE, " The following tracks are in the active list but"
6383 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006384 result.append(buffer);
6385 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08006386 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08006387 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08006388 if (mTracks.indexOf(track) < 0) {
6389 track->dump(buffer, SIZE, true);
6390 result.append(buffer);
6391 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006392 }
Eric Laurent81784c32012-11-19 14:55:58 -08006393
6394 }
6395 write(fd, result.string(), result.size());
6396}
6397
Andy Hung73c02e42015-03-29 01:13:58 -07006398
6399void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
6400{
6401 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6402 RecordThread *recordThread = (RecordThread *) threadBase.get();
6403 mRsmpInFront = recordThread->mRsmpInRear;
6404 mRsmpInUnrel = 0;
6405}
6406
6407void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
6408 size_t *framesAvailable, bool *hasOverrun)
6409{
6410 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6411 RecordThread *recordThread = (RecordThread *) threadBase.get();
6412 const int32_t rear = recordThread->mRsmpInRear;
6413 const int32_t front = mRsmpInFront;
6414 const ssize_t filled = rear - front;
6415
6416 size_t framesIn;
6417 bool overrun = false;
6418 if (filled < 0) {
6419 // should not happen, but treat like a massive overrun and re-sync
6420 framesIn = 0;
6421 mRsmpInFront = rear;
6422 overrun = true;
6423 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
6424 framesIn = (size_t) filled;
6425 } else {
6426 // client is not keeping up with server, but give it latest data
6427 framesIn = recordThread->mRsmpInFrames;
6428 mRsmpInFront = /* front = */ rear - framesIn;
6429 overrun = true;
6430 }
6431 if (framesAvailable != NULL) {
6432 *framesAvailable = framesIn;
6433 }
6434 if (hasOverrun != NULL) {
6435 *hasOverrun = overrun;
6436 }
6437}
6438
Eric Laurent81784c32012-11-19 14:55:58 -08006439// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006440status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
6441 AudioBufferProvider::Buffer* buffer, int64_t pts __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006442{
Andy Hung73c02e42015-03-29 01:13:58 -07006443 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006444 if (threadBase == 0) {
6445 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006446 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006447 return NOT_ENOUGH_DATA;
6448 }
6449 RecordThread *recordThread = (RecordThread *) threadBase.get();
6450 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07006451 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07006452 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006453 // FIXME should not be P2 (don't want to increase latency)
6454 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006455 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07006456 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006457 front &= recordThread->mRsmpInFramesP2 - 1;
6458 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07006459 if (part1 > (size_t) filled) {
6460 part1 = filled;
6461 }
6462 size_t ask = buffer->frameCount;
6463 ALOG_ASSERT(ask > 0);
6464 if (part1 > ask) {
6465 part1 = ask;
6466 }
6467 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07006468 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07006469 buffer->raw = NULL;
6470 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07006471 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07006472 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08006473 }
6474
Andy Hung57446612015-04-19 23:56:46 -07006475 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07006476 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07006477 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08006478 return NO_ERROR;
6479}
6480
6481// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006482void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
6483 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006484{
Glenn Kasten85948432013-08-19 12:09:05 -07006485 size_t stepCount = buffer->frameCount;
6486 if (stepCount == 0) {
6487 return;
6488 }
Andy Hung73c02e42015-03-29 01:13:58 -07006489 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
6490 mRsmpInUnrel -= stepCount;
6491 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07006492 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006493 buffer->frameCount = 0;
6494}
6495
Andy Hung97a893e2015-03-29 01:03:07 -07006496AudioFlinger::RecordThread::RecordBufferConverter::RecordBufferConverter(
6497 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6498 uint32_t srcSampleRate,
6499 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6500 uint32_t dstSampleRate) :
6501 mSrcChannelMask(AUDIO_CHANNEL_INVALID), // updateParameters will set following vars
6502 // mSrcFormat
6503 // mSrcSampleRate
6504 // mDstChannelMask
6505 // mDstFormat
6506 // mDstSampleRate
6507 // mSrcChannelCount
6508 // mDstChannelCount
6509 // mDstFrameSize
6510 mBuf(NULL), mBufFrames(0), mBufFrameSize(0),
Andy Hungd330ee42015-04-20 13:23:41 -07006511 mResampler(NULL),
6512 mIsLegacyDownmix(false),
6513 mIsLegacyUpmix(false),
6514 mRequiresFloat(false),
6515 mInputConverterProvider(NULL)
Andy Hung97a893e2015-03-29 01:03:07 -07006516{
6517 (void)updateParameters(srcChannelMask, srcFormat, srcSampleRate,
6518 dstChannelMask, dstFormat, dstSampleRate);
6519}
6520
6521AudioFlinger::RecordThread::RecordBufferConverter::~RecordBufferConverter() {
6522 free(mBuf);
6523 delete mResampler;
Andy Hungd330ee42015-04-20 13:23:41 -07006524 delete mInputConverterProvider;
Andy Hung97a893e2015-03-29 01:03:07 -07006525}
6526
6527size_t AudioFlinger::RecordThread::RecordBufferConverter::convert(void *dst,
6528 AudioBufferProvider *provider, size_t frames)
6529{
Andy Hungd330ee42015-04-20 13:23:41 -07006530 if (mInputConverterProvider != NULL) {
6531 mInputConverterProvider->setBufferProvider(provider);
6532 provider = mInputConverterProvider;
6533 }
6534
6535 if (mResampler == NULL) {
Andy Hung97a893e2015-03-29 01:03:07 -07006536 ALOGVV("NO RESAMPLING sampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6537 mSrcSampleRate, mSrcFormat, mDstFormat);
6538
6539 AudioBufferProvider::Buffer buffer;
6540 for (size_t i = frames; i > 0; ) {
6541 buffer.frameCount = i;
6542 status_t status = provider->getNextBuffer(&buffer, 0);
6543 if (status != OK || buffer.frameCount == 0) {
6544 frames -= i; // cannot fill request.
6545 break;
6546 }
Andy Hungd330ee42015-04-20 13:23:41 -07006547 // format convert to destination buffer
6548 convertNoResampler(dst, buffer.raw, buffer.frameCount);
Andy Hung97a893e2015-03-29 01:03:07 -07006549
6550 dst = (int8_t*)dst + buffer.frameCount * mDstFrameSize;
6551 i -= buffer.frameCount;
6552 provider->releaseBuffer(&buffer);
6553 }
6554 } else {
6555 ALOGVV("RESAMPLING mSrcSampleRate:%u mDstSampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6556 mSrcSampleRate, mDstSampleRate, mSrcFormat, mDstFormat);
6557
Andy Hungd330ee42015-04-20 13:23:41 -07006558 // reallocate buffer if needed
6559 if (mBufFrameSize != 0 && mBufFrames < frames) {
6560 free(mBuf);
6561 mBufFrames = frames;
6562 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
6563 }
Andy Hung97a893e2015-03-29 01:03:07 -07006564 // resampler accumulates, but we only have one source track
Andy Hungd330ee42015-04-20 13:23:41 -07006565 memset(mBuf, 0, frames * mBufFrameSize);
6566 frames = mResampler->resample((int32_t*)mBuf, frames, provider);
6567 // format convert to destination buffer
6568 convertResampler(dst, mBuf, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006569 }
6570 return frames;
6571}
6572
6573status_t AudioFlinger::RecordThread::RecordBufferConverter::updateParameters(
6574 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6575 uint32_t srcSampleRate,
6576 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6577 uint32_t dstSampleRate)
6578{
6579 // quick evaluation if there is any change.
6580 if (mSrcFormat == srcFormat
6581 && mSrcChannelMask == srcChannelMask
6582 && mSrcSampleRate == srcSampleRate
6583 && mDstFormat == dstFormat
6584 && mDstChannelMask == dstChannelMask
6585 && mDstSampleRate == dstSampleRate) {
6586 return NO_ERROR;
6587 }
6588
Andy Hungdb4c0312015-05-06 08:46:52 -07006589 ALOGV("RecordBufferConverter updateParameters srcMask:%#x dstMask:%#x"
6590 " srcFormat:%#x dstFormat:%#x srcRate:%u dstRate:%u",
6591 srcChannelMask, dstChannelMask, srcFormat, dstFormat, srcSampleRate, dstSampleRate);
Andy Hung97a893e2015-03-29 01:03:07 -07006592 const bool valid =
6593 audio_is_input_channel(srcChannelMask)
6594 && audio_is_input_channel(dstChannelMask)
6595 && audio_is_valid_format(srcFormat) && audio_is_linear_pcm(srcFormat)
6596 && audio_is_valid_format(dstFormat) && audio_is_linear_pcm(dstFormat)
6597 && (srcSampleRate <= dstSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX)
6598 ; // no upsampling checks for now
6599 if (!valid) {
6600 return BAD_VALUE;
6601 }
6602
6603 mSrcFormat = srcFormat;
6604 mSrcChannelMask = srcChannelMask;
6605 mSrcSampleRate = srcSampleRate;
6606 mDstFormat = dstFormat;
6607 mDstChannelMask = dstChannelMask;
6608 mDstSampleRate = dstSampleRate;
6609
6610 // compute derived parameters
6611 mSrcChannelCount = audio_channel_count_from_in_mask(srcChannelMask);
6612 mDstChannelCount = audio_channel_count_from_in_mask(dstChannelMask);
6613 mDstFrameSize = mDstChannelCount * audio_bytes_per_sample(mDstFormat);
6614
Andy Hungd330ee42015-04-20 13:23:41 -07006615 // do we need to resample?
6616 delete mResampler;
6617 mResampler = NULL;
6618 if (mSrcSampleRate != mDstSampleRate) {
6619 mResampler = AudioResampler::create(AUDIO_FORMAT_PCM_FLOAT,
6620 mSrcChannelCount, mDstSampleRate);
6621 mResampler->setSampleRate(mSrcSampleRate);
6622 mResampler->setVolume(AudioMixer::UNITY_GAIN_FLOAT, AudioMixer::UNITY_GAIN_FLOAT);
6623 }
6624
6625 // are we running legacy channel conversion modes?
6626 mIsLegacyDownmix = (mSrcChannelMask == AUDIO_CHANNEL_IN_STEREO
6627 || mSrcChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK)
6628 && mDstChannelMask == AUDIO_CHANNEL_IN_MONO;
6629 mIsLegacyUpmix = mSrcChannelMask == AUDIO_CHANNEL_IN_MONO
6630 && (mDstChannelMask == AUDIO_CHANNEL_IN_STEREO
6631 || mDstChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK);
6632
6633 // do we need to process in float?
6634 mRequiresFloat = mResampler != NULL || mIsLegacyDownmix || mIsLegacyUpmix;
6635
6636 // do we need a staging buffer to convert for destination (we can still optimize this)?
6637 // we use mBufFrameSize > 0 to indicate both frame size as well as buffer necessity
6638 if (mResampler != NULL) {
6639 mBufFrameSize = max(mSrcChannelCount, FCC_2)
6640 * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
6641 } else if ((mIsLegacyUpmix || mIsLegacyDownmix) && mDstFormat != AUDIO_FORMAT_PCM_FLOAT) {
6642 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
6643 } else if (mSrcChannelMask != mDstChannelMask && mDstFormat != mSrcFormat) {
Andy Hung97a893e2015-03-29 01:03:07 -07006644 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(mSrcFormat);
6645 } else {
6646 mBufFrameSize = 0;
6647 }
6648 mBufFrames = 0; // force the buffer to be resized.
6649
Andy Hungd330ee42015-04-20 13:23:41 -07006650 // do we need an input converter buffer provider to give us float?
6651 delete mInputConverterProvider;
6652 mInputConverterProvider = NULL;
6653 if (mRequiresFloat && mSrcFormat != AUDIO_FORMAT_PCM_FLOAT) {
6654 mInputConverterProvider = new ReformatBufferProvider(
6655 audio_channel_count_from_in_mask(mSrcChannelMask),
6656 mSrcFormat,
6657 AUDIO_FORMAT_PCM_FLOAT,
6658 256 /* provider buffer frame count */);
6659 }
6660
6661 // do we need a remixer to do channel mask conversion
6662 if (!mIsLegacyDownmix && !mIsLegacyUpmix && mSrcChannelMask != mDstChannelMask) {
6663 (void) memcpy_by_index_array_initialization_from_channel_mask(
6664 mIdxAry, ARRAY_SIZE(mIdxAry), mDstChannelMask, mSrcChannelMask);
Andy Hung97a893e2015-03-29 01:03:07 -07006665 }
6666 return NO_ERROR;
6667}
6668
Andy Hungd330ee42015-04-20 13:23:41 -07006669void AudioFlinger::RecordThread::RecordBufferConverter::convertNoResampler(
6670 void *dst, const void *src, size_t frames)
Andy Hung97a893e2015-03-29 01:03:07 -07006671{
Andy Hungd330ee42015-04-20 13:23:41 -07006672 // src is native type unless there is legacy upmix or downmix, whereupon it is float.
Andy Hung97a893e2015-03-29 01:03:07 -07006673 if (mBufFrameSize != 0 && mBufFrames < frames) {
6674 free(mBuf);
6675 mBufFrames = frames;
6676 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
6677 }
Andy Hungd330ee42015-04-20 13:23:41 -07006678 // do we need to do legacy upmix and downmix?
6679 if (mIsLegacyUpmix || mIsLegacyDownmix) {
Andy Hung97a893e2015-03-29 01:03:07 -07006680 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07006681 if (mIsLegacyUpmix) {
6682 upmix_to_stereo_float_from_mono_float((float *)dstBuf,
6683 (const float *)src, frames);
6684 } else /*mIsLegacyDownmix */ {
6685 downmix_to_mono_float_from_stereo_float((float *)dstBuf,
6686 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006687 }
Andy Hungd330ee42015-04-20 13:23:41 -07006688 if (mBuf != NULL) {
6689 memcpy_by_audio_format(dst, mDstFormat, mBuf, AUDIO_FORMAT_PCM_FLOAT,
6690 frames * mDstChannelCount);
6691 }
6692 return;
6693 }
6694 // do we need to do channel mask conversion?
6695 if (mSrcChannelMask != mDstChannelMask) {
Andy Hung97a893e2015-03-29 01:03:07 -07006696 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07006697 memcpy_by_index_array(dstBuf, mDstChannelCount,
6698 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mSrcFormat), frames);
6699 if (dstBuf == dst) {
6700 return; // format is the same
6701 }
6702 }
6703 // convert to destination buffer
6704 const void *convertBuf = mBuf != NULL ? mBuf : src;
6705 memcpy_by_audio_format(dst, mDstFormat, convertBuf, mSrcFormat,
6706 frames * mDstChannelCount);
6707}
6708
6709void AudioFlinger::RecordThread::RecordBufferConverter::convertResampler(
6710 void *dst, /*not-a-const*/ void *src, size_t frames)
6711{
6712 // src buffer format is ALWAYS float when entering this routine
6713 if (mIsLegacyUpmix) {
6714 ; // mono to stereo already handled by resampler
6715 } else if (mIsLegacyDownmix
6716 || (mSrcChannelMask == mDstChannelMask && mSrcChannelCount == 1)) {
6717 // the resampler outputs stereo for mono input channel (a feature?)
6718 // must convert to mono
6719 downmix_to_mono_float_from_stereo_float((float *)src,
6720 (const float *)src, frames);
6721 } else if (mSrcChannelMask != mDstChannelMask) {
6722 // convert to mono channel again for channel mask conversion (could be skipped
6723 // with further optimization).
Andy Hung97a893e2015-03-29 01:03:07 -07006724 if (mSrcChannelCount == 1) {
Andy Hungd330ee42015-04-20 13:23:41 -07006725 downmix_to_mono_float_from_stereo_float((float *)src,
6726 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006727 }
Andy Hungd330ee42015-04-20 13:23:41 -07006728 // convert to destination format (in place, OK as float is larger than other types)
6729 if (mDstFormat != AUDIO_FORMAT_PCM_FLOAT) {
6730 memcpy_by_audio_format(src, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
6731 frames * mSrcChannelCount);
6732 }
6733 // channel convert and save to dst
6734 memcpy_by_index_array(dst, mDstChannelCount,
6735 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mDstFormat), frames);
6736 return;
Andy Hung97a893e2015-03-29 01:03:07 -07006737 }
Andy Hungd330ee42015-04-20 13:23:41 -07006738 // convert to destination format and save to dst
6739 memcpy_by_audio_format(dst, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
6740 frames * mDstChannelCount);
Andy Hung97a893e2015-03-29 01:03:07 -07006741}
6742
Eric Laurent10351942014-05-08 18:49:52 -07006743bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
6744 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006745{
6746 bool reconfig = false;
6747
Eric Laurent10351942014-05-08 18:49:52 -07006748 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006749
Eric Laurent10351942014-05-08 18:49:52 -07006750 audio_format_t reqFormat = mFormat;
6751 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07006752 // 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 -07006753 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
6754
6755 AudioParameter param = AudioParameter(keyValuePair);
6756 int value;
6757 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
6758 // channel count change can be requested. Do we mandate the first client defines the
6759 // HAL sampling rate and channel count or do we allow changes on the fly?
6760 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6761 samplingRate = value;
6762 reconfig = true;
6763 }
6764 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07006765 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07006766 status = BAD_VALUE;
6767 } else {
6768 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08006769 reconfig = true;
6770 }
Eric Laurent10351942014-05-08 18:49:52 -07006771 }
6772 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
6773 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07006774 if (!audio_is_input_channel(mask) ||
6775 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07006776 status = BAD_VALUE;
6777 } else {
6778 channelMask = mask;
6779 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006780 }
Eric Laurent10351942014-05-08 18:49:52 -07006781 }
6782 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6783 // do not accept frame count changes if tracks are open as the track buffer
6784 // size depends on frame count and correct behavior would not be guaranteed
6785 // if frame count is changed after track creation
6786 if (mActiveTracks.size() > 0) {
6787 status = INVALID_OPERATION;
6788 } else {
6789 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006790 }
Eric Laurent10351942014-05-08 18:49:52 -07006791 }
6792 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6793 // forward device change to effects that have requested to be
6794 // aware of attached audio device.
6795 for (size_t i = 0; i < mEffectChains.size(); i++) {
6796 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08006797 }
Eric Laurent81784c32012-11-19 14:55:58 -08006798
Eric Laurent10351942014-05-08 18:49:52 -07006799 // store input device and output device but do not forward output device to audio HAL.
6800 // Note that status is ignored by the caller for output device
6801 // (see AudioFlinger::setParameters()
6802 if (audio_is_output_devices(value)) {
6803 mOutDevice = value;
6804 status = BAD_VALUE;
6805 } else {
6806 mInDevice = value;
Eric Laurente8726fe2015-06-26 09:39:24 -07006807 if (value != AUDIO_DEVICE_NONE) {
6808 mPrevInDevice = value;
6809 }
Eric Laurent10351942014-05-08 18:49:52 -07006810 // disable AEC and NS if the device is a BT SCO headset supporting those
6811 // pre processings
6812 if (mTracks.size() > 0) {
6813 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6814 mAudioFlinger->btNrecIsOff();
6815 for (size_t i = 0; i < mTracks.size(); i++) {
6816 sp<RecordTrack> track = mTracks[i];
6817 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
6818 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08006819 }
6820 }
6821 }
Eric Laurent10351942014-05-08 18:49:52 -07006822 }
6823 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
6824 mAudioSource != (audio_source_t)value) {
6825 // forward device change to effects that have requested to be
6826 // aware of attached audio device.
6827 for (size_t i = 0; i < mEffectChains.size(); i++) {
6828 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08006829 }
Eric Laurent10351942014-05-08 18:49:52 -07006830 mAudioSource = (audio_source_t)value;
6831 }
Glenn Kastene198c362013-08-13 09:13:36 -07006832
Eric Laurent10351942014-05-08 18:49:52 -07006833 if (status == NO_ERROR) {
6834 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6835 keyValuePair.string());
6836 if (status == INVALID_OPERATION) {
6837 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006838 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6839 keyValuePair.string());
Eric Laurent10351942014-05-08 18:49:52 -07006840 }
6841 if (reconfig) {
6842 if (status == BAD_VALUE &&
Andy Hung97a893e2015-03-29 01:03:07 -07006843 audio_is_linear_pcm(mInput->stream->common.get_format(&mInput->stream->common)) &&
6844 audio_is_linear_pcm(reqFormat) &&
Eric Laurent10351942014-05-08 18:49:52 -07006845 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
Andy Hung97a893e2015-03-29 01:03:07 -07006846 <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate)) &&
Andy Hunge5412692014-05-16 11:25:07 -07006847 audio_channel_count_from_in_mask(
Andy Hungd1abb8f2015-05-05 23:42:34 -07006848 mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07006849 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006850 }
Eric Laurent10351942014-05-08 18:49:52 -07006851 if (status == NO_ERROR) {
6852 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07006853 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08006854 }
6855 }
Eric Laurent81784c32012-11-19 14:55:58 -08006856 }
Eric Laurent10351942014-05-08 18:49:52 -07006857
Eric Laurent81784c32012-11-19 14:55:58 -08006858 return reconfig;
6859}
6860
6861String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6862{
Eric Laurent81784c32012-11-19 14:55:58 -08006863 Mutex::Autolock _l(mLock);
6864 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07006865 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08006866 }
6867
Glenn Kastend8ea6992013-07-16 14:17:15 -07006868 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
6869 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08006870 free(s);
6871 return out_s8;
6872}
6873
Eric Laurent73e26b62015-04-27 16:55:58 -07006874void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event) {
6875 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
6876
6877 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08006878
6879 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07006880 case AUDIO_INPUT_OPENED:
6881 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07006882 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07006883 desc->mChannelMask = mChannelMask;
6884 desc->mSamplingRate = mSampleRate;
6885 desc->mFormat = mFormat;
6886 desc->mFrameCount = mFrameCount;
6887 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006888 break;
6889
Eric Laurent73e26b62015-04-27 16:55:58 -07006890 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08006891 default:
6892 break;
6893 }
Eric Laurent73e26b62015-04-27 16:55:58 -07006894 mAudioFlinger->ioConfigChanged(event, desc);
Eric Laurent81784c32012-11-19 14:55:58 -08006895}
6896
Glenn Kastendeca2ae2014-02-07 10:25:56 -08006897void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006898{
Eric Laurent81784c32012-11-19 14:55:58 -08006899 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
6900 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Andy Hunge5412692014-05-16 11:25:07 -07006901 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Andy Hungd330ee42015-04-20 13:23:41 -07006902 if (mChannelCount > FCC_8) {
6903 ALOGE("HAL channel count %d > %d", mChannelCount, FCC_8);
6904 }
Andy Hung463be252014-07-10 16:56:07 -07006905 mHALFormat = mInput->stream->common.get_format(&mInput->stream->common);
6906 mFormat = mHALFormat;
Andy Hungd330ee42015-04-20 13:23:41 -07006907 if (!audio_is_linear_pcm(mFormat)) {
6908 ALOGE("HAL format %#x is not linear pcm", mFormat);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07006909 }
Eric Laurent665470b2014-07-03 16:37:08 -07006910 mFrameSize = audio_stream_in_frame_size(mInput->stream);
Glenn Kasten548efc92012-11-29 08:48:51 -08006911 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
6912 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006913 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08006914 // 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 -07006915 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08006916 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006917 // A larger value should allow more old data to be read after a track calls start(),
6918 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07006919 //
6920 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08006921 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07006922 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07006923 free(mRsmpInBuffer);
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006924
6925 // TODO optimize audio capture buffer sizes ...
6926 // Here we calculate the size of the sliding buffer used as a source
6927 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
6928 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
6929 // be better to have it derived from the pipe depth in the long term.
6930 // The current value is higher than necessary. However it should not add to latency.
6931
Glenn Kasten85948432013-08-19 12:09:05 -07006932 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Andy Hung57446612015-04-19 23:56:46 -07006933 (void)posix_memalign(&mRsmpInBuffer, 32, (mRsmpInFramesP2 + mFrameCount - 1) * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006934
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006935 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
6936 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08006937}
6938
Glenn Kasten5f972c02014-01-13 09:59:31 -08006939uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08006940{
6941 Mutex::Autolock _l(mLock);
6942 if (initCheck() != NO_ERROR) {
6943 return 0;
6944 }
6945
6946 return mInput->stream->get_input_frames_lost(mInput->stream);
6947}
6948
6949uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
6950{
6951 Mutex::Autolock _l(mLock);
6952 uint32_t result = 0;
6953 if (getEffectChain_l(sessionId) != 0) {
6954 result = EFFECT_SESSION;
6955 }
6956
6957 for (size_t i = 0; i < mTracks.size(); ++i) {
6958 if (sessionId == mTracks[i]->sessionId()) {
6959 result |= TRACK_SESSION;
6960 break;
6961 }
6962 }
6963
6964 return result;
6965}
6966
6967KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
6968{
6969 KeyedVector<int, bool> ids;
6970 Mutex::Autolock _l(mLock);
6971 for (size_t j = 0; j < mTracks.size(); ++j) {
6972 sp<RecordThread::RecordTrack> track = mTracks[j];
6973 int sessionId = track->sessionId();
6974 if (ids.indexOfKey(sessionId) < 0) {
6975 ids.add(sessionId, true);
6976 }
6977 }
6978 return ids;
6979}
6980
6981AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
6982{
6983 Mutex::Autolock _l(mLock);
6984 AudioStreamIn *input = mInput;
6985 mInput = NULL;
6986 return input;
6987}
6988
6989// this method must always be called either with ThreadBase mLock held or inside the thread loop
6990audio_stream_t* AudioFlinger::RecordThread::stream() const
6991{
6992 if (mInput == NULL) {
6993 return NULL;
6994 }
6995 return &mInput->stream->common;
6996}
6997
6998status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6999{
7000 // only one chain per input thread
7001 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07007002 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08007003 return INVALID_OPERATION;
7004 }
7005 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07007006 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08007007 chain->setInBuffer(NULL);
7008 chain->setOutBuffer(NULL);
7009
7010 checkSuspendOnAddEffectChain_l(chain);
7011
Eric Laurent1b928682014-10-02 19:41:47 -07007012 // make sure enabled pre processing effects state is communicated to the HAL as we
7013 // just moved them to a new input stream.
7014 chain->syncHalEffectsState();
7015
Eric Laurent81784c32012-11-19 14:55:58 -08007016 mEffectChains.add(chain);
7017
7018 return NO_ERROR;
7019}
7020
7021size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7022{
7023 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
7024 ALOGW_IF(mEffectChains.size() != 1,
7025 "removeEffectChain_l() %p invalid chain size %d on thread %p",
7026 chain.get(), mEffectChains.size(), this);
7027 if (mEffectChains.size() == 1) {
7028 mEffectChains.removeAt(0);
7029 }
7030 return 0;
7031}
7032
Eric Laurent1c333e22014-05-20 10:48:17 -07007033status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
7034 audio_patch_handle_t *handle)
7035{
7036 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007037
7038 // store new device and send to effects
7039 mInDevice = patch->sources[0].ext.device.type;
Eric Laurent296fb132015-05-01 11:38:42 -07007040 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07007041 for (size_t i = 0; i < mEffectChains.size(); i++) {
7042 mEffectChains[i]->setDevice_l(mInDevice);
7043 }
7044
7045 // disable AEC and NS if the device is a BT SCO headset supporting those
7046 // pre processings
7047 if (mTracks.size() > 0) {
7048 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7049 mAudioFlinger->btNrecIsOff();
7050 for (size_t i = 0; i < mTracks.size(); i++) {
7051 sp<RecordTrack> track = mTracks[i];
7052 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7053 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
7054 }
7055 }
7056
7057 // store new source and send to effects
7058 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7059 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07007060 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07007061 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07007062 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007063 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007064
Eric Laurent054d9d32015-04-24 08:48:48 -07007065 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007066 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
7067 status = hwDevice->create_audio_patch(hwDevice,
7068 patch->num_sources,
7069 patch->sources,
7070 patch->num_sinks,
7071 patch->sinks,
7072 handle);
7073 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007074 char *address;
7075 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
7076 address = audio_device_address_to_parameter(
7077 patch->sources[0].ext.device.type,
7078 patch->sources[0].ext.device.address);
7079 } else {
7080 address = (char *)calloc(1, 1);
7081 }
7082 AudioParameter param = AudioParameter(String8(address));
7083 free(address);
7084 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING),
7085 (int)patch->sources[0].ext.device.type);
7086 param.addInt(String8(AUDIO_PARAMETER_STREAM_INPUT_SOURCE),
7087 (int)patch->sinks[0].ext.mix.usecase.source);
7088 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7089 param.toString().string());
7090 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07007091 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007092
Eric Laurente8726fe2015-06-26 09:39:24 -07007093 if (mInDevice != mPrevInDevice) {
7094 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
7095 mPrevInDevice = mInDevice;
7096 }
Eric Laurent296fb132015-05-01 11:38:42 -07007097
Eric Laurent1c333e22014-05-20 10:48:17 -07007098 return status;
7099}
7100
7101status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
7102{
7103 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007104
7105 mInDevice = AUDIO_DEVICE_NONE;
7106
Eric Laurent1c333e22014-05-20 10:48:17 -07007107 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
7108 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
7109 status = hwDevice->release_audio_patch(hwDevice, handle);
7110 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007111 AudioParameter param;
7112 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
7113 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7114 param.toString().string());
Eric Laurent1c333e22014-05-20 10:48:17 -07007115 }
7116 return status;
7117}
7118
Eric Laurent83b88082014-06-20 18:31:16 -07007119void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
7120{
7121 Mutex::Autolock _l(mLock);
7122 mTracks.add(record);
7123}
7124
7125void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
7126{
7127 Mutex::Autolock _l(mLock);
7128 destroyTrack_l(record);
7129}
7130
7131void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
7132{
7133 ThreadBase::getAudioPortConfig(config);
7134 config->role = AUDIO_PORT_ROLE_SINK;
7135 config->ext.mix.hw_module = mInput->audioHwDev->handle();
7136 config->ext.mix.usecase.source = mAudioSource;
7137}
Eric Laurent1c333e22014-05-20 10:48:17 -07007138
Glenn Kasten63238ef2015-03-02 15:50:29 -08007139} // namespace android