blob: 0bcdf8d7b0ace8e350cb72d3fc36a1f87f5bf0f0 [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",
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800378 AUDIO_DEVICE_NONE, "NONE", // must be last
379 }, mappingsIn[] = {
Glenn Kasten84d61ca2015-05-06 18:32:13 -0700380 AUDIO_DEVICE_IN_COMMUNICATION, "COMMUNICATION",
381 AUDIO_DEVICE_IN_AMBIENT, "AMBIENT",
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800382 AUDIO_DEVICE_IN_BUILTIN_MIC, "BUILTIN_MIC",
Glenn Kasten84d61ca2015-05-06 18:32:13 -0700383 AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET, "BLUETOOTH_SCO_HEADSET",
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800384 AUDIO_DEVICE_IN_WIRED_HEADSET, "WIRED_HEADSET",
Glenn Kasten84d61ca2015-05-06 18:32:13 -0700385 AUDIO_DEVICE_IN_AUX_DIGITAL, "AUX_DIGITAL",
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800386 AUDIO_DEVICE_IN_VOICE_CALL, "VOICE_CALL",
Glenn Kasten84d61ca2015-05-06 18:32:13 -0700387 AUDIO_DEVICE_IN_TELEPHONY_RX, "TELEPHONY_RX",
388 AUDIO_DEVICE_IN_BACK_MIC, "BACK_MIC",
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800389 AUDIO_DEVICE_IN_REMOTE_SUBMIX, "REMOTE_SUBMIX",
Glenn Kasten84d61ca2015-05-06 18:32:13 -0700390 AUDIO_DEVICE_IN_ANLG_DOCK_HEADSET, "ANLG_DOCK_HEADSET",
391 AUDIO_DEVICE_IN_DGTL_DOCK_HEADSET, "DGTL_DOCK_HEADSET",
392 AUDIO_DEVICE_IN_USB_ACCESSORY, "USB_ACCESSORY",
393 AUDIO_DEVICE_IN_USB_DEVICE, "USB_DEVICE",
394 AUDIO_DEVICE_IN_FM_TUNER, "FM_TUNER",
395 AUDIO_DEVICE_IN_TV_TUNER, "TV_TUNER",
396 AUDIO_DEVICE_IN_LINE, "LINE",
397 AUDIO_DEVICE_IN_SPDIF, "SPDIF",
398 AUDIO_DEVICE_IN_BLUETOOTH_A2DP, "BLUETOOTH_A2DP",
399 AUDIO_DEVICE_IN_LOOPBACK, "LOOPBACK",
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800400 AUDIO_DEVICE_NONE, "NONE", // must be last
401 };
402 String8 result;
403 audio_devices_t allDevices = AUDIO_DEVICE_NONE;
404 const mapping *entry;
405 if (devices & AUDIO_DEVICE_BIT_IN) {
406 devices &= ~AUDIO_DEVICE_BIT_IN;
407 entry = mappingsIn;
408 } else {
409 entry = mappingsOut;
410 }
411 for ( ; entry->mDevices != AUDIO_DEVICE_NONE; entry++) {
412 allDevices = (audio_devices_t) (allDevices | entry->mDevices);
413 if (devices & entry->mDevices) {
414 if (!result.isEmpty()) {
415 result.append("|");
416 }
417 result.append(entry->mString);
418 }
419 }
420 if (devices & ~allDevices) {
421 if (!result.isEmpty()) {
422 result.append("|");
423 }
424 result.appendFormat("0x%X", devices & ~allDevices);
425 }
426 if (result.isEmpty()) {
427 result.append(entry->mString);
428 }
429 return result;
430}
431
432String8 inputFlagsToString(audio_input_flags_t flags)
433{
434 static const struct mapping {
435 audio_input_flags_t mFlag;
436 const char * mString;
437 } mappings[] = {
438 AUDIO_INPUT_FLAG_FAST, "FAST",
439 AUDIO_INPUT_FLAG_HW_HOTWORD, "HW_HOTWORD",
440 AUDIO_INPUT_FLAG_NONE, "NONE", // must be last
441 };
442 String8 result;
443 audio_input_flags_t allFlags = AUDIO_INPUT_FLAG_NONE;
444 const mapping *entry;
445 for (entry = mappings; entry->mFlag != AUDIO_INPUT_FLAG_NONE; entry++) {
446 allFlags = (audio_input_flags_t) (allFlags | entry->mFlag);
447 if (flags & entry->mFlag) {
448 if (!result.isEmpty()) {
449 result.append("|");
450 }
451 result.append(entry->mString);
452 }
453 }
454 if (flags & ~allFlags) {
455 if (!result.isEmpty()) {
456 result.append("|");
457 }
458 result.appendFormat("0x%X", flags & ~allFlags);
459 }
460 if (result.isEmpty()) {
461 result.append(entry->mString);
462 }
463 return result;
464}
465
466String8 outputFlagsToString(audio_output_flags_t flags)
Glenn Kasten97b7b752014-09-28 13:04:24 -0700467{
468 static const struct mapping {
469 audio_output_flags_t mFlag;
470 const char * mString;
471 } mappings[] = {
472 AUDIO_OUTPUT_FLAG_DIRECT, "DIRECT",
473 AUDIO_OUTPUT_FLAG_PRIMARY, "PRIMARY",
474 AUDIO_OUTPUT_FLAG_FAST, "FAST",
475 AUDIO_OUTPUT_FLAG_DEEP_BUFFER, "DEEP_BUFFER",
Glenn Kastendfb0e112015-02-18 14:33:39 -0800476 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD, "COMPRESS_OFFLOAD",
Glenn Kasten97b7b752014-09-28 13:04:24 -0700477 AUDIO_OUTPUT_FLAG_NON_BLOCKING, "NON_BLOCKING",
478 AUDIO_OUTPUT_FLAG_HW_AV_SYNC, "HW_AV_SYNC",
479 AUDIO_OUTPUT_FLAG_NONE, "NONE", // must be last
480 };
481 String8 result;
482 audio_output_flags_t allFlags = AUDIO_OUTPUT_FLAG_NONE;
483 const mapping *entry;
484 for (entry = mappings; entry->mFlag != AUDIO_OUTPUT_FLAG_NONE; entry++) {
485 allFlags = (audio_output_flags_t) (allFlags | entry->mFlag);
486 if (flags & entry->mFlag) {
487 if (!result.isEmpty()) {
488 result.append("|");
489 }
490 result.append(entry->mString);
491 }
492 }
493 if (flags & ~allFlags) {
494 if (!result.isEmpty()) {
495 result.append("|");
496 }
497 result.appendFormat("0x%X", flags & ~allFlags);
498 }
499 if (result.isEmpty()) {
500 result.append(entry->mString);
501 }
502 return result;
503}
504
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800505const char *sourceToString(audio_source_t source)
506{
507 switch (source) {
508 case AUDIO_SOURCE_DEFAULT: return "default";
509 case AUDIO_SOURCE_MIC: return "mic";
510 case AUDIO_SOURCE_VOICE_UPLINK: return "voice uplink";
511 case AUDIO_SOURCE_VOICE_DOWNLINK: return "voice downlink";
512 case AUDIO_SOURCE_VOICE_CALL: return "voice call";
513 case AUDIO_SOURCE_CAMCORDER: return "camcorder";
514 case AUDIO_SOURCE_VOICE_RECOGNITION: return "voice recognition";
515 case AUDIO_SOURCE_VOICE_COMMUNICATION: return "voice communication";
516 case AUDIO_SOURCE_REMOTE_SUBMIX: return "remote submix";
517 case AUDIO_SOURCE_FM_TUNER: return "FM tuner";
518 case AUDIO_SOURCE_HOTWORD: return "hotword";
519 default: return "unknown";
520 }
521}
522
Eric Laurent81784c32012-11-19 14:55:58 -0800523AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -0700524 audio_devices_t outDevice, audio_devices_t inDevice, type_t type, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -0800525 : Thread(false /*canCallJava*/),
526 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700527 mAudioFlinger(audioFlinger),
Glenn Kasten70949c42013-08-06 07:40:12 -0700528 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800529 // are set by PlaybackThread::readOutputParameters_l() or
530 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700531 //FIXME: mStandby should be true here. Is this some kind of hack?
Eric Laurent81784c32012-11-19 14:55:58 -0800532 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
533 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
534 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700535 mDeathRecipient(new PMDeathRecipient(this)),
536 mSystemReady(systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -0800537{
Eric Laurent296fb132015-05-01 11:38:42 -0700538 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800539}
540
541AudioFlinger::ThreadBase::~ThreadBase()
542{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700543 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700544 mConfigEvents.clear();
545
Eric Laurent81784c32012-11-19 14:55:58 -0800546 // do not lock the mutex in destructor
547 releaseWakeLock_l();
548 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800549 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800550 binder->unlinkToDeath(mDeathRecipient);
551 }
552}
553
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700554status_t AudioFlinger::ThreadBase::readyToRun()
555{
556 status_t status = initCheck();
557 if (status == NO_ERROR) {
558 ALOGI("AudioFlinger's thread %p ready to run", this);
559 } else {
560 ALOGE("No working audio driver found.");
561 }
562 return status;
563}
564
Eric Laurent81784c32012-11-19 14:55:58 -0800565void AudioFlinger::ThreadBase::exit()
566{
567 ALOGV("ThreadBase::exit");
568 // do any cleanup required for exit to succeed
569 preExit();
570 {
571 // This lock prevents the following race in thread (uniprocessor for illustration):
572 // if (!exitPending()) {
573 // // context switch from here to exit()
574 // // exit() calls requestExit(), what exitPending() observes
575 // // exit() calls signal(), which is dropped since no waiters
576 // // context switch back from exit() to here
577 // mWaitWorkCV.wait(...);
578 // // now thread is hung
579 // }
580 AutoMutex lock(mLock);
581 requestExit();
582 mWaitWorkCV.broadcast();
583 }
584 // When Thread::requestExitAndWait is made virtual and this method is renamed to
585 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
586 requestExitAndWait();
587}
588
589status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
590{
591 status_t status;
592
593 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
594 Mutex::Autolock _l(mLock);
595
Eric Laurent10351942014-05-08 18:49:52 -0700596 return sendSetParameterConfigEvent_l(keyValuePairs);
597}
598
599// sendConfigEvent_l() must be called with ThreadBase::mLock held
600// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
601status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
602{
603 status_t status = NO_ERROR;
604
Eric Laurent72e3f392015-05-20 14:43:50 -0700605 if (event->mRequiresSystemReady && !mSystemReady) {
606 event->mWaitStatus = false;
607 mPendingConfigEvents.add(event);
608 return status;
609 }
Eric Laurent10351942014-05-08 18:49:52 -0700610 mConfigEvents.add(event);
611 ALOGV("sendConfigEvent_l() num events %d event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800612 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700613 mLock.unlock();
614 {
615 Mutex::Autolock _l(event->mLock);
616 while (event->mWaitStatus) {
617 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
618 event->mStatus = TIMED_OUT;
619 event->mWaitStatus = false;
620 }
621 }
622 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800623 }
Eric Laurent10351942014-05-08 18:49:52 -0700624 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800625 return status;
626}
627
Eric Laurent73e26b62015-04-27 16:55:58 -0700628void AudioFlinger::ThreadBase::sendIoConfigEvent(audio_io_config_event event)
Eric Laurent81784c32012-11-19 14:55:58 -0800629{
630 Mutex::Autolock _l(mLock);
Eric Laurent73e26b62015-04-27 16:55:58 -0700631 sendIoConfigEvent_l(event);
Eric Laurent81784c32012-11-19 14:55:58 -0800632}
633
634// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
Eric Laurent73e26b62015-04-27 16:55:58 -0700635void AudioFlinger::ThreadBase::sendIoConfigEvent_l(audio_io_config_event event)
Eric Laurent81784c32012-11-19 14:55:58 -0800636{
Eric Laurent73e26b62015-04-27 16:55:58 -0700637 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event);
Eric Laurent10351942014-05-08 18:49:52 -0700638 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800639}
640
Eric Laurent72e3f392015-05-20 14:43:50 -0700641void AudioFlinger::ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio)
642{
643 Mutex::Autolock _l(mLock);
644 sendPrioConfigEvent_l(pid, tid, prio);
645}
646
Eric Laurent81784c32012-11-19 14:55:58 -0800647// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
648void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
649{
Eric Laurent10351942014-05-08 18:49:52 -0700650 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio);
651 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800652}
653
Eric Laurent10351942014-05-08 18:49:52 -0700654// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
655status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800656{
Eric Laurent10351942014-05-08 18:49:52 -0700657 sp<ConfigEvent> configEvent = (ConfigEvent *)new SetParameterConfigEvent(keyValuePair);
658 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700659}
660
Eric Laurent1c333e22014-05-20 10:48:17 -0700661status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
662 const struct audio_patch *patch,
663 audio_patch_handle_t *handle)
664{
665 Mutex::Autolock _l(mLock);
666 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
667 status_t status = sendConfigEvent_l(configEvent);
668 if (status == NO_ERROR) {
669 CreateAudioPatchConfigEventData *data =
670 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
671 *handle = data->mHandle;
672 }
673 return status;
674}
675
676status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
677 const audio_patch_handle_t handle)
678{
679 Mutex::Autolock _l(mLock);
680 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
681 return sendConfigEvent_l(configEvent);
682}
683
684
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700685// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700686void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700687{
Eric Laurent10351942014-05-08 18:49:52 -0700688 bool configChanged = false;
689
Eric Laurent81784c32012-11-19 14:55:58 -0800690 while (!mConfigEvents.isEmpty()) {
Eric Laurent10351942014-05-08 18:49:52 -0700691 ALOGV("processConfigEvents_l() remaining events %d", mConfigEvents.size());
692 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800693 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700694 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700695 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700696 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
697 // FIXME Need to understand why this has to be done asynchronously
698 int err = requestPriority(data->mPid, data->mTid, data->mPrio,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700699 true /*asynchronous*/);
700 if (err != 0) {
701 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700702 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700703 }
704 } break;
705 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700706 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent73e26b62015-04-27 16:55:58 -0700707 ioConfigChanged(data->mEvent);
Eric Laurent10351942014-05-08 18:49:52 -0700708 } break;
709 case CFG_EVENT_SET_PARAMETER: {
710 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
711 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
712 configChanged = true;
Glenn Kastend5418eb2013-08-14 13:11:06 -0700713 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700714 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700715 case CFG_EVENT_CREATE_AUDIO_PATCH: {
716 CreateAudioPatchConfigEventData *data =
717 (CreateAudioPatchConfigEventData *)event->mData.get();
718 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
719 } break;
720 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
721 ReleaseAudioPatchConfigEventData *data =
722 (ReleaseAudioPatchConfigEventData *)event->mData.get();
723 event->mStatus = releaseAudioPatch_l(data->mHandle);
724 } break;
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700725 default:
Eric Laurent10351942014-05-08 18:49:52 -0700726 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700727 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800728 }
Eric Laurent10351942014-05-08 18:49:52 -0700729 {
730 Mutex::Autolock _l(event->mLock);
731 if (event->mWaitStatus) {
732 event->mWaitStatus = false;
733 event->mCond.signal();
734 }
735 }
736 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
737 }
738
739 if (configChanged) {
740 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800741 }
Eric Laurent81784c32012-11-19 14:55:58 -0800742}
743
Marco Nelissenb2208842014-02-07 14:00:50 -0800744String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
745 String8 s;
Andy Hungf98ec8d2015-05-19 12:53:24 -0700746 const audio_channel_representation_t representation = audio_channel_mask_get_representation(mask);
747
748 switch (representation) {
749 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
750 if (output) {
751 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
752 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
753 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
754 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
755 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
756 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
757 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
758 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
759 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
760 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
761 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
762 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
763 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
764 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
765 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
766 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
767 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
768 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
769 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
770 } else {
771 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
772 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
773 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
774 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
775 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
776 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
777 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
778 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
779 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
780 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
781 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
782 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
783 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
784 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
785 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
786 }
787 const int len = s.length();
788 if (len > 2) {
789 char *str = s.lockBuffer(len); // needed?
790 s.unlockBuffer(len - 2); // remove trailing ", "
791 }
792 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800793 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700794 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
795 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
796 return s;
797 default:
798 s.appendFormat("unknown mask, representation:%d bits:%#x",
799 representation, audio_channel_mask_get_bits(mask));
800 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800801 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800802}
803
Glenn Kasten0f11b512014-01-31 16:18:54 -0800804void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800805{
806 const size_t SIZE = 256;
807 char buffer[SIZE];
808 String8 result;
809
810 bool locked = AudioFlinger::dumpTryLock(mLock);
811 if (!locked) {
Glenn Kasten97b7b752014-09-28 13:04:24 -0700812 dprintf(fd, "thread %p may be deadlocked\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -0800813 }
814
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800815 dprintf(fd, " Thread name: %s\n", mThreadName);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700816 dprintf(fd, " I/O handle: %d\n", mId);
817 dprintf(fd, " TID: %d\n", getTid());
818 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700819 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700820 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700821 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat));
Elliott Hughes87cebad2014-05-22 10:14:43 -0700822 dprintf(fd, " HAL buffer size: %u bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700823 dprintf(fd, " Channel count: %u\n", mChannelCount);
824 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800825 channelMaskToString(mChannelMask, mType != RECORD).string());
Glenn Kasten97b7b752014-09-28 13:04:24 -0700826 dprintf(fd, " Format: 0x%x (%s)\n", mFormat, formatToString(mFormat));
827 dprintf(fd, " Frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700828 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800829 size_t numConfig = mConfigEvents.size();
830 if (numConfig) {
831 for (size_t i = 0; i < numConfig; i++) {
832 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700833 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800834 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700835 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800836 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700837 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800838 }
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800839 dprintf(fd, " Output device: %#x (%s)\n", mOutDevice, devicesToString(mOutDevice).string());
840 dprintf(fd, " Input device: %#x (%s)\n", mInDevice, devicesToString(mInDevice).string());
841 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, sourceToString(mAudioSource));
Eric Laurent81784c32012-11-19 14:55:58 -0800842
843 if (locked) {
844 mLock.unlock();
845 }
846}
847
848void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
849{
850 const size_t SIZE = 256;
851 char buffer[SIZE];
852 String8 result;
853
Marco Nelissenb2208842014-02-07 14:00:50 -0800854 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000855 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800856 write(fd, buffer, strlen(buffer));
857
Marco Nelissenb2208842014-02-07 14:00:50 -0800858 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800859 sp<EffectChain> chain = mEffectChains[i];
860 if (chain != 0) {
861 chain->dump(fd, args);
862 }
863 }
864}
865
Marco Nelissene14a5d62013-10-03 08:51:24 -0700866void AudioFlinger::ThreadBase::acquireWakeLock(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800867{
868 Mutex::Autolock _l(mLock);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700869 acquireWakeLock_l(uid);
Eric Laurent81784c32012-11-19 14:55:58 -0800870}
871
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100872String16 AudioFlinger::ThreadBase::getWakeLockTag()
873{
874 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -0800875 case MIXER:
876 return String16("AudioMix");
877 case DIRECT:
878 return String16("AudioDirectOut");
879 case DUPLICATING:
880 return String16("AudioDup");
881 case RECORD:
882 return String16("AudioIn");
883 case OFFLOAD:
884 return String16("AudioOffload");
885 default:
886 ALOG_ASSERT(false);
887 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100888 }
889}
890
Marco Nelissene14a5d62013-10-03 08:51:24 -0700891void AudioFlinger::ThreadBase::acquireWakeLock_l(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800892{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800893 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800894 if (mPowerManager != 0) {
895 sp<IBinder> binder = new BBinder();
Marco Nelissene14a5d62013-10-03 08:51:24 -0700896 status_t status;
897 if (uid >= 0) {
Eric Laurent547789d2013-10-04 11:46:55 -0700898 status = mPowerManager->acquireWakeLockWithUid(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700899 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100900 getWakeLockTag(),
Marco Nelissene14a5d62013-10-03 08:51:24 -0700901 String16("media"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700902 uid,
903 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700904 } else {
Eric Laurent547789d2013-10-04 11:46:55 -0700905 status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700906 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100907 getWakeLockTag(),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700908 String16("media"),
909 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700910 }
Eric Laurent81784c32012-11-19 14:55:58 -0800911 if (status == NO_ERROR) {
912 mWakeLockToken = binder;
913 }
Glenn Kastend7dca052015-03-05 16:05:54 -0800914 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Eric Laurent81784c32012-11-19 14:55:58 -0800915 }
916}
917
918void AudioFlinger::ThreadBase::releaseWakeLock()
919{
920 Mutex::Autolock _l(mLock);
921 releaseWakeLock_l();
922}
923
924void AudioFlinger::ThreadBase::releaseWakeLock_l()
925{
926 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800927 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -0800928 if (mPowerManager != 0) {
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700929 mPowerManager->releaseWakeLock(mWakeLockToken, 0,
930 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800931 }
932 mWakeLockToken.clear();
933 }
934}
935
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800936void AudioFlinger::ThreadBase::updateWakeLockUids(const SortedVector<int> &uids) {
937 Mutex::Autolock _l(mLock);
938 updateWakeLockUids_l(uids);
939}
940
941void AudioFlinger::ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -0700942 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800943 // use checkService() to avoid blocking if power service is not up yet
944 sp<IBinder> binder =
945 defaultServiceManager()->checkService(String16("power"));
946 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800947 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800948 } else {
949 mPowerManager = interface_cast<IPowerManager>(binder);
950 binder->linkToDeath(mDeathRecipient);
951 }
952 }
953}
954
955void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<int> &uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800956 getPowerManager_l();
957 if (mWakeLockToken == NULL) {
958 ALOGE("no wake lock to update!");
959 return;
960 }
961 if (mPowerManager != 0) {
962 sp<IBinder> binder = new BBinder();
963 status_t status;
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700964 status = mPowerManager->updateWakeLockUids(mWakeLockToken, uids.size(), uids.array(),
965 true /* FIXME force oneway contrary to .aidl */);
Glenn Kastend7dca052015-03-05 16:05:54 -0800966 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800967 }
968}
969
Eric Laurent81784c32012-11-19 14:55:58 -0800970void AudioFlinger::ThreadBase::clearPowerManager()
971{
972 Mutex::Autolock _l(mLock);
973 releaseWakeLock_l();
974 mPowerManager.clear();
975}
976
Glenn Kasten0f11b512014-01-31 16:18:54 -0800977void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800978{
979 sp<ThreadBase> thread = mThread.promote();
980 if (thread != 0) {
981 thread->clearPowerManager();
982 }
983 ALOGW("power manager service died !!!");
984}
985
986void AudioFlinger::ThreadBase::setEffectSuspended(
987 const effect_uuid_t *type, bool suspend, int sessionId)
988{
989 Mutex::Autolock _l(mLock);
990 setEffectSuspended_l(type, suspend, sessionId);
991}
992
993void AudioFlinger::ThreadBase::setEffectSuspended_l(
994 const effect_uuid_t *type, bool suspend, int sessionId)
995{
996 sp<EffectChain> chain = getEffectChain_l(sessionId);
997 if (chain != 0) {
998 if (type != NULL) {
999 chain->setEffectSuspended_l(type, suspend);
1000 } else {
1001 chain->setEffectSuspendedAll_l(suspend);
1002 }
1003 }
1004
1005 updateSuspendedSessions_l(type, suspend, sessionId);
1006}
1007
1008void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1009{
1010 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1011 if (index < 0) {
1012 return;
1013 }
1014
1015 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1016 mSuspendedSessions.valueAt(index);
1017
1018 for (size_t i = 0; i < sessionEffects.size(); i++) {
1019 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
1020 for (int j = 0; j < desc->mRefCount; j++) {
1021 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1022 chain->setEffectSuspendedAll_l(true);
1023 } else {
1024 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1025 desc->mType.timeLow);
1026 chain->setEffectSuspended_l(&desc->mType, true);
1027 }
1028 }
1029 }
1030}
1031
1032void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1033 bool suspend,
1034 int sessionId)
1035{
1036 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1037
1038 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1039
1040 if (suspend) {
1041 if (index >= 0) {
1042 sessionEffects = mSuspendedSessions.valueAt(index);
1043 } else {
1044 mSuspendedSessions.add(sessionId, sessionEffects);
1045 }
1046 } else {
1047 if (index < 0) {
1048 return;
1049 }
1050 sessionEffects = mSuspendedSessions.valueAt(index);
1051 }
1052
1053
1054 int key = EffectChain::kKeyForSuspendAll;
1055 if (type != NULL) {
1056 key = type->timeLow;
1057 }
1058 index = sessionEffects.indexOfKey(key);
1059
1060 sp<SuspendedSessionDesc> desc;
1061 if (suspend) {
1062 if (index >= 0) {
1063 desc = sessionEffects.valueAt(index);
1064 } else {
1065 desc = new SuspendedSessionDesc();
1066 if (type != NULL) {
1067 desc->mType = *type;
1068 }
1069 sessionEffects.add(key, desc);
1070 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1071 }
1072 desc->mRefCount++;
1073 } else {
1074 if (index < 0) {
1075 return;
1076 }
1077 desc = sessionEffects.valueAt(index);
1078 if (--desc->mRefCount == 0) {
1079 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1080 sessionEffects.removeItemsAt(index);
1081 if (sessionEffects.isEmpty()) {
1082 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1083 sessionId);
1084 mSuspendedSessions.removeItem(sessionId);
1085 }
1086 }
1087 }
1088 if (!sessionEffects.isEmpty()) {
1089 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1090 }
1091}
1092
1093void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1094 bool enabled,
1095 int sessionId)
1096{
1097 Mutex::Autolock _l(mLock);
1098 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1099}
1100
1101void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1102 bool enabled,
1103 int sessionId)
1104{
1105 if (mType != RECORD) {
1106 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1107 // another session. This gives the priority to well behaved effect control panels
1108 // and applications not using global effects.
1109 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1110 // global effects
1111 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
1112 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1113 }
1114 }
1115
1116 sp<EffectChain> chain = getEffectChain_l(sessionId);
1117 if (chain != 0) {
1118 chain->checkSuspendOnEffectEnabled(effect, enabled);
1119 }
1120}
1121
1122// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1123sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1124 const sp<AudioFlinger::Client>& client,
1125 const sp<IEffectClient>& effectClient,
1126 int32_t priority,
1127 int sessionId,
1128 effect_descriptor_t *desc,
1129 int *enabled,
Glenn Kasten9156ef32013-08-06 15:39:08 -07001130 status_t *status)
Eric Laurent81784c32012-11-19 14:55:58 -08001131{
1132 sp<EffectModule> effect;
1133 sp<EffectHandle> handle;
1134 status_t lStatus;
1135 sp<EffectChain> chain;
1136 bool chainCreated = false;
1137 bool effectCreated = false;
1138 bool effectRegistered = false;
1139
1140 lStatus = initCheck();
1141 if (lStatus != NO_ERROR) {
1142 ALOGW("createEffect_l() Audio driver not initialized.");
1143 goto Exit;
1144 }
1145
Andy Hung98ef9782014-03-04 14:46:50 -08001146 // Reject any effect on Direct output threads for now, since the format of
1147 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1148 if (mType == DIRECT) {
1149 ALOGW("createEffect_l() Cannot add effect %s on Direct output type thread %s",
Glenn Kastend7dca052015-03-05 16:05:54 -08001150 desc->name, mThreadName);
Andy Hung98ef9782014-03-04 14:46:50 -08001151 lStatus = BAD_VALUE;
1152 goto Exit;
1153 }
1154
Andy Hung389cfdb2014-08-07 17:49:53 -07001155 // Reject any effect on mixer or duplicating multichannel sinks.
Andy Hung9a592762014-07-21 21:56:01 -07001156 // TODO: fix both format and multichannel issues with effects.
Andy Hung389cfdb2014-08-07 17:49:53 -07001157 if ((mType == MIXER || mType == DUPLICATING) && mChannelCount != FCC_2) {
1158 ALOGW("createEffect_l() Cannot add effect %s for multichannel(%d) %s threads",
1159 desc->name, mChannelCount, mType == MIXER ? "MIXER" : "DUPLICATING");
Andy Hung9a592762014-07-21 21:56:01 -07001160 lStatus = BAD_VALUE;
1161 goto Exit;
1162 }
1163
Eric Laurent5baf2af2013-09-12 17:37:00 -07001164 // Allow global effects only on offloaded and mixer threads
1165 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1166 switch (mType) {
1167 case MIXER:
1168 case OFFLOAD:
1169 break;
1170 case DIRECT:
1171 case DUPLICATING:
1172 case RECORD:
1173 default:
Glenn Kastend7dca052015-03-05 16:05:54 -08001174 ALOGW("createEffect_l() Cannot add global effect %s on thread %s",
1175 desc->name, mThreadName);
Eric Laurent5baf2af2013-09-12 17:37:00 -07001176 lStatus = BAD_VALUE;
1177 goto Exit;
1178 }
Eric Laurent81784c32012-11-19 14:55:58 -08001179 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07001180
Eric Laurent81784c32012-11-19 14:55:58 -08001181 // Only Pre processor effects are allowed on input threads and only on input threads
1182 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
1183 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
1184 desc->name, desc->flags, mType);
1185 lStatus = BAD_VALUE;
1186 goto Exit;
1187 }
1188
1189 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1190
1191 { // scope for mLock
1192 Mutex::Autolock _l(mLock);
1193
1194 // check for existing effect chain with the requested audio session
1195 chain = getEffectChain_l(sessionId);
1196 if (chain == 0) {
1197 // create a new chain for this session
1198 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1199 chain = new EffectChain(this, sessionId);
1200 addEffectChain_l(chain);
1201 chain->setStrategy(getStrategyForSession_l(sessionId));
1202 chainCreated = true;
1203 } else {
1204 effect = chain->getEffectFromDesc_l(desc);
1205 }
1206
1207 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1208
1209 if (effect == 0) {
1210 int id = mAudioFlinger->nextUniqueId();
1211 // Check CPU and memory usage
1212 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
1213 if (lStatus != NO_ERROR) {
1214 goto Exit;
1215 }
1216 effectRegistered = true;
1217 // create a new effect module if none present in the chain
1218 effect = new EffectModule(this, chain, desc, id, sessionId);
1219 lStatus = effect->status();
1220 if (lStatus != NO_ERROR) {
1221 goto Exit;
1222 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07001223 effect->setOffloaded(mType == OFFLOAD, mId);
1224
Eric Laurent81784c32012-11-19 14:55:58 -08001225 lStatus = chain->addEffect_l(effect);
1226 if (lStatus != NO_ERROR) {
1227 goto Exit;
1228 }
1229 effectCreated = true;
1230
1231 effect->setDevice(mOutDevice);
1232 effect->setDevice(mInDevice);
1233 effect->setMode(mAudioFlinger->getMode());
1234 effect->setAudioSource(mAudioSource);
1235 }
1236 // create effect handle and connect it to effect module
1237 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001238 lStatus = handle->initCheck();
1239 if (lStatus == OK) {
1240 lStatus = effect->addHandle(handle.get());
1241 }
Eric Laurent81784c32012-11-19 14:55:58 -08001242 if (enabled != NULL) {
1243 *enabled = (int)effect->isEnabled();
1244 }
1245 }
1246
1247Exit:
1248 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1249 Mutex::Autolock _l(mLock);
1250 if (effectCreated) {
1251 chain->removeEffect_l(effect);
1252 }
1253 if (effectRegistered) {
1254 AudioSystem::unregisterEffect(effect->id());
1255 }
1256 if (chainCreated) {
1257 removeEffectChain_l(chain);
1258 }
1259 handle.clear();
1260 }
1261
Glenn Kasten9156ef32013-08-06 15:39:08 -07001262 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001263 return handle;
1264}
1265
1266sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
1267{
1268 Mutex::Autolock _l(mLock);
1269 return getEffect_l(sessionId, effectId);
1270}
1271
1272sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
1273{
1274 sp<EffectChain> chain = getEffectChain_l(sessionId);
1275 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1276}
1277
1278// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1279// PlaybackThread::mLock held
1280status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1281{
1282 // check for existing effect chain with the requested audio session
1283 int sessionId = effect->sessionId();
1284 sp<EffectChain> chain = getEffectChain_l(sessionId);
1285 bool chainCreated = false;
1286
Eric Laurent5baf2af2013-09-12 17:37:00 -07001287 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
1288 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
1289 this, effect->desc().name, effect->desc().flags);
1290
Eric Laurent81784c32012-11-19 14:55:58 -08001291 if (chain == 0) {
1292 // create a new chain for this session
1293 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1294 chain = new EffectChain(this, sessionId);
1295 addEffectChain_l(chain);
1296 chain->setStrategy(getStrategyForSession_l(sessionId));
1297 chainCreated = true;
1298 }
1299 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1300
1301 if (chain->getEffectFromId_l(effect->id()) != 0) {
1302 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1303 this, effect->desc().name, chain.get());
1304 return BAD_VALUE;
1305 }
1306
Eric Laurent5baf2af2013-09-12 17:37:00 -07001307 effect->setOffloaded(mType == OFFLOAD, mId);
1308
Eric Laurent81784c32012-11-19 14:55:58 -08001309 status_t status = chain->addEffect_l(effect);
1310 if (status != NO_ERROR) {
1311 if (chainCreated) {
1312 removeEffectChain_l(chain);
1313 }
1314 return status;
1315 }
1316
1317 effect->setDevice(mOutDevice);
1318 effect->setDevice(mInDevice);
1319 effect->setMode(mAudioFlinger->getMode());
1320 effect->setAudioSource(mAudioSource);
1321 return NO_ERROR;
1322}
1323
1324void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
1325
1326 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
1327 effect_descriptor_t desc = effect->desc();
1328 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1329 detachAuxEffect_l(effect->id());
1330 }
1331
1332 sp<EffectChain> chain = effect->chain().promote();
1333 if (chain != 0) {
1334 // remove effect chain if removing last effect
1335 if (chain->removeEffect_l(effect) == 0) {
1336 removeEffectChain_l(chain);
1337 }
1338 } else {
1339 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1340 }
1341}
1342
1343void AudioFlinger::ThreadBase::lockEffectChains_l(
1344 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1345{
1346 effectChains = mEffectChains;
1347 for (size_t i = 0; i < mEffectChains.size(); i++) {
1348 mEffectChains[i]->lock();
1349 }
1350}
1351
1352void AudioFlinger::ThreadBase::unlockEffectChains(
1353 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1354{
1355 for (size_t i = 0; i < effectChains.size(); i++) {
1356 effectChains[i]->unlock();
1357 }
1358}
1359
1360sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
1361{
1362 Mutex::Autolock _l(mLock);
1363 return getEffectChain_l(sessionId);
1364}
1365
1366sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const
1367{
1368 size_t size = mEffectChains.size();
1369 for (size_t i = 0; i < size; i++) {
1370 if (mEffectChains[i]->sessionId() == sessionId) {
1371 return mEffectChains[i];
1372 }
1373 }
1374 return 0;
1375}
1376
1377void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1378{
1379 Mutex::Autolock _l(mLock);
1380 size_t size = mEffectChains.size();
1381 for (size_t i = 0; i < size; i++) {
1382 mEffectChains[i]->setMode_l(mode);
1383 }
1384}
1385
Eric Laurent83b88082014-06-20 18:31:16 -07001386void AudioFlinger::ThreadBase::getAudioPortConfig(struct audio_port_config *config)
1387{
1388 config->type = AUDIO_PORT_TYPE_MIX;
1389 config->ext.mix.handle = mId;
1390 config->sample_rate = mSampleRate;
1391 config->format = mFormat;
1392 config->channel_mask = mChannelMask;
1393 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1394 AUDIO_PORT_CONFIG_FORMAT;
1395}
1396
Eric Laurent72e3f392015-05-20 14:43:50 -07001397void AudioFlinger::ThreadBase::systemReady()
1398{
1399 Mutex::Autolock _l(mLock);
1400 if (mSystemReady) {
1401 return;
1402 }
1403 mSystemReady = true;
1404
1405 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1406 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1407 }
1408 mPendingConfigEvents.clear();
1409}
1410
Eric Laurent83b88082014-06-20 18:31:16 -07001411
Eric Laurent81784c32012-11-19 14:55:58 -08001412// ----------------------------------------------------------------------------
1413// Playback
1414// ----------------------------------------------------------------------------
1415
1416AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1417 AudioStreamOut* output,
1418 audio_io_handle_t id,
1419 audio_devices_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07001420 type_t type,
1421 bool systemReady)
1422 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type, systemReady),
Andy Hung2098f272014-02-27 14:00:06 -08001423 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001424 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001425 mMixerBuffer(NULL),
1426 mMixerBufferSize(0),
1427 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1428 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001429 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001430 mEffectBuffer(NULL),
1431 mEffectBufferSize(0),
1432 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1433 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001434 mSuspended(0), mBytesWritten(0),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001435 mActiveTracksGeneration(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001436 // mStreamTypes[] initialized in constructor body
1437 mOutput(output),
1438 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
1439 mMixerStatus(MIXER_IDLE),
1440 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
1441 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001442 mBytesRemaining(0),
1443 mCurrentWriteLength(0),
1444 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001445 mWriteAckSequence(0),
1446 mDrainSequence(0),
Eric Laurentede6c3b2013-09-19 14:37:46 -07001447 mSignalPending(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001448 mScreenState(AudioFlinger::mScreenState),
1449 // index 0 is reserved for normal mixer's submix
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001450 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1),
Eric Laurentd1f69b02014-12-15 14:33:13 -08001451 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001452 // mLatchD, mLatchQ,
1453 mLatchDValid(false), mLatchQValid(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001454{
Glenn Kastend7dca052015-03-05 16:05:54 -08001455 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1456 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001457
1458 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1459 // it would be safer to explicitly pass initial masterVolume/masterMute as
1460 // parameter.
1461 //
1462 // If the HAL we are using has support for master volume or master mute,
1463 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1464 // and the mute set to false).
1465 mMasterVolume = audioFlinger->masterVolume_l();
1466 mMasterMute = audioFlinger->masterMute_l();
1467 if (mOutput && mOutput->audioHwDev) {
1468 if (mOutput->audioHwDev->canSetMasterVolume()) {
1469 mMasterVolume = 1.0;
1470 }
1471
1472 if (mOutput->audioHwDev->canSetMasterMute()) {
1473 mMasterMute = false;
1474 }
1475 }
1476
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001477 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001478
Eric Laurent223fd5c2014-11-11 13:43:36 -08001479 // ++ operator does not compile
Glenn Kasten66e46352014-01-16 17:44:23 -08001480 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001481 stream = (audio_stream_type_t) (stream + 1)) {
1482 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1483 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1484 }
Eric Laurent81784c32012-11-19 14:55:58 -08001485}
1486
1487AudioFlinger::PlaybackThread::~PlaybackThread()
1488{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001489 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001490 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001491 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001492 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001493}
1494
1495void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1496{
1497 dumpInternals(fd, args);
1498 dumpTracks(fd, args);
1499 dumpEffectChains(fd, args);
1500}
1501
Glenn Kasten0f11b512014-01-31 16:18:54 -08001502void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001503{
1504 const size_t SIZE = 256;
1505 char buffer[SIZE];
1506 String8 result;
1507
Marco Nelissenb2208842014-02-07 14:00:50 -08001508 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001509 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1510 const stream_type_t *st = &mStreamTypes[i];
1511 if (i > 0) {
1512 result.appendFormat(", ");
1513 }
1514 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1515 if (st->mute) {
1516 result.append("M");
1517 }
1518 }
1519 result.append("\n");
1520 write(fd, result.string(), result.length());
1521 result.clear();
1522
Eric Laurent81784c32012-11-19 14:55:58 -08001523 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1524 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001525 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001526 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001527
1528 size_t numtracks = mTracks.size();
1529 size_t numactive = mActiveTracks.size();
Elliott Hughes87cebad2014-05-22 10:14:43 -07001530 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001531 size_t numactiveseen = 0;
1532 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07001533 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08001534 Track::appendDumpHeader(result);
1535 for (size_t i = 0; i < numtracks; ++i) {
1536 sp<Track> track = mTracks[i];
1537 if (track != 0) {
1538 bool active = mActiveTracks.indexOf(track) >= 0;
1539 if (active) {
1540 numactiveseen++;
1541 }
1542 track->dump(buffer, SIZE, active);
1543 result.append(buffer);
1544 }
1545 }
1546 } else {
1547 result.append("\n");
1548 }
1549 if (numactiveseen != numactive) {
1550 // some tracks in the active list were not in the tracks list
1551 snprintf(buffer, SIZE, " The following tracks are in the active list but"
1552 " not in the track list\n");
1553 result.append(buffer);
1554 Track::appendDumpHeader(result);
1555 for (size_t i = 0; i < numactive; ++i) {
1556 sp<Track> track = mActiveTracks[i].promote();
1557 if (track != 0 && mTracks.indexOf(track) < 0) {
1558 track->dump(buffer, SIZE, true);
1559 result.append(buffer);
1560 }
1561 }
1562 }
1563
1564 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001565}
1566
1567void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1568{
Glenn Kasten97b7b752014-09-28 13:04:24 -07001569 dprintf(fd, "\nOutput thread %p type %d (%s):\n", this, type(), threadTypeToString(type()));
Glenn Kasten44182c22015-03-05 17:12:23 -08001570
1571 dumpBase(fd, args);
1572
Elliott Hughes87cebad2014-05-22 10:14:43 -07001573 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
1574 dprintf(fd, " Last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1575 dprintf(fd, " Total writes: %d\n", mNumWrites);
1576 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1577 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1578 dprintf(fd, " Suspend count: %d\n", mSuspended);
1579 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1580 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1581 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1582 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001583 AudioStreamOut *output = mOutput;
1584 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
1585 String8 flagsAsString = outputFlagsToString(flags);
1586 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n", output, flags, flagsAsString.string());
Eric Laurent81784c32012-11-19 14:55:58 -08001587}
1588
1589// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001590
1591void AudioFlinger::PlaybackThread::onFirstRef()
1592{
Glenn Kastend7dca052015-03-05 16:05:54 -08001593 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001594}
1595
1596// ThreadBase virtuals
1597void AudioFlinger::PlaybackThread::preExit()
1598{
1599 ALOGV(" preExit()");
1600 // FIXME this is using hard-coded strings but in the future, this functionality will be
1601 // converted to use audio HAL extensions required to support tunneling
1602 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1603}
1604
1605// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1606sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1607 const sp<AudioFlinger::Client>& client,
1608 audio_stream_type_t streamType,
1609 uint32_t sampleRate,
1610 audio_format_t format,
1611 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001612 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001613 const sp<IMemory>& sharedBuffer,
1614 int sessionId,
1615 IAudioFlinger::track_flags_t *flags,
1616 pid_t tid,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001617 int uid,
Eric Laurent81784c32012-11-19 14:55:58 -08001618 status_t *status)
1619{
Glenn Kasten74935e42013-12-19 08:56:45 -08001620 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001621 sp<Track> track;
1622 status_t lStatus;
1623
1624 bool isTimed = (*flags & IAudioFlinger::TRACK_TIMED) != 0;
1625
1626 // client expresses a preference for FAST, but we get the final say
1627 if (*flags & IAudioFlinger::TRACK_FAST) {
1628 if (
1629 // not timed
1630 (!isTimed) &&
1631 // either of these use cases:
1632 (
1633 // use case 1: shared buffer with any frame count
1634 (
1635 (sharedBuffer != 0)
1636 ) ||
Glenn Kasten1dfe2f92015-03-09 12:03:14 -07001637 // use case 2: frame count is default or at least as large as HAL
Eric Laurent81784c32012-11-19 14:55:58 -08001638 (
Glenn Kasten1dfe2f92015-03-09 12:03:14 -07001639 // we formerly checked for a callback handler (non-0 tid),
1640 // but that is no longer required for TRANSFER_OBTAIN mode
Eric Laurent81784c32012-11-19 14:55:58 -08001641 ((frameCount == 0) ||
Glenn Kastenb5fed682013-12-03 09:06:43 -08001642 (frameCount >= mFrameCount))
Eric Laurent81784c32012-11-19 14:55:58 -08001643 )
1644 ) &&
1645 // PCM data
1646 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07001647 // TODO: extract as a data library function that checks that a computationally
1648 // expensive downmixer is not required: isFastOutputChannelConversion()
Andy Hung9a592762014-07-21 21:56:01 -07001649 (channelMask == mChannelMask ||
Andy Hung1f439e12015-05-19 12:57:41 -07001650 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
1651 (channelMask == AUDIO_CHANNEL_OUT_MONO
1652 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001653 // hardware sample rate
1654 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001655 // normal mixer has an associated fast mixer
1656 hasFastMixer() &&
1657 // there are sufficient fast track slots available
1658 (mFastTrackAvailMask != 0)
1659 // FIXME test that MixerThread for this fast track has a capable output HAL
1660 // FIXME add a permission test also?
1661 ) {
1662 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1663 if (frameCount == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001664 // read the fast track multiplier property the first time it is needed
1665 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1666 if (ok != 0) {
1667 ALOGE("%s pthread_once failed: %d", __func__, ok);
1668 }
1669 frameCount = mFrameCount * sFastTrackMultiplier;
Eric Laurent81784c32012-11-19 14:55:58 -08001670 }
1671 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
1672 frameCount, mFrameCount);
1673 } else {
1674 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
Andy Hung6146c082014-03-18 11:56:15 -07001675 "mFrameCount=%d format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
1676 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001677 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Andy Hung6146c082014-03-18 11:56:15 -07001678 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001679 audio_is_linear_pcm(format),
1680 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
1681 *flags &= ~IAudioFlinger::TRACK_FAST;
Andy Hung0e48d252015-01-26 11:43:15 -08001682 }
1683 }
1684 // For normal PCM streaming tracks, update minimum frame count.
1685 // For compatibility with AudioTrack calculation, buffer depth is forced
1686 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1687 // This is probably too conservative, but legacy application code may depend on it.
1688 // If you change this calculation, also review the start threshold which is related.
1689 if (!(*flags & IAudioFlinger::TRACK_FAST)
1690 && audio_is_linear_pcm(format) && sharedBuffer == 0) {
Andy Hung8edb8dc2015-03-26 19:13:55 -07001691 // this must match AudioTrack.cpp calculateMinFrameCount().
1692 // TODO: Move to a common library
Eric Laurent81784c32012-11-19 14:55:58 -08001693 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1694 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1695 if (minBufCount < 2) {
1696 minBufCount = 2;
1697 }
Andy Hung8edb8dc2015-03-26 19:13:55 -07001698 // For normal mixing tracks, if speed is > 1.0f (normal), AudioTrack
1699 // or the client should compute and pass in a larger buffer request.
Andy Hung0e48d252015-01-26 11:43:15 -08001700 size_t minFrameCount =
Andy Hung8edb8dc2015-03-26 19:13:55 -07001701 minBufCount * sourceFramesNeededWithTimestretch(
1702 sampleRate, mNormalFrameCount,
1703 mSampleRate, AUDIO_TIMESTRETCH_SPEED_NORMAL /*speed*/);
Andy Hung0e48d252015-01-26 11:43:15 -08001704 if (frameCount < minFrameCount) { // including frameCount == 0
Eric Laurent81784c32012-11-19 14:55:58 -08001705 frameCount = minFrameCount;
1706 }
Eric Laurent81784c32012-11-19 14:55:58 -08001707 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001708 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001709
Glenn Kastenc3df8382014-03-13 15:05:25 -07001710 switch (mType) {
1711
1712 case DIRECT:
Glenn Kasten993fa062014-05-02 11:14:34 -07001713 if (audio_is_linear_pcm(format)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001714 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001715 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1716 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001717 sampleRate, format, channelMask, mOutput, mFormat);
1718 lStatus = BAD_VALUE;
1719 goto Exit;
1720 }
1721 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001722 break;
1723
1724 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001725 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001726 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1727 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001728 sampleRate, format, channelMask, mOutput, mFormat);
1729 lStatus = BAD_VALUE;
1730 goto Exit;
1731 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001732 break;
1733
1734 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07001735 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001736 ALOGE("createTrack_l() Bad parameter: format %#x \""
1737 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001738 format, mOutput, mFormat);
1739 lStatus = BAD_VALUE;
1740 goto Exit;
1741 }
Andy Hungcd044842014-08-07 11:04:34 -07001742 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08001743 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1744 lStatus = BAD_VALUE;
1745 goto Exit;
1746 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001747 break;
1748
Eric Laurent81784c32012-11-19 14:55:58 -08001749 }
1750
1751 lStatus = initCheck();
1752 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07001753 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08001754 goto Exit;
1755 }
1756
1757 { // scope for mLock
1758 Mutex::Autolock _l(mLock);
1759
1760 // all tracks in same audio session must share the same routing strategy otherwise
1761 // conflicts will happen when tracks are moved from one output to another by audio policy
1762 // manager
1763 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1764 for (size_t i = 0; i < mTracks.size(); ++i) {
1765 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07001766 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001767 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1768 if (sessionId == t->sessionId() && strategy != actual) {
1769 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1770 strategy, actual);
1771 lStatus = BAD_VALUE;
1772 goto Exit;
1773 }
1774 }
1775 }
1776
1777 if (!isTimed) {
1778 track = new Track(this, client, streamType, sampleRate, format,
Eric Laurent83b88082014-06-20 18:31:16 -07001779 channelMask, frameCount, NULL, sharedBuffer,
1780 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08001781 } else {
1782 track = TimedTrack::create(this, client, streamType, sampleRate, format,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001783 channelMask, frameCount, sharedBuffer, sessionId, uid);
Eric Laurent81784c32012-11-19 14:55:58 -08001784 }
Glenn Kasten03003332013-08-06 15:40:54 -07001785
1786 // new Track always returns non-NULL,
1787 // but TimedTrack::create() is a factory that could fail by returning NULL
1788 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
1789 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08001790 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001791 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08001792 goto Exit;
1793 }
1794 mTracks.add(track);
1795
1796 sp<EffectChain> chain = getEffectChain_l(sessionId);
1797 if (chain != 0) {
1798 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1799 track->setMainBuffer(chain->inBuffer());
1800 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1801 chain->incTrackCnt();
1802 }
1803
1804 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1805 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1806 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1807 // so ask activity manager to do this on our behalf
1808 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1809 }
1810 }
1811
1812 lStatus = NO_ERROR;
1813
1814Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001815 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001816 return track;
1817}
1818
1819uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1820{
1821 return latency;
1822}
1823
1824uint32_t AudioFlinger::PlaybackThread::latency() const
1825{
1826 Mutex::Autolock _l(mLock);
1827 return latency_l();
1828}
1829uint32_t AudioFlinger::PlaybackThread::latency_l() const
1830{
1831 if (initCheck() == NO_ERROR) {
1832 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
1833 } else {
1834 return 0;
1835 }
1836}
1837
1838void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1839{
1840 Mutex::Autolock _l(mLock);
1841 // Don't apply master volume in SW if our HAL can do it for us.
1842 if (mOutput && mOutput->audioHwDev &&
1843 mOutput->audioHwDev->canSetMasterVolume()) {
1844 mMasterVolume = 1.0;
1845 } else {
1846 mMasterVolume = value;
1847 }
1848}
1849
1850void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1851{
1852 Mutex::Autolock _l(mLock);
1853 // Don't apply master mute in SW if our HAL can do it for us.
1854 if (mOutput && mOutput->audioHwDev &&
1855 mOutput->audioHwDev->canSetMasterMute()) {
1856 mMasterMute = false;
1857 } else {
1858 mMasterMute = muted;
1859 }
1860}
1861
1862void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
1863{
1864 Mutex::Autolock _l(mLock);
1865 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001866 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001867}
1868
1869void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
1870{
1871 Mutex::Autolock _l(mLock);
1872 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001873 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001874}
1875
1876float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
1877{
1878 Mutex::Autolock _l(mLock);
1879 return mStreamTypes[stream].volume;
1880}
1881
1882// addTrack_l() must be called with ThreadBase::mLock held
1883status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1884{
1885 status_t status = ALREADY_EXISTS;
1886
1887 // set retry count for buffer fill
1888 track->mRetryCount = kMaxTrackStartupRetries;
1889 if (mActiveTracks.indexOf(track) < 0) {
1890 // the track is newly added, make sure it fills up all its
1891 // buffers before playing. This is to ensure the client will
1892 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07001893 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001894 TrackBase::track_state state = track->mState;
1895 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08001896 status = AudioSystem::startOutput(mId, track->streamType(),
1897 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001898 mLock.lock();
1899 // abort track was stopped/paused while we released the lock
1900 if (state != track->mState) {
1901 if (status == NO_ERROR) {
1902 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08001903 AudioSystem::stopOutput(mId, track->streamType(),
1904 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001905 mLock.lock();
1906 }
1907 return INVALID_OPERATION;
1908 }
1909 // abort if start is rejected by audio policy manager
1910 if (status != NO_ERROR) {
1911 return PERMISSION_DENIED;
1912 }
1913#ifdef ADD_BATTERY_DATA
1914 // to track the speaker usage
1915 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
1916#endif
1917 }
1918
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001919 track->mFillingUpStatus = track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent81784c32012-11-19 14:55:58 -08001920 track->mResetDone = false;
1921 track->mPresentationCompleteFrames = 0;
1922 mActiveTracks.add(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001923 mWakeLockUids.add(track->uid());
1924 mActiveTracksGeneration++;
Eric Laurentfd477972013-10-25 18:10:40 -07001925 mLatestActiveTrack = track;
Eric Laurentd0107bc2013-06-11 14:38:48 -07001926 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1927 if (chain != 0) {
1928 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
1929 track->sessionId());
1930 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08001931 }
1932
1933 status = NO_ERROR;
1934 }
1935
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08001936 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001937 return status;
1938}
1939
Eric Laurentbfb1b832013-01-07 09:53:42 -08001940bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08001941{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001942 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08001943 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001944 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
1945 track->mState = TrackBase::STOPPED;
1946 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08001947 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07001948 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001949 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08001950 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001951
1952 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08001953}
1954
1955void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1956{
1957 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
1958 mTracks.remove(track);
1959 deleteTrackName_l(track->name());
1960 // redundant as track is about to be destroyed, for dumpsys only
1961 track->mName = -1;
1962 if (track->isFastTrack()) {
1963 int index = track->mFastIndex;
1964 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
1965 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1966 mFastTrackAvailMask |= 1 << index;
1967 // redundant as track is about to be destroyed, for dumpsys only
1968 track->mFastIndex = -1;
1969 }
1970 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1971 if (chain != 0) {
1972 chain->decTrackCnt();
1973 }
1974}
1975
Eric Laurentede6c3b2013-09-19 14:37:46 -07001976void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001977{
1978 // Thread could be blocked waiting for async
1979 // so signal it to handle state changes immediately
1980 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1981 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1982 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001983 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001984}
1985
Eric Laurent81784c32012-11-19 14:55:58 -08001986String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1987{
Eric Laurent81784c32012-11-19 14:55:58 -08001988 Mutex::Autolock _l(mLock);
1989 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07001990 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08001991 }
1992
Glenn Kastend8ea6992013-07-16 14:17:15 -07001993 char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
1994 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08001995 free(s);
1996 return out_s8;
1997}
1998
Eric Laurent73e26b62015-04-27 16:55:58 -07001999void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event) {
2000 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2001 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002002
Eric Laurent73e26b62015-04-27 16:55:58 -07002003 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002004
2005 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002006 case AUDIO_OUTPUT_OPENED:
2007 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002008 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002009 desc->mChannelMask = mChannelMask;
2010 desc->mSamplingRate = mSampleRate;
2011 desc->mFormat = mFormat;
2012 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002013 // AudioFlinger::frameCount(audio_io_handle_t)
Eric Laurent73e26b62015-04-27 16:55:58 -07002014 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002015 break;
2016
Eric Laurent73e26b62015-04-27 16:55:58 -07002017 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002018 default:
2019 break;
2020 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002021 mAudioFlinger->ioConfigChanged(event, desc);
Eric Laurent81784c32012-11-19 14:55:58 -08002022}
2023
Eric Laurentbfb1b832013-01-07 09:53:42 -08002024void AudioFlinger::PlaybackThread::writeCallback()
2025{
2026 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002027 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002028}
2029
2030void AudioFlinger::PlaybackThread::drainCallback()
2031{
2032 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002033 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002034}
2035
Eric Laurent3b4529e2013-09-05 18:09:19 -07002036void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002037{
2038 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002039 // reject out of sequence requests
2040 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2041 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002042 mWaitWorkCV.signal();
2043 }
2044}
2045
Eric Laurent3b4529e2013-09-05 18:09:19 -07002046void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002047{
2048 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002049 // reject out of sequence requests
2050 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
2051 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002052 mWaitWorkCV.signal();
2053 }
2054}
2055
2056// static
2057int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
Glenn Kasten0f11b512014-01-31 16:18:54 -08002058 void *param __unused,
Eric Laurentbfb1b832013-01-07 09:53:42 -08002059 void *cookie)
2060{
2061 AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
2062 ALOGV("asyncCallback() event %d", event);
2063 switch (event) {
2064 case STREAM_CBK_EVENT_WRITE_READY:
2065 me->writeCallback();
2066 break;
2067 case STREAM_CBK_EVENT_DRAIN_READY:
2068 me->drainCallback();
2069 break;
2070 default:
2071 ALOGW("asyncCallback() unknown event %d", event);
2072 break;
2073 }
2074 return 0;
2075}
2076
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002077void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002078{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002079 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Eric Laurent81784c32012-11-19 14:55:58 -08002080 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
2081 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002082 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002083 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002084 }
Andy Hung9a592762014-07-21 21:56:01 -07002085 if ((mType == MIXER || mType == DUPLICATING)
2086 && !isValidPcmSinkChannelMask(mChannelMask)) {
2087 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2088 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002089 }
Andy Hunge5412692014-05-16 11:25:07 -07002090 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Andy Hung463be252014-07-10 16:56:07 -07002091 mHALFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
2092 mFormat = mHALFormat;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002093 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002094 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002095 }
Andy Hung6146c082014-03-18 11:56:15 -07002096 if ((mType == MIXER || mType == DUPLICATING)
2097 && !isValidPcmSinkFormat(mFormat)) {
2098 LOG_FATAL("HAL format %#x not supported for mixed output",
2099 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002100 }
Phil Burk062e67a2015-02-11 13:40:50 -08002101 mFrameSize = mOutput->getFrameSize();
Glenn Kasten70949c42013-08-06 07:40:12 -07002102 mBufferSize = mOutput->stream->common.get_buffer_size(&mOutput->stream->common);
2103 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002104 if (mFrameCount & 15) {
2105 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
2106 mFrameCount);
2107 }
2108
Eric Laurentbfb1b832013-01-07 09:53:42 -08002109 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
2110 (mOutput->stream->set_callback != NULL)) {
2111 if (mOutput->stream->set_callback(mOutput->stream,
2112 AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
2113 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002114 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002115 }
2116 }
2117
Eric Laurentd1f69b02014-12-15 14:33:13 -08002118 mHwSupportsPause = false;
2119 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
2120 if (mOutput->stream->pause != NULL) {
2121 if (mOutput->stream->resume != NULL) {
2122 mHwSupportsPause = true;
2123 } else {
2124 ALOGW("direct output implements pause but not resume");
2125 }
2126 } else if (mOutput->stream->resume != NULL) {
2127 ALOGW("direct output implements resume but not pause");
2128 }
2129 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002130 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2131 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2132 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002133
Andy Hungfbfc3952015-01-15 13:33:51 -08002134 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2135 // For best precision, we use float instead of the associated output
2136 // device format (typically PCM 16 bit).
2137
2138 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2139 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2140 mBufferSize = mFrameSize * mFrameCount;
2141
2142 // TODO: We currently use the associated output device channel mask and sample rate.
2143 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2144 // (if a valid mask) to avoid premature downmix.
2145 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2146 // instead of the output device sample rate to avoid loss of high frequency information.
2147 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2148 }
2149
Andy Hung09a50072014-02-27 14:30:47 -08002150 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002151 double multiplier = 1.0;
2152 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2153 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002154 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2155 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Eric Laurent81784c32012-11-19 14:55:58 -08002156 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2157 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2158 maxNormalFrameCount = maxNormalFrameCount & ~15;
2159 if (maxNormalFrameCount < minNormalFrameCount) {
2160 maxNormalFrameCount = minNormalFrameCount;
2161 }
2162 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2163 if (multiplier <= 1.0) {
2164 multiplier = 1.0;
2165 } else if (multiplier <= 2.0) {
2166 if (2 * mFrameCount <= maxNormalFrameCount) {
2167 multiplier = 2.0;
2168 } else {
2169 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2170 }
2171 } else {
2172 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
Andy Hung09a50072014-02-27 14:30:47 -08002173 // 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 -08002174 // track, but we sometimes have to do this to satisfy the maximum frame count
2175 // constraint)
2176 // FIXME this rounding up should not be done if no HAL SRC
2177 uint32_t truncMult = (uint32_t) multiplier;
2178 if ((truncMult & 1)) {
2179 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
2180 ++truncMult;
2181 }
2182 }
2183 multiplier = (double) truncMult;
2184 }
2185 }
2186 mNormalFrameCount = multiplier * mFrameCount;
2187 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002188 if (mType == MIXER || mType == DUPLICATING) {
2189 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2190 }
Andy Hung09a50072014-02-27 14:30:47 -08002191 ALOGI("HAL output buffer size %u frames, normal sink buffer size %u frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002192 mNormalFrameCount);
2193
Andy Hung010a1a12014-03-13 13:57:33 -07002194 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2195 // Originally this was int16_t[] array, need to remove legacy implications.
2196 free(mSinkBuffer);
2197 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002198 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2199 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2200 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002201 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002202
Andy Hung69aed5f2014-02-25 17:24:40 -08002203 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2204 // drives the output.
2205 free(mMixerBuffer);
2206 mMixerBuffer = NULL;
2207 if (mMixerBufferEnabled) {
2208 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2209 mMixerBufferSize = mNormalFrameCount * mChannelCount
2210 * audio_bytes_per_sample(mMixerBufferFormat);
2211 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2212 }
Andy Hung98ef9782014-03-04 14:46:50 -08002213 free(mEffectBuffer);
2214 mEffectBuffer = NULL;
2215 if (mEffectBufferEnabled) {
2216 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
2217 mEffectBufferSize = mNormalFrameCount * mChannelCount
2218 * audio_bytes_per_sample(mEffectBufferFormat);
2219 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2220 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002221
Eric Laurent81784c32012-11-19 14:55:58 -08002222 // force reconfiguration of effect chains and engines to take new buffer size and audio
2223 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002224 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002225 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2226 // matter.
2227 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2228 Vector< sp<EffectChain> > effectChains = mEffectChains;
2229 for (size_t i = 0; i < effectChains.size(); i ++) {
2230 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2231 }
2232}
2233
2234
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002235status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002236{
2237 if (halFrames == NULL || dspFrames == NULL) {
2238 return BAD_VALUE;
2239 }
2240 Mutex::Autolock _l(mLock);
2241 if (initCheck() != NO_ERROR) {
2242 return INVALID_OPERATION;
2243 }
2244 size_t framesWritten = mBytesWritten / mFrameSize;
2245 *halFrames = framesWritten;
2246
2247 if (isSuspended()) {
2248 // return an estimation of rendered frames when the output is suspended
2249 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
2250 *dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0;
2251 return NO_ERROR;
2252 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002253 status_t status;
2254 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002255 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002256 *dspFrames = (size_t)frames;
2257 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002258 }
2259}
2260
2261uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
2262{
2263 Mutex::Autolock _l(mLock);
2264 uint32_t result = 0;
2265 if (getEffectChain_l(sessionId) != 0) {
2266 result = EFFECT_SESSION;
2267 }
2268
2269 for (size_t i = 0; i < mTracks.size(); ++i) {
2270 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002271 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002272 result |= TRACK_SESSION;
2273 break;
2274 }
2275 }
2276
2277 return result;
2278}
2279
2280uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
2281{
2282 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2283 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2284 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2285 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2286 }
2287 for (size_t i = 0; i < mTracks.size(); i++) {
2288 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002289 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002290 return AudioSystem::getStrategyForStream(track->streamType());
2291 }
2292 }
2293 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2294}
2295
2296
Phil Burk062e67a2015-02-11 13:40:50 -08002297AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002298{
2299 Mutex::Autolock _l(mLock);
2300 return mOutput;
2301}
2302
Phil Burk062e67a2015-02-11 13:40:50 -08002303AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002304{
2305 Mutex::Autolock _l(mLock);
2306 AudioStreamOut *output = mOutput;
2307 mOutput = NULL;
2308 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2309 // must push a NULL and wait for ack
2310 mOutputSink.clear();
2311 mPipeSink.clear();
2312 mNormalSink.clear();
2313 return output;
2314}
2315
2316// this method must always be called either with ThreadBase mLock held or inside the thread loop
2317audio_stream_t* AudioFlinger::PlaybackThread::stream() const
2318{
2319 if (mOutput == NULL) {
2320 return NULL;
2321 }
2322 return &mOutput->stream->common;
2323}
2324
2325uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2326{
2327 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2328}
2329
2330status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2331{
2332 if (!isValidSyncEvent(event)) {
2333 return BAD_VALUE;
2334 }
2335
2336 Mutex::Autolock _l(mLock);
2337
2338 for (size_t i = 0; i < mTracks.size(); ++i) {
2339 sp<Track> track = mTracks[i];
2340 if (event->triggerSession() == track->sessionId()) {
2341 (void) track->setSyncEvent(event);
2342 return NO_ERROR;
2343 }
2344 }
2345
2346 return NAME_NOT_FOUND;
2347}
2348
2349bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2350{
2351 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2352}
2353
2354void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2355 const Vector< sp<Track> >& tracksToRemove)
2356{
2357 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002358 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002359 for (size_t i = 0 ; i < count ; i++) {
2360 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002361 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002362 AudioSystem::stopOutput(mId, track->streamType(),
2363 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002364#ifdef ADD_BATTERY_DATA
2365 // to track the speaker usage
2366 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2367#endif
2368 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002369 AudioSystem::releaseOutput(mId, track->streamType(),
2370 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002371 }
Eric Laurent81784c32012-11-19 14:55:58 -08002372 }
2373 }
2374 }
Eric Laurent81784c32012-11-19 14:55:58 -08002375}
2376
2377void AudioFlinger::PlaybackThread::checkSilentMode_l()
2378{
2379 if (!mMasterMute) {
2380 char value[PROPERTY_VALUE_MAX];
2381 if (property_get("ro.audio.silent", value, "0") > 0) {
2382 char *endptr;
2383 unsigned long ul = strtoul(value, &endptr, 0);
2384 if (*endptr == '\0' && ul != 0) {
2385 ALOGD("Silence is golden");
2386 // The setprop command will not allow a property to be changed after
2387 // the first time it is set, so we don't have to worry about un-muting.
2388 setMasterMute_l(true);
2389 }
2390 }
2391 }
2392}
2393
2394// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002395ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002396{
2397 // FIXME rewrite to reduce number of system calls
2398 mLastWriteTime = systemTime();
2399 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002400 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002401 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002402
2403 // If an NBAIO sink is present, use it to write the normal mixer's submix
2404 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002405
Andy Hung010a1a12014-03-13 13:57:33 -07002406 const size_t count = mBytesRemaining / mFrameSize;
2407
Simon Wilson2d590962012-11-29 15:18:50 -08002408 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002409 // update the setpoint when AudioFlinger::mScreenState changes
2410 uint32_t screenState = AudioFlinger::mScreenState;
2411 if (screenState != mScreenState) {
2412 mScreenState = screenState;
2413 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2414 if (pipe != NULL) {
2415 pipe->setAvgFrames((mScreenState & 1) ?
2416 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2417 }
2418 }
Andy Hung010a1a12014-03-13 13:57:33 -07002419 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002420 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002421 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002422 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002423 } else {
2424 bytesWritten = framesWritten;
2425 }
Glenn Kastenefaa7ab2014-08-20 08:48:54 -07002426 mLatchDValid = false;
Glenn Kasten767094d2013-08-23 13:51:43 -07002427 status_t status = mNormalSink->getTimestamp(mLatchD.mTimestamp);
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002428 if (status == NO_ERROR) {
2429 size_t totalFramesWritten = mNormalSink->framesWritten();
2430 if (totalFramesWritten >= mLatchD.mTimestamp.mPosition) {
2431 mLatchD.mUnpresentedFrames = totalFramesWritten - mLatchD.mTimestamp.mPosition;
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002432 // mLatchD.mFramesReleased is set immediately before D is clocked into Q
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002433 mLatchDValid = true;
2434 }
2435 }
Eric Laurent81784c32012-11-19 14:55:58 -08002436 // otherwise use the HAL / AudioStreamOut directly
2437 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002438 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002439
Eric Laurentbfb1b832013-01-07 09:53:42 -08002440 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002441 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2442 mWriteAckSequence += 2;
2443 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002444 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002445 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002446 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002447 // FIXME We should have an implementation of timestamps for direct output threads.
2448 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002449 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002450 if (mUseAsyncWrite &&
2451 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2452 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002453 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002454 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002455 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002456 }
Eric Laurent81784c32012-11-19 14:55:58 -08002457 }
2458
Eric Laurent81784c32012-11-19 14:55:58 -08002459 mNumWrites++;
2460 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002461 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002462 return bytesWritten;
2463}
2464
2465void AudioFlinger::PlaybackThread::threadLoop_drain()
2466{
2467 if (mOutput->stream->drain) {
2468 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2469 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002470 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2471 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002472 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002473 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002474 }
2475 mOutput->stream->drain(mOutput->stream,
2476 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
2477 : AUDIO_DRAIN_ALL);
2478 }
2479}
2480
2481void AudioFlinger::PlaybackThread::threadLoop_exit()
2482{
Eric Laurent275e8e92014-11-30 15:14:47 -08002483 {
2484 Mutex::Autolock _l(mLock);
2485 for (size_t i = 0; i < mTracks.size(); i++) {
2486 sp<Track> track = mTracks[i];
2487 track->invalidate();
2488 }
2489 }
Eric Laurent81784c32012-11-19 14:55:58 -08002490}
2491
2492/*
2493The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002494 - mSinkBufferSize from frame count * frame size
Eric Laurent81784c32012-11-19 14:55:58 -08002495 - activeSleepTime from activeSleepTimeUs()
2496 - idleSleepTime from idleSleepTimeUs()
2497 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
2498 - maxPeriod from frame count and sample rate (MIXER only)
2499
2500The parameters that affect these derived values are:
2501 - frame count
2502 - frame size
2503 - sample rate
2504 - device type: A2DP or not
2505 - device latency
2506 - format: PCM or not
2507 - active sleep time
2508 - idle sleep time
2509*/
2510
2511void AudioFlinger::PlaybackThread::cacheParameters_l()
2512{
Andy Hung25c2dac2014-02-27 14:56:00 -08002513 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002514 activeSleepTime = activeSleepTimeUs();
2515 idleSleepTime = idleSleepTimeUs();
2516}
2517
2518void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2519{
Glenn Kasten7c027242012-12-26 14:43:16 -08002520 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurent81784c32012-11-19 14:55:58 -08002521 this, streamType, mTracks.size());
2522 Mutex::Autolock _l(mLock);
2523
2524 size_t size = mTracks.size();
2525 for (size_t i = 0; i < size; i++) {
2526 sp<Track> t = mTracks[i];
2527 if (t->streamType() == streamType) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002528 t->invalidate();
Eric Laurent81784c32012-11-19 14:55:58 -08002529 }
2530 }
2531}
2532
2533status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2534{
2535 int session = chain->sessionId();
Andy Hung010a1a12014-03-13 13:57:33 -07002536 int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled
2537 ? mEffectBuffer : mSinkBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002538 bool ownsBuffer = false;
2539
2540 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
2541 if (session > 0) {
2542 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002543 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002544 if (mType != DIRECT) {
2545 size_t numSamples = mNormalFrameCount * mChannelCount;
2546 buffer = new int16_t[numSamples];
2547 memset(buffer, 0, numSamples * sizeof(int16_t));
2548 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2549 ownsBuffer = true;
2550 }
2551
2552 // Attach all tracks with same session ID to this chain.
2553 for (size_t i = 0; i < mTracks.size(); ++i) {
2554 sp<Track> track = mTracks[i];
2555 if (session == track->sessionId()) {
2556 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2557 buffer);
2558 track->setMainBuffer(buffer);
2559 chain->incTrackCnt();
2560 }
2561 }
2562
2563 // indicate all active tracks in the chain
2564 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2565 sp<Track> track = mActiveTracks[i].promote();
2566 if (track == 0) {
2567 continue;
2568 }
2569 if (session == track->sessionId()) {
2570 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2571 chain->incActiveTrackCnt();
2572 }
2573 }
2574 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002575 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08002576 chain->setInBuffer(buffer, ownsBuffer);
Andy Hung010a1a12014-03-13 13:57:33 -07002577 chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled
2578 ? mEffectBuffer : mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002579 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
2580 // chains list in order to be processed last as it contains output stage effects
2581 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2582 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
2583 // after track specific effects and before output stage
2584 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
2585 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
2586 // Effect chain for other sessions are inserted at beginning of effect
2587 // chains list to be processed before output mix effects. Relative order between other
2588 // sessions is not important
2589 size_t size = mEffectChains.size();
2590 size_t i = 0;
2591 for (i = 0; i < size; i++) {
2592 if (mEffectChains[i]->sessionId() < session) {
2593 break;
2594 }
2595 }
2596 mEffectChains.insertAt(chain, i);
2597 checkSuspendOnAddEffectChain_l(chain);
2598
2599 return NO_ERROR;
2600}
2601
2602size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2603{
2604 int session = chain->sessionId();
2605
2606 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2607
2608 for (size_t i = 0; i < mEffectChains.size(); i++) {
2609 if (chain == mEffectChains[i]) {
2610 mEffectChains.removeAt(i);
2611 // detach all active tracks from the chain
2612 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2613 sp<Track> track = mActiveTracks[i].promote();
2614 if (track == 0) {
2615 continue;
2616 }
2617 if (session == track->sessionId()) {
2618 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2619 chain.get(), session);
2620 chain->decActiveTrackCnt();
2621 }
2622 }
2623
2624 // detach all tracks with same session ID from this chain
2625 for (size_t i = 0; i < mTracks.size(); ++i) {
2626 sp<Track> track = mTracks[i];
2627 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002628 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002629 chain->decTrackCnt();
2630 }
2631 }
2632 break;
2633 }
2634 }
2635 return mEffectChains.size();
2636}
2637
2638status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2639 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2640{
2641 Mutex::Autolock _l(mLock);
2642 return attachAuxEffect_l(track, EffectId);
2643}
2644
2645status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2646 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2647{
2648 status_t status = NO_ERROR;
2649
2650 if (EffectId == 0) {
2651 track->setAuxBuffer(0, NULL);
2652 } else {
2653 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2654 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2655 if (effect != 0) {
2656 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2657 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2658 } else {
2659 status = INVALID_OPERATION;
2660 }
2661 } else {
2662 status = BAD_VALUE;
2663 }
2664 }
2665 return status;
2666}
2667
2668void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2669{
2670 for (size_t i = 0; i < mTracks.size(); ++i) {
2671 sp<Track> track = mTracks[i];
2672 if (track->auxEffectId() == effectId) {
2673 attachAuxEffect_l(track, 0);
2674 }
2675 }
2676}
2677
2678bool AudioFlinger::PlaybackThread::threadLoop()
2679{
2680 Vector< sp<Track> > tracksToRemove;
2681
2682 standbyTime = systemTime();
2683
2684 // MIXER
2685 nsecs_t lastWarning = 0;
2686
2687 // DUPLICATING
2688 // FIXME could this be made local to while loop?
2689 writeFrames = 0;
2690
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002691 int lastGeneration = 0;
2692
Eric Laurent81784c32012-11-19 14:55:58 -08002693 cacheParameters_l();
2694 sleepTime = idleSleepTime;
2695
2696 if (mType == MIXER) {
2697 sleepTimeShift = 0;
2698 }
2699
2700 CpuStats cpuStats;
2701 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2702
2703 acquireWakeLock();
2704
Glenn Kasten9e58b552013-01-18 15:09:48 -08002705 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2706 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2707 // and then that string will be logged at the next convenient opportunity.
2708 const char *logString = NULL;
2709
Eric Laurent664539d2013-09-23 18:24:31 -07002710 checkSilentMode_l();
2711
Eric Laurent81784c32012-11-19 14:55:58 -08002712 while (!exitPending())
2713 {
2714 cpuStats.sample(myName);
2715
2716 Vector< sp<EffectChain> > effectChains;
2717
Eric Laurent81784c32012-11-19 14:55:58 -08002718 { // scope for mLock
2719
2720 Mutex::Autolock _l(mLock);
2721
Eric Laurent021cf962014-05-13 10:18:14 -07002722 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07002723
Glenn Kasten9e58b552013-01-18 15:09:48 -08002724 if (logString != NULL) {
2725 mNBLogWriter->logTimestamp();
2726 mNBLogWriter->log(logString);
2727 logString = NULL;
2728 }
2729
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002730 // Gather the framesReleased counters for all active tracks,
2731 // and latch them atomically with the timestamp.
2732 // FIXME We're using raw pointers as indices. A unique track ID would be a better index.
2733 mLatchD.mFramesReleased.clear();
2734 size_t size = mActiveTracks.size();
2735 for (size_t i = 0; i < size; i++) {
2736 sp<Track> t = mActiveTracks[i].promote();
2737 if (t != 0) {
2738 mLatchD.mFramesReleased.add(t.get(),
2739 t->mAudioTrackServerProxy->framesReleased());
2740 }
2741 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002742 if (mLatchDValid) {
2743 mLatchQ = mLatchD;
2744 mLatchDValid = false;
2745 mLatchQValid = true;
2746 }
2747
Eric Laurent81784c32012-11-19 14:55:58 -08002748 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002749 if (mSignalPending) {
2750 // A signal was raised while we were unlocked
2751 mSignalPending = false;
2752 } else if (waitingAsyncCallback_l()) {
2753 if (exitPending()) {
2754 break;
2755 }
Marco Nelissen078538c2015-05-12 09:17:57 -07002756 bool released = false;
2757 // The following works around a bug in the offload driver. Ideally we would release
2758 // the wake lock every time, but that causes the last offload buffer(s) to be
2759 // dropped while the device is on battery, so we need to hold a wake lock during
2760 // the drain phase.
2761 if (mBytesRemaining && !(mDrainSequence & 1)) {
2762 releaseWakeLock_l();
2763 released = true;
2764 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002765 mWakeLockUids.clear();
2766 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002767 ALOGV("wait async completion");
2768 mWaitWorkCV.wait(mLock);
2769 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07002770 if (released) {
2771 acquireWakeLock_l();
2772 }
Eric Laurent972a1732013-09-04 09:42:59 -07002773 standbyTime = systemTime() + standbyDelay;
2774 sleepTime = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002775
2776 continue;
2777 }
2778 if ((!mActiveTracks.size() && systemTime() > standbyTime) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08002779 isSuspended()) {
2780 // put audio hardware into standby after short delay
2781 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002782
2783 threadLoop_standby();
2784
2785 mStandby = true;
2786 }
2787
2788 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2789 // we're about to wait, flush the binder command buffer
2790 IPCThreadState::self()->flushCommands();
2791
2792 clearOutputTracks();
2793
2794 if (exitPending()) {
2795 break;
2796 }
2797
2798 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002799 mWakeLockUids.clear();
2800 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002801 // wait until we have something to do...
2802 ALOGV("%s going to sleep", myName.string());
2803 mWaitWorkCV.wait(mLock);
2804 ALOGV("%s waking up", myName.string());
2805 acquireWakeLock_l();
2806
2807 mMixerStatus = MIXER_IDLE;
2808 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2809 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002810 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002811 checkSilentMode_l();
2812
2813 standbyTime = systemTime() + standbyDelay;
2814 sleepTime = idleSleepTime;
2815 if (mType == MIXER) {
2816 sleepTimeShift = 0;
2817 }
2818
2819 continue;
2820 }
2821 }
Eric Laurent81784c32012-11-19 14:55:58 -08002822 // mMixerStatusIgnoringFastTracks is also updated internally
2823 mMixerStatus = prepareTracks_l(&tracksToRemove);
2824
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002825 // compare with previously applied list
2826 if (lastGeneration != mActiveTracksGeneration) {
2827 // update wakelock
2828 updateWakeLockUids_l(mWakeLockUids);
2829 lastGeneration = mActiveTracksGeneration;
2830 }
2831
Eric Laurent81784c32012-11-19 14:55:58 -08002832 // prevent any changes in effect chain list and in each effect chain
2833 // during mixing and effect process as the audio buffers could be deleted
2834 // or modified if an effect is created or deleted
2835 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002836 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08002837
Eric Laurentbfb1b832013-01-07 09:53:42 -08002838 if (mBytesRemaining == 0) {
2839 mCurrentWriteLength = 0;
2840 if (mMixerStatus == MIXER_TRACKS_READY) {
2841 // threadLoop_mix() sets mCurrentWriteLength
2842 threadLoop_mix();
2843 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
2844 && (mMixerStatus != MIXER_DRAIN_ALL)) {
2845 // threadLoop_sleepTime sets sleepTime to 0 if data
2846 // must be written to HAL
2847 threadLoop_sleepTime();
2848 if (sleepTime == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08002849 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002850 }
2851 }
Andy Hung98ef9782014-03-04 14:46:50 -08002852 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
2853 // mMixerBuffer with data if mMixerBufferValid is true and sleepTime == 0.
2854 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
2855 // or mSinkBuffer (if there are no effects).
2856 //
2857 // This is done pre-effects computation; if effects change to
2858 // support higher precision, this needs to move.
2859 //
2860 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
2861 // TODO use sleepTime == 0 as an additional condition.
2862 if (mMixerBufferValid) {
2863 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
2864 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
2865
2866 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
2867 mNormalFrameCount * mChannelCount);
2868 }
2869
Eric Laurentbfb1b832013-01-07 09:53:42 -08002870 mBytesRemaining = mCurrentWriteLength;
2871 if (isSuspended()) {
2872 sleepTime = suspendSleepTimeUs();
2873 // simulate write to HAL when suspended
Andy Hung25c2dac2014-02-27 14:56:00 -08002874 mBytesWritten += mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002875 mBytesRemaining = 0;
2876 }
Eric Laurent81784c32012-11-19 14:55:58 -08002877
Eric Laurentbfb1b832013-01-07 09:53:42 -08002878 // only process effects if we're going to write
Eric Laurent59fe0102013-09-27 18:48:26 -07002879 if (sleepTime == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002880 for (size_t i = 0; i < effectChains.size(); i ++) {
2881 effectChains[i]->process_l();
2882 }
Eric Laurent81784c32012-11-19 14:55:58 -08002883 }
2884 }
Eric Laurent59fe0102013-09-27 18:48:26 -07002885 // Process effect chains for offloaded thread even if no audio
2886 // was read from audio track: process only updates effect state
2887 // and thus does have to be synchronized with audio writes but may have
2888 // to be called while waiting for async write callback
2889 if (mType == OFFLOAD) {
2890 for (size_t i = 0; i < effectChains.size(); i ++) {
2891 effectChains[i]->process_l();
2892 }
2893 }
Eric Laurent81784c32012-11-19 14:55:58 -08002894
Andy Hung98ef9782014-03-04 14:46:50 -08002895 // Only if the Effects buffer is enabled and there is data in the
2896 // Effects buffer (buffer valid), we need to
2897 // copy into the sink buffer.
2898 // TODO use sleepTime == 0 as an additional condition.
2899 if (mEffectBufferValid) {
2900 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
2901 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
2902 mNormalFrameCount * mChannelCount);
2903 }
2904
Eric Laurent81784c32012-11-19 14:55:58 -08002905 // enable changes in effect chain
2906 unlockEffectChains(effectChains);
2907
Eric Laurentbfb1b832013-01-07 09:53:42 -08002908 if (!waitingAsyncCallback()) {
2909 // sleepTime == 0 means we must write to audio hardware
2910 if (sleepTime == 0) {
2911 if (mBytesRemaining) {
2912 ssize_t ret = threadLoop_write();
2913 if (ret < 0) {
2914 mBytesRemaining = 0;
2915 } else {
2916 mBytesWritten += ret;
2917 mBytesRemaining -= ret;
2918 }
2919 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
2920 (mMixerStatus == MIXER_DRAIN_ALL)) {
2921 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08002922 }
Glenn Kasten4944acb2013-08-19 08:39:20 -07002923 if (mType == MIXER) {
2924 // write blocked detection
2925 nsecs_t now = systemTime();
2926 nsecs_t delta = now - mLastWriteTime;
2927 if (!mStandby && delta > maxPeriod) {
2928 mNumDelayedWrites++;
2929 if ((now - lastWarning) > kWarningThrottleNs) {
2930 ATRACE_NAME("underrun");
2931 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2932 ns2ms(delta), mNumDelayedWrites, this);
2933 lastWarning = now;
2934 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002935 }
2936 }
Eric Laurent81784c32012-11-19 14:55:58 -08002937
Eric Laurentbfb1b832013-01-07 09:53:42 -08002938 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07002939 ATRACE_BEGIN("sleep");
Eric Laurentbfb1b832013-01-07 09:53:42 -08002940 usleep(sleepTime);
Glenn Kastene7754022014-10-31 12:11:26 -07002941 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002942 }
Eric Laurent81784c32012-11-19 14:55:58 -08002943 }
2944
2945 // Finally let go of removed track(s), without the lock held
2946 // since we can't guarantee the destructors won't acquire that
2947 // same lock. This will also mutate and push a new fast mixer state.
2948 threadLoop_removeTracks(tracksToRemove);
2949 tracksToRemove.clear();
2950
2951 // FIXME I don't understand the need for this here;
2952 // it was in the original code but maybe the
2953 // assignment in saveOutputTracks() makes this unnecessary?
2954 clearOutputTracks();
2955
2956 // Effect chains will be actually deleted here if they were removed from
2957 // mEffectChains list during mixing or effects processing
2958 effectChains.clear();
2959
2960 // FIXME Note that the above .clear() is no longer necessary since effectChains
2961 // is now local to this block, but will keep it for now (at least until merge done).
2962 }
2963
Eric Laurentbfb1b832013-01-07 09:53:42 -08002964 threadLoop_exit();
2965
Eric Laurentcf817a22014-08-04 20:36:31 -07002966 if (!mStandby) {
2967 threadLoop_standby();
2968 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08002969 }
2970
2971 releaseWakeLock();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002972 mWakeLockUids.clear();
2973 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002974
2975 ALOGV("Thread %p type %d exiting", this, mType);
2976 return false;
2977}
2978
Eric Laurentbfb1b832013-01-07 09:53:42 -08002979// removeTracks_l() must be called with ThreadBase::mLock held
2980void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
2981{
2982 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002983 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002984 for (size_t i=0 ; i<count ; i++) {
2985 const sp<Track>& track = tracksToRemove.itemAt(i);
2986 mActiveTracks.remove(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002987 mWakeLockUids.remove(track->uid());
2988 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002989 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
2990 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2991 if (chain != 0) {
2992 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
2993 track->sessionId());
2994 chain->decActiveTrackCnt();
2995 }
2996 if (track->isTerminated()) {
2997 removeTrack_l(track);
2998 }
2999 }
3000 }
3001
3002}
Eric Laurent81784c32012-11-19 14:55:58 -08003003
Eric Laurentaccc1472013-09-20 09:36:34 -07003004status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3005{
3006 if (mNormalSink != 0) {
3007 return mNormalSink->getTimestamp(timestamp);
3008 }
Andy Hung9a1c8892014-12-03 11:37:42 -08003009 if ((mType == OFFLOAD || mType == DIRECT)
3010 && mOutput != NULL && mOutput->stream->get_presentation_position) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003011 uint64_t position64;
Phil Burk062e67a2015-02-11 13:40:50 -08003012 int ret = mOutput->getPresentationPosition(&position64, &timestamp.mTime);
Eric Laurentaccc1472013-09-20 09:36:34 -07003013 if (ret == 0) {
3014 timestamp.mPosition = (uint32_t)position64;
3015 return NO_ERROR;
3016 }
3017 }
3018 return INVALID_OPERATION;
3019}
Eric Laurent1c333e22014-05-20 10:48:17 -07003020
Eric Laurent054d9d32015-04-24 08:48:48 -07003021status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
3022 audio_patch_handle_t *handle)
3023{
3024 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3025 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3026 if (mFastMixer != 0) {
3027 FastMixerStateQueue *sq = mFastMixer->sq();
3028 FastMixerState *state = sq->begin();
3029 if (!(state->mCommand & FastMixerState::IDLE)) {
3030 previousCommand = state->mCommand;
3031 state->mCommand = FastMixerState::HOT_IDLE;
3032 sq->end();
3033 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3034 } else {
3035 sq->end(false /*didModify*/);
3036 }
3037 }
3038 status_t status = PlaybackThread::createAudioPatch_l(patch, handle);
3039
3040 if (!(previousCommand & FastMixerState::IDLE)) {
3041 ALOG_ASSERT(mFastMixer != 0);
3042 FastMixerStateQueue *sq = mFastMixer->sq();
3043 FastMixerState *state = sq->begin();
3044 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3045 state->mCommand = previousCommand;
3046 sq->end();
3047 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3048 }
3049
3050 return status;
3051}
3052
Eric Laurent1c333e22014-05-20 10:48:17 -07003053status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3054 audio_patch_handle_t *handle)
3055{
3056 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003057
3058 // store new device and send to effects
3059 audio_devices_t type = AUDIO_DEVICE_NONE;
3060 for (unsigned int i = 0; i < patch->num_sinks; i++) {
3061 type |= patch->sinks[i].ext.device.type;
3062 }
3063
3064#ifdef ADD_BATTERY_DATA
3065 // when changing the audio output device, call addBatteryData to notify
3066 // the change
3067 if (mOutDevice != type) {
3068 uint32_t params = 0;
3069 // check whether speaker is on
3070 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3071 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003072 }
3073
Eric Laurent054d9d32015-04-24 08:48:48 -07003074 audio_devices_t deviceWithoutSpeaker
3075 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3076 // check if any other device (except speaker) is on
3077 if (type & deviceWithoutSpeaker) {
3078 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3079 }
3080
3081 if (params != 0) {
3082 addBatteryData(params);
3083 }
3084 }
3085#endif
3086
3087 for (size_t i = 0; i < mEffectChains.size(); i++) {
3088 mEffectChains[i]->setDevice_l(type);
3089 }
3090 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003091 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003092
3093 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003094 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
3095 status = hwDevice->create_audio_patch(hwDevice,
3096 patch->num_sources,
3097 patch->sources,
3098 patch->num_sinks,
3099 patch->sinks,
3100 handle);
3101 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003102 char *address;
3103 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3104 //FIXME: we only support address on first sink with HAL version < 3.0
3105 address = audio_device_address_to_parameter(
3106 patch->sinks[0].ext.device.type,
3107 patch->sinks[0].ext.device.address);
3108 } else {
3109 address = (char *)calloc(1, 1);
3110 }
3111 AudioParameter param = AudioParameter(String8(address));
3112 free(address);
3113 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), (int)type);
3114 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3115 param.toString().string());
3116 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003117 }
Eric Laurent296fb132015-05-01 11:38:42 -07003118 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent1c333e22014-05-20 10:48:17 -07003119 return status;
3120}
3121
Eric Laurent054d9d32015-04-24 08:48:48 -07003122status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3123{
3124 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3125 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3126 if (mFastMixer != 0) {
3127 FastMixerStateQueue *sq = mFastMixer->sq();
3128 FastMixerState *state = sq->begin();
3129 if (!(state->mCommand & FastMixerState::IDLE)) {
3130 previousCommand = state->mCommand;
3131 state->mCommand = FastMixerState::HOT_IDLE;
3132 sq->end();
3133 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3134 } else {
3135 sq->end(false /*didModify*/);
3136 }
3137 }
3138
3139 status_t status = PlaybackThread::releaseAudioPatch_l(handle);
3140
3141 if (!(previousCommand & FastMixerState::IDLE)) {
3142 ALOG_ASSERT(mFastMixer != 0);
3143 FastMixerStateQueue *sq = mFastMixer->sq();
3144 FastMixerState *state = sq->begin();
3145 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3146 state->mCommand = previousCommand;
3147 sq->end();
3148 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3149 }
3150
3151 return status;
3152}
3153
Eric Laurent1c333e22014-05-20 10:48:17 -07003154status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3155{
3156 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003157
3158 mOutDevice = AUDIO_DEVICE_NONE;
3159
Eric Laurent1c333e22014-05-20 10:48:17 -07003160 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
3161 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
3162 status = hwDevice->release_audio_patch(hwDevice, handle);
3163 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003164 AudioParameter param;
3165 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
3166 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3167 param.toString().string());
Eric Laurent1c333e22014-05-20 10:48:17 -07003168 }
3169 return status;
3170}
3171
Eric Laurent83b88082014-06-20 18:31:16 -07003172void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3173{
3174 Mutex::Autolock _l(mLock);
3175 mTracks.add(track);
3176}
3177
3178void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3179{
3180 Mutex::Autolock _l(mLock);
3181 destroyTrack_l(track);
3182}
3183
3184void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
3185{
3186 ThreadBase::getAudioPortConfig(config);
3187 config->role = AUDIO_PORT_ROLE_SOURCE;
3188 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3189 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
3190}
3191
Eric Laurent81784c32012-11-19 14:55:58 -08003192// ----------------------------------------------------------------------------
3193
3194AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurent72e3f392015-05-20 14:43:50 -07003195 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
3196 : PlaybackThread(audioFlinger, output, id, device, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08003197 // mAudioMixer below
3198 // mFastMixer below
3199 mFastMixerFutex(0)
3200 // mOutputSink below
3201 // mPipeSink below
3202 // mNormalSink below
3203{
3204 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07003205 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, "
Eric Laurent81784c32012-11-19 14:55:58 -08003206 "mFrameCount=%d, mNormalFrameCount=%d",
3207 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3208 mNormalFrameCount);
3209 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3210
Andy Hungfbfc3952015-01-15 13:33:51 -08003211 if (type == DUPLICATING) {
3212 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3213 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3214 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3215 return;
3216 }
Eric Laurent81784c32012-11-19 14:55:58 -08003217 // create an NBAIO sink for the HAL output stream, and negotiate
3218 mOutputSink = new AudioStreamOutSink(output->stream);
3219 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003220 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Eric Laurent81784c32012-11-19 14:55:58 -08003221 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
3222 ALOG_ASSERT(index == 0);
3223
3224 // initialize fast mixer depending on configuration
3225 bool initFastMixer;
3226 switch (kUseFastMixer) {
3227 case FastMixer_Never:
3228 initFastMixer = false;
3229 break;
3230 case FastMixer_Always:
3231 initFastMixer = true;
3232 break;
3233 case FastMixer_Static:
3234 case FastMixer_Dynamic:
3235 initFastMixer = mFrameCount < mNormalFrameCount;
3236 break;
3237 }
3238 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003239 audio_format_t fastMixerFormat;
3240 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3241 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3242 } else {
3243 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3244 }
3245 if (mFormat != fastMixerFormat) {
3246 // change our Sink format to accept our intermediate precision
3247 mFormat = fastMixerFormat;
3248 free(mSinkBuffer);
3249 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3250 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3251 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3252 }
Eric Laurent81784c32012-11-19 14:55:58 -08003253
3254 // create a MonoPipe to connect our submix to FastMixer
3255 NBAIO_Format format = mOutputSink->format();
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003256 NBAIO_Format origformat = format;
Andy Hung1258c1a2014-05-23 21:22:17 -07003257 // adjust format to match that of the Fast Mixer
Glenn Kasten97b7b752014-09-28 13:04:24 -07003258 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003259 format.mFormat = fastMixerFormat;
3260 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3261
Eric Laurent81784c32012-11-19 14:55:58 -08003262 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3263 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3264 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3265 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3266 const NBAIO_Format offers[1] = {format};
3267 size_t numCounterOffers = 0;
3268 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
3269 ALOG_ASSERT(index == 0);
3270 monoPipe->setAvgFrames((mScreenState & 1) ?
3271 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3272 mPipeSink = monoPipe;
3273
Glenn Kasten46909e72013-02-26 09:20:22 -08003274#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08003275 if (mTeeSinkOutputEnabled) {
3276 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003277 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
3278 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08003279 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003280 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003281 ALOG_ASSERT(index == 0);
3282 mTeeSink = teeSink;
3283 PipeReader *teeSource = new PipeReader(*teeSink);
3284 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003285 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003286 ALOG_ASSERT(index == 0);
3287 mTeeSource = teeSource;
3288 }
Glenn Kasten46909e72013-02-26 09:20:22 -08003289#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003290
3291 // create fast mixer and configure it initially with just one fast track for our submix
3292 mFastMixer = new FastMixer();
3293 FastMixerStateQueue *sq = mFastMixer->sq();
3294#ifdef STATE_QUEUE_DUMP
3295 sq->setObserverDump(&mStateQueueObserverDump);
3296 sq->setMutatorDump(&mStateQueueMutatorDump);
3297#endif
3298 FastMixerState *state = sq->begin();
3299 FastTrack *fastTrack = &state->mFastTracks[0];
3300 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3301 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3302 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003303 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3304 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003305 fastTrack->mGeneration++;
3306 state->mFastTracksGen++;
3307 state->mTrackMask = 1;
3308 // fast mixer will use the HAL output sink
3309 state->mOutputSink = mOutputSink.get();
3310 state->mOutputSinkGen++;
3311 state->mFrameCount = mFrameCount;
3312 state->mCommand = FastMixerState::COLD_IDLE;
3313 // already done in constructor initialization list
3314 //mFastMixerFutex = 0;
3315 state->mColdFutexAddr = &mFastMixerFutex;
3316 state->mColdGen++;
3317 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08003318#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003319 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08003320#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08003321 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3322 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003323 sq->end();
3324 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3325
3326 // start the fast mixer
3327 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3328 pid_t tid = mFastMixer->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003329 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003330
3331#ifdef AUDIO_WATCHDOG
3332 // create and start the watchdog
3333 mAudioWatchdog = new AudioWatchdog();
3334 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3335 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3336 tid = mAudioWatchdog->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003337 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003338#endif
3339
Eric Laurent81784c32012-11-19 14:55:58 -08003340 }
3341
3342 switch (kUseFastMixer) {
3343 case FastMixer_Never:
3344 case FastMixer_Dynamic:
3345 mNormalSink = mOutputSink;
3346 break;
3347 case FastMixer_Always:
3348 mNormalSink = mPipeSink;
3349 break;
3350 case FastMixer_Static:
3351 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3352 break;
3353 }
3354}
3355
3356AudioFlinger::MixerThread::~MixerThread()
3357{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003358 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003359 FastMixerStateQueue *sq = mFastMixer->sq();
3360 FastMixerState *state = sq->begin();
3361 if (state->mCommand == FastMixerState::COLD_IDLE) {
3362 int32_t old = android_atomic_inc(&mFastMixerFutex);
3363 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003364 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003365 }
3366 }
3367 state->mCommand = FastMixerState::EXIT;
3368 sq->end();
3369 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3370 mFastMixer->join();
3371 // Though the fast mixer thread has exited, it's state queue is still valid.
3372 // We'll use that extract the final state which contains one remaining fast track
3373 // corresponding to our sub-mix.
3374 state = sq->begin();
3375 ALOG_ASSERT(state->mTrackMask == 1);
3376 FastTrack *fastTrack = &state->mFastTracks[0];
3377 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3378 delete fastTrack->mBufferProvider;
3379 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003380 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003381#ifdef AUDIO_WATCHDOG
3382 if (mAudioWatchdog != 0) {
3383 mAudioWatchdog->requestExit();
3384 mAudioWatchdog->requestExitAndWait();
3385 mAudioWatchdog.clear();
3386 }
3387#endif
3388 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003389 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003390 delete mAudioMixer;
3391}
3392
3393
3394uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3395{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003396 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003397 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3398 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3399 }
3400 return latency;
3401}
3402
3403
3404void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3405{
3406 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3407}
3408
Eric Laurentbfb1b832013-01-07 09:53:42 -08003409ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003410{
3411 // FIXME we should only do one push per cycle; confirm this is true
3412 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003413 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003414 FastMixerStateQueue *sq = mFastMixer->sq();
3415 FastMixerState *state = sq->begin();
3416 if (state->mCommand != FastMixerState::MIX_WRITE &&
3417 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3418 if (state->mCommand == FastMixerState::COLD_IDLE) {
3419 int32_t old = android_atomic_inc(&mFastMixerFutex);
3420 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003421 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003422 }
3423#ifdef AUDIO_WATCHDOG
3424 if (mAudioWatchdog != 0) {
3425 mAudioWatchdog->resume();
3426 }
3427#endif
3428 }
3429 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08003430#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003431 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08003432 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08003433#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003434 sq->end();
3435 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3436 if (kUseFastMixer == FastMixer_Dynamic) {
3437 mNormalSink = mPipeSink;
3438 }
3439 } else {
3440 sq->end(false /*didModify*/);
3441 }
3442 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003443 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003444}
3445
3446void AudioFlinger::MixerThread::threadLoop_standby()
3447{
3448 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003449 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003450 FastMixerStateQueue *sq = mFastMixer->sq();
3451 FastMixerState *state = sq->begin();
3452 if (!(state->mCommand & FastMixerState::IDLE)) {
3453 state->mCommand = FastMixerState::COLD_IDLE;
3454 state->mColdFutexAddr = &mFastMixerFutex;
3455 state->mColdGen++;
3456 mFastMixerFutex = 0;
3457 sq->end();
3458 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3459 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3460 if (kUseFastMixer == FastMixer_Dynamic) {
3461 mNormalSink = mOutputSink;
3462 }
3463#ifdef AUDIO_WATCHDOG
3464 if (mAudioWatchdog != 0) {
3465 mAudioWatchdog->pause();
3466 }
3467#endif
3468 } else {
3469 sq->end(false /*didModify*/);
3470 }
3471 }
3472 PlaybackThread::threadLoop_standby();
3473}
3474
Eric Laurentbfb1b832013-01-07 09:53:42 -08003475bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3476{
3477 return false;
3478}
3479
3480bool AudioFlinger::PlaybackThread::shouldStandby_l()
3481{
3482 return !mStandby;
3483}
3484
3485bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3486{
3487 Mutex::Autolock _l(mLock);
3488 return waitingAsyncCallback_l();
3489}
3490
Eric Laurent81784c32012-11-19 14:55:58 -08003491// shared by MIXER and DIRECT, overridden by DUPLICATING
3492void AudioFlinger::PlaybackThread::threadLoop_standby()
3493{
3494 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08003495 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003496 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003497 // discard any pending drain or write ack by incrementing sequence
3498 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3499 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003500 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003501 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3502 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003503 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003504 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003505}
3506
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003507void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3508{
3509 ALOGV("signal playback thread");
3510 broadcast_l();
3511}
3512
Eric Laurent81784c32012-11-19 14:55:58 -08003513void AudioFlinger::MixerThread::threadLoop_mix()
3514{
3515 // obtain the presentation timestamp of the next output buffer
3516 int64_t pts;
3517 status_t status = INVALID_OPERATION;
3518
3519 if (mNormalSink != 0) {
3520 status = mNormalSink->getNextWriteTimestamp(&pts);
3521 } else {
3522 status = mOutputSink->getNextWriteTimestamp(&pts);
3523 }
3524
3525 if (status != NO_ERROR) {
3526 pts = AudioBufferProvider::kInvalidPTS;
3527 }
3528
3529 // mix buffers...
3530 mAudioMixer->process(pts);
Andy Hung25c2dac2014-02-27 14:56:00 -08003531 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003532 // increase sleep time progressively when application underrun condition clears.
3533 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3534 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3535 // such that we would underrun the audio HAL.
3536 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
3537 sleepTimeShift--;
3538 }
3539 sleepTime = 0;
3540 standbyTime = systemTime() + standbyDelay;
3541 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003542
Eric Laurent81784c32012-11-19 14:55:58 -08003543}
3544
3545void AudioFlinger::MixerThread::threadLoop_sleepTime()
3546{
3547 // If no tracks are ready, sleep once for the duration of an output
3548 // buffer size, then write 0s to the output
3549 if (sleepTime == 0) {
3550 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3551 sleepTime = activeSleepTime >> sleepTimeShift;
3552 if (sleepTime < kMinThreadSleepTimeUs) {
3553 sleepTime = kMinThreadSleepTimeUs;
3554 }
3555 // reduce sleep time in case of consecutive application underruns to avoid
3556 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3557 // duration we would end up writing less data than needed by the audio HAL if
3558 // the condition persists.
3559 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3560 sleepTimeShift++;
3561 }
3562 } else {
3563 sleepTime = idleSleepTime;
3564 }
3565 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003566 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3567 // before effects processing or output.
3568 if (mMixerBufferValid) {
3569 memset(mMixerBuffer, 0, mMixerBufferSize);
3570 } else {
3571 memset(mSinkBuffer, 0, mSinkBufferSize);
3572 }
Eric Laurent81784c32012-11-19 14:55:58 -08003573 sleepTime = 0;
3574 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3575 "anticipated start");
3576 }
3577 // TODO add standby time extension fct of effect tail
3578}
3579
3580// prepareTracks_l() must be called with ThreadBase::mLock held
3581AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3582 Vector< sp<Track> > *tracksToRemove)
3583{
3584
3585 mixer_state mixerStatus = MIXER_IDLE;
3586 // find out which tracks need to be processed
3587 size_t count = mActiveTracks.size();
3588 size_t mixedTracks = 0;
3589 size_t tracksWithEffect = 0;
3590 // counts only _active_ fast tracks
3591 size_t fastTracks = 0;
3592 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
3593
3594 float masterVolume = mMasterVolume;
3595 bool masterMute = mMasterMute;
3596
3597 if (masterMute) {
3598 masterVolume = 0;
3599 }
3600 // Delegate master volume control to effect in output mix effect chain if needed
3601 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3602 if (chain != 0) {
3603 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
3604 chain->setVolume_l(&v, &v);
3605 masterVolume = (float)((v + (1 << 23)) >> 24);
3606 chain.clear();
3607 }
3608
3609 // prepare a new state to push
3610 FastMixerStateQueue *sq = NULL;
3611 FastMixerState *state = NULL;
3612 bool didModify = false;
3613 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003614 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003615 sq = mFastMixer->sq();
3616 state = sq->begin();
3617 }
3618
Andy Hung69aed5f2014-02-25 17:24:40 -08003619 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08003620 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08003621
Eric Laurent81784c32012-11-19 14:55:58 -08003622 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003623 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003624 if (t == 0) {
3625 continue;
3626 }
3627
3628 // this const just means the local variable doesn't change
3629 Track* const track = t.get();
3630
3631 // process fast tracks
3632 if (track->isFastTrack()) {
3633
3634 // It's theoretically possible (though unlikely) for a fast track to be created
3635 // and then removed within the same normal mix cycle. This is not a problem, as
3636 // the track never becomes active so it's fast mixer slot is never touched.
3637 // The converse, of removing an (active) track and then creating a new track
3638 // at the identical fast mixer slot within the same normal mix cycle,
3639 // is impossible because the slot isn't marked available until the end of each cycle.
3640 int j = track->mFastIndex;
3641 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
3642 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
3643 FastTrack *fastTrack = &state->mFastTracks[j];
3644
3645 // Determine whether the track is currently in underrun condition,
3646 // and whether it had a recent underrun.
3647 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
3648 FastTrackUnderruns underruns = ftDump->mUnderruns;
3649 uint32_t recentFull = (underruns.mBitFields.mFull -
3650 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
3651 uint32_t recentPartial = (underruns.mBitFields.mPartial -
3652 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
3653 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
3654 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
3655 uint32_t recentUnderruns = recentPartial + recentEmpty;
3656 track->mObservedUnderruns = underruns;
3657 // don't count underruns that occur while stopping or pausing
3658 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07003659 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
3660 recentUnderruns > 0) {
3661 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
3662 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003663 }
3664
3665 // This is similar to the state machine for normal tracks,
3666 // with a few modifications for fast tracks.
3667 bool isActive = true;
3668 switch (track->mState) {
3669 case TrackBase::STOPPING_1:
3670 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08003671 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003672 track->mState = TrackBase::STOPPING_2;
3673 }
3674 break;
3675 case TrackBase::PAUSING:
3676 // ramp down is not yet implemented
3677 track->setPaused();
3678 break;
3679 case TrackBase::RESUMING:
3680 // ramp up is not yet implemented
3681 track->mState = TrackBase::ACTIVE;
3682 break;
3683 case TrackBase::ACTIVE:
3684 if (recentFull > 0 || recentPartial > 0) {
3685 // track has provided at least some frames recently: reset retry count
3686 track->mRetryCount = kMaxTrackRetries;
3687 }
3688 if (recentUnderruns == 0) {
3689 // no recent underruns: stay active
3690 break;
3691 }
3692 // there has recently been an underrun of some kind
3693 if (track->sharedBuffer() == 0) {
3694 // were any of the recent underruns "empty" (no frames available)?
3695 if (recentEmpty == 0) {
3696 // no, then ignore the partial underruns as they are allowed indefinitely
3697 break;
3698 }
3699 // there has recently been an "empty" underrun: decrement the retry counter
3700 if (--(track->mRetryCount) > 0) {
3701 break;
3702 }
3703 // indicate to client process that the track was disabled because of underrun;
3704 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003705 android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003706 // remove from active list, but state remains ACTIVE [confusing but true]
3707 isActive = false;
3708 break;
3709 }
3710 // fall through
3711 case TrackBase::STOPPING_2:
3712 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003713 case TrackBase::STOPPED:
3714 case TrackBase::FLUSHED: // flush() while active
3715 // Check for presentation complete if track is inactive
3716 // We have consumed all the buffers of this track.
3717 // This would be incomplete if we auto-paused on underrun
3718 {
3719 size_t audioHALFrames =
3720 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3721 size_t framesWritten = mBytesWritten / mFrameSize;
3722 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
3723 // track stays in active list until presentation is complete
3724 break;
3725 }
3726 }
3727 if (track->isStopping_2()) {
3728 track->mState = TrackBase::STOPPED;
3729 }
3730 if (track->isStopped()) {
3731 // Can't reset directly, as fast mixer is still polling this track
3732 // track->reset();
3733 // So instead mark this track as needing to be reset after push with ack
3734 resetMask |= 1 << i;
3735 }
3736 isActive = false;
3737 break;
3738 case TrackBase::IDLE:
3739 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08003740 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08003741 }
3742
3743 if (isActive) {
3744 // was it previously inactive?
3745 if (!(state->mTrackMask & (1 << j))) {
3746 ExtendedAudioBufferProvider *eabp = track;
3747 VolumeProvider *vp = track;
3748 fastTrack->mBufferProvider = eabp;
3749 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08003750 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003751 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08003752 fastTrack->mGeneration++;
3753 state->mTrackMask |= 1 << j;
3754 didModify = true;
3755 // no acknowledgement required for newly active tracks
3756 }
3757 // cache the combined master volume and stream type volume for fast mixer; this
3758 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08003759 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08003760 ++fastTracks;
3761 } else {
3762 // was it previously active?
3763 if (state->mTrackMask & (1 << j)) {
3764 fastTrack->mBufferProvider = NULL;
3765 fastTrack->mGeneration++;
3766 state->mTrackMask &= ~(1 << j);
3767 didModify = true;
3768 // If any fast tracks were removed, we must wait for acknowledgement
3769 // because we're about to decrement the last sp<> on those tracks.
3770 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3771 } else {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003772 LOG_ALWAYS_FATAL("fast track %d should have been active", j);
Eric Laurent81784c32012-11-19 14:55:58 -08003773 }
3774 tracksToRemove->add(track);
3775 // Avoids a misleading display in dumpsys
3776 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
3777 }
3778 continue;
3779 }
3780
3781 { // local variable scope to avoid goto warning
3782
3783 audio_track_cblk_t* cblk = track->cblk();
3784
3785 // The first time a track is added we wait
3786 // for all its buffers to be filled before processing it
3787 int name = track->name();
3788 // make sure that we have enough frames to mix one full buffer.
3789 // enforce this condition only once to enable draining the buffer in case the client
3790 // app does not call stop() and relies on underrun to stop:
3791 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
3792 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003793 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07003794 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07003795 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07003796
3797 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07003798 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07003799 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
3800 // add frames already consumed but not yet released by the resampler
3801 // because mAudioTrackServerProxy->framesReady() will include these frames
3802 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
3803
Eric Laurent81784c32012-11-19 14:55:58 -08003804 uint32_t minFrames = 1;
3805 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
3806 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003807 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08003808 }
Eric Laurent13e4c962013-12-20 17:36:01 -08003809
3810 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07003811 if (ATRACE_ENABLED()) {
3812 // I wish we had formatted trace names
3813 char traceName[16];
3814 strcpy(traceName, "nRdy");
3815 int name = track->name();
3816 if (AudioMixer::TRACK0 <= name &&
3817 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
3818 name -= AudioMixer::TRACK0;
3819 traceName[4] = (name / 10) + '0';
3820 traceName[5] = (name % 10) + '0';
3821 } else {
3822 traceName[4] = '?';
3823 traceName[5] = '?';
3824 }
3825 traceName[6] = '\0';
3826 ATRACE_INT(traceName, framesReady);
3827 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003828 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08003829 !track->isPaused() && !track->isTerminated())
3830 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003831 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003832
3833 mixedTracks++;
3834
Andy Hung69aed5f2014-02-25 17:24:40 -08003835 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
3836 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08003837 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08003838 if (track->mainBuffer() != mSinkBuffer &&
3839 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08003840 if (mEffectBufferEnabled) {
3841 mEffectBufferValid = true; // Later can set directly.
3842 }
Eric Laurent81784c32012-11-19 14:55:58 -08003843 chain = getEffectChain_l(track->sessionId());
3844 // Delegate volume control to effect in track effect chain if needed
3845 if (chain != 0) {
3846 tracksWithEffect++;
3847 } else {
3848 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
3849 "session %d",
3850 name, track->sessionId());
3851 }
3852 }
3853
3854
3855 int param = AudioMixer::VOLUME;
3856 if (track->mFillingUpStatus == Track::FS_FILLED) {
3857 // no ramp for the first volume setting
3858 track->mFillingUpStatus = Track::FS_ACTIVE;
3859 if (track->mState == TrackBase::RESUMING) {
3860 track->mState = TrackBase::ACTIVE;
3861 param = AudioMixer::RAMP_VOLUME;
3862 }
3863 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003864 // FIXME should not make a decision based on mServer
3865 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003866 // If the track is stopped before the first frame was mixed,
3867 // do not apply ramp
3868 param = AudioMixer::RAMP_VOLUME;
3869 }
3870
3871 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07003872 uint32_t vl, vr; // in U8.24 integer format
3873 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08003874 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07003875 vl = vr = 0;
3876 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08003877 if (track->isPausing()) {
3878 track->setPaused();
3879 }
3880 } else {
3881
3882 // read original volumes with volume control
3883 float typeVolume = mStreamTypes[track->streamType()].volume;
3884 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003885 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07003886 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07003887 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
3888 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08003889 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07003890 if (vlf > GAIN_FLOAT_UNITY) {
3891 ALOGV("Track left volume out of range: %.3g", vlf);
3892 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003893 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07003894 if (vrf > GAIN_FLOAT_UNITY) {
3895 ALOGV("Track right volume out of range: %.3g", vrf);
3896 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003897 }
3898 // now apply the master volume and stream type volume
Andy Hung6be49402014-05-30 10:42:03 -07003899 vlf *= v;
3900 vrf *= v;
Eric Laurent81784c32012-11-19 14:55:58 -08003901 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07003902 // then derive vl and vr as U8.24 versions for the effect chain
3903 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
3904 vl = (uint32_t) (scaleto8_24 * vlf);
3905 vr = (uint32_t) (scaleto8_24 * vrf);
3906 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08003907 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08003908 // send level comes from shared memory and so may be corrupt
3909 if (sendLevel > MAX_GAIN_INT) {
3910 ALOGV("Track send level out of range: %04X", sendLevel);
3911 sendLevel = MAX_GAIN_INT;
3912 }
Andy Hung6be49402014-05-30 10:42:03 -07003913 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
3914 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08003915 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003916
Eric Laurent81784c32012-11-19 14:55:58 -08003917 // Delegate volume control to effect in track effect chain if needed
3918 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3919 // Do not ramp volume if volume is controlled by effect
3920 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08003921 // Update remaining floating point volume levels
3922 vlf = (float)vl / (1 << 24);
3923 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08003924 track->mHasVolumeController = true;
3925 } else {
3926 // force no volume ramp when volume controller was just disabled or removed
3927 // from effect chain to avoid volume spike
3928 if (track->mHasVolumeController) {
3929 param = AudioMixer::VOLUME;
3930 }
3931 track->mHasVolumeController = false;
3932 }
3933
Eric Laurent81784c32012-11-19 14:55:58 -08003934 // XXX: these things DON'T need to be done each time
3935 mAudioMixer->setBufferProvider(name, track);
3936 mAudioMixer->enable(name);
3937
Andy Hung6be49402014-05-30 10:42:03 -07003938 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
3939 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
3940 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08003941 mAudioMixer->setParameter(
3942 name,
3943 AudioMixer::TRACK,
3944 AudioMixer::FORMAT, (void *)track->format());
3945 mAudioMixer->setParameter(
3946 name,
3947 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003948 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07003949 mAudioMixer->setParameter(
3950 name,
3951 AudioMixer::TRACK,
3952 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08003953 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07003954 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003955 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08003956 if (reqSampleRate == 0) {
3957 reqSampleRate = mSampleRate;
3958 } else if (reqSampleRate > maxSampleRate) {
3959 reqSampleRate = maxSampleRate;
3960 }
Eric Laurent81784c32012-11-19 14:55:58 -08003961 mAudioMixer->setParameter(
3962 name,
3963 AudioMixer::RESAMPLE,
3964 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003965 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07003966
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07003967 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07003968 mAudioMixer->setParameter(
3969 name,
3970 AudioMixer::TIMESTRETCH,
3971 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07003972 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07003973
Andy Hung69aed5f2014-02-25 17:24:40 -08003974 /*
3975 * Select the appropriate output buffer for the track.
3976 *
Andy Hung98ef9782014-03-04 14:46:50 -08003977 * Tracks with effects go into their own effects chain buffer
3978 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08003979 *
3980 * Other tracks can use mMixerBuffer for higher precision
3981 * channel accumulation. If this buffer is enabled
3982 * (mMixerBufferEnabled true), then selected tracks will accumulate
3983 * into it.
3984 *
3985 */
3986 if (mMixerBufferEnabled
3987 && (track->mainBuffer() == mSinkBuffer
3988 || track->mainBuffer() == mMixerBuffer)) {
3989 mAudioMixer->setParameter(
3990 name,
3991 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08003992 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08003993 mAudioMixer->setParameter(
3994 name,
3995 AudioMixer::TRACK,
3996 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
3997 // TODO: override track->mainBuffer()?
3998 mMixerBufferValid = true;
3999 } else {
4000 mAudioMixer->setParameter(
4001 name,
4002 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004003 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08004004 mAudioMixer->setParameter(
4005 name,
4006 AudioMixer::TRACK,
4007 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
4008 }
Eric Laurent81784c32012-11-19 14:55:58 -08004009 mAudioMixer->setParameter(
4010 name,
4011 AudioMixer::TRACK,
4012 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
4013
4014 // reset retry count
4015 track->mRetryCount = kMaxTrackRetries;
4016
4017 // If one track is ready, set the mixer ready if:
4018 // - the mixer was not ready during previous round OR
4019 // - no other track is not ready
4020 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
4021 mixerStatus != MIXER_TRACKS_ENABLED) {
4022 mixerStatus = MIXER_TRACKS_READY;
4023 }
4024 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004025 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Glenn Kasten82aaf942013-07-17 16:05:07 -07004026 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004027 }
Eric Laurent81784c32012-11-19 14:55:58 -08004028 // clear effect chain input buffer if an active track underruns to avoid sending
4029 // previous audio buffer again to effects
4030 chain = getEffectChain_l(track->sessionId());
4031 if (chain != 0) {
4032 chain->clearInputBuffer();
4033 }
4034
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004035 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004036 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
4037 track->isStopped() || track->isPaused()) {
4038 // We have consumed all the buffers of this track.
4039 // Remove it from the list of active tracks.
4040 // TODO: use actual buffer filling status instead of latency when available from
4041 // audio HAL
4042 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
4043 size_t framesWritten = mBytesWritten / mFrameSize;
4044 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
4045 if (track->isStopped()) {
4046 track->reset();
4047 }
4048 tracksToRemove->add(track);
4049 }
4050 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08004051 // No buffers for this track. Give it a few chances to
4052 // fill a buffer, then remove it from active list.
4053 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004054 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004055 tracksToRemove->add(track);
4056 // indicate to client process that the track was disabled because of underrun;
4057 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07004058 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08004059 // If one track is not ready, mark the mixer also not ready if:
4060 // - the mixer was ready during previous round OR
4061 // - no other track is ready
4062 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
4063 mixerStatus != MIXER_TRACKS_READY) {
4064 mixerStatus = MIXER_TRACKS_ENABLED;
4065 }
4066 }
4067 mAudioMixer->disable(name);
4068 }
4069
4070 } // local variable scope to avoid goto warning
4071track_is_ready: ;
4072
4073 }
4074
4075 // Push the new FastMixer state if necessary
4076 bool pauseAudioWatchdog = false;
4077 if (didModify) {
4078 state->mFastTracksGen++;
4079 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4080 if (kUseFastMixer == FastMixer_Dynamic &&
4081 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4082 state->mCommand = FastMixerState::COLD_IDLE;
4083 state->mColdFutexAddr = &mFastMixerFutex;
4084 state->mColdGen++;
4085 mFastMixerFutex = 0;
4086 if (kUseFastMixer == FastMixer_Dynamic) {
4087 mNormalSink = mOutputSink;
4088 }
4089 // If we go into cold idle, need to wait for acknowledgement
4090 // so that fast mixer stops doing I/O.
4091 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4092 pauseAudioWatchdog = true;
4093 }
Eric Laurent81784c32012-11-19 14:55:58 -08004094 }
4095 if (sq != NULL) {
4096 sq->end(didModify);
4097 sq->push(block);
4098 }
4099#ifdef AUDIO_WATCHDOG
4100 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4101 mAudioWatchdog->pause();
4102 }
4103#endif
4104
4105 // Now perform the deferred reset on fast tracks that have stopped
4106 while (resetMask != 0) {
4107 size_t i = __builtin_ctz(resetMask);
4108 ALOG_ASSERT(i < count);
4109 resetMask &= ~(1 << i);
4110 sp<Track> t = mActiveTracks[i].promote();
4111 if (t == 0) {
4112 continue;
4113 }
4114 Track* track = t.get();
4115 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
4116 track->reset();
4117 }
4118
4119 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004120 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004121
Eric Laurent97d547d2014-09-02 14:45:53 -07004122 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
4123 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07004124 }
4125
4126 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07004127 // as long as there are effects we should clear the effects buffer, to avoid
4128 // passing a non-clean buffer to the effect chain
4129 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07004130 }
Andy Hung69aed5f2014-02-25 17:24:40 -08004131 // sink or mix buffer must be cleared if all tracks are connected to an
4132 // effect chain as in this case the mixer will not write to the sink or mix buffer
4133 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08004134 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4135 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08004136 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08004137 if (mMixerBufferValid) {
4138 memset(mMixerBuffer, 0, mMixerBufferSize);
4139 // TODO: In testing, mSinkBuffer below need not be cleared because
4140 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
4141 // after mixing.
4142 //
4143 // To enforce this guarantee:
4144 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4145 // (mixedTracks == 0 && fastTracks > 0))
4146 // must imply MIXER_TRACKS_READY.
4147 // Later, we may clear buffers regardless, and skip much of this logic.
4148 }
Andy Hung98ef9782014-03-04 14:46:50 -08004149 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07004150 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004151 }
4152
4153 // if any fast tracks, then status is ready
4154 mMixerStatusIgnoringFastTracks = mixerStatus;
4155 if (fastTracks > 0) {
4156 mixerStatus = MIXER_TRACKS_READY;
4157 }
4158 return mixerStatus;
4159}
4160
4161// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07004162int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
4163 audio_format_t format, int sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08004164{
Andy Hunge8a1ced2014-05-09 15:02:21 -07004165 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08004166}
4167
4168// deleteTrackName_l() must be called with ThreadBase::mLock held
4169void AudioFlinger::MixerThread::deleteTrackName_l(int name)
4170{
4171 ALOGV("remove track (%d) and delete from mixer", name);
4172 mAudioMixer->deleteTrackName(name);
4173}
4174
Eric Laurent10351942014-05-08 18:49:52 -07004175// checkForNewParameter_l() must be called with ThreadBase::mLock held
4176bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
4177 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004178{
Eric Laurent81784c32012-11-19 14:55:58 -08004179 bool reconfig = false;
4180
Eric Laurent10351942014-05-08 18:49:52 -07004181 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004182
Eric Laurent10351942014-05-08 18:49:52 -07004183 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
4184 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004185 if (mFastMixer != 0) {
Eric Laurent10351942014-05-08 18:49:52 -07004186 FastMixerStateQueue *sq = mFastMixer->sq();
4187 FastMixerState *state = sq->begin();
4188 if (!(state->mCommand & FastMixerState::IDLE)) {
4189 previousCommand = state->mCommand;
4190 state->mCommand = FastMixerState::HOT_IDLE;
4191 sq->end();
4192 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
4193 } else {
4194 sq->end(false /*didModify*/);
Eric Laurent81784c32012-11-19 14:55:58 -08004195 }
Eric Laurent10351942014-05-08 18:49:52 -07004196 }
Eric Laurent81784c32012-11-19 14:55:58 -08004197
Eric Laurent10351942014-05-08 18:49:52 -07004198 AudioParameter param = AudioParameter(keyValuePair);
4199 int value;
4200 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4201 reconfig = true;
4202 }
4203 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004204 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004205 status = BAD_VALUE;
4206 } else {
4207 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08004208 reconfig = true;
4209 }
Eric Laurent10351942014-05-08 18:49:52 -07004210 }
4211 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004212 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004213 status = BAD_VALUE;
4214 } else {
4215 // no need to save value, since it's constant
4216 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004217 }
Eric Laurent10351942014-05-08 18:49:52 -07004218 }
4219 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4220 // do not accept frame count changes if tracks are open as the track buffer
4221 // size depends on frame count and correct behavior would not be guaranteed
4222 // if frame count is changed after track creation
4223 if (!mTracks.isEmpty()) {
4224 status = INVALID_OPERATION;
4225 } else {
4226 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004227 }
Eric Laurent10351942014-05-08 18:49:52 -07004228 }
4229 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004230#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07004231 // when changing the audio output device, call addBatteryData to notify
4232 // the change
4233 if (mOutDevice != value) {
4234 uint32_t params = 0;
4235 // check whether speaker is on
4236 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
4237 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08004238 }
Eric Laurent10351942014-05-08 18:49:52 -07004239
4240 audio_devices_t deviceWithoutSpeaker
4241 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
4242 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07004243 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07004244 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4245 }
4246
4247 if (params != 0) {
4248 addBatteryData(params);
4249 }
4250 }
Eric Laurent81784c32012-11-19 14:55:58 -08004251#endif
4252
Eric Laurent10351942014-05-08 18:49:52 -07004253 // forward device change to effects that have requested to be
4254 // aware of attached audio device.
4255 if (value != AUDIO_DEVICE_NONE) {
4256 mOutDevice = value;
4257 for (size_t i = 0; i < mEffectChains.size(); i++) {
4258 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08004259 }
4260 }
Eric Laurent10351942014-05-08 18:49:52 -07004261 }
Eric Laurent81784c32012-11-19 14:55:58 -08004262
Eric Laurent10351942014-05-08 18:49:52 -07004263 if (status == NO_ERROR) {
4264 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4265 keyValuePair.string());
4266 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004267 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004268 mStandby = true;
4269 mBytesWritten = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004270 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Eric Laurent10351942014-05-08 18:49:52 -07004271 keyValuePair.string());
Eric Laurent81784c32012-11-19 14:55:58 -08004272 }
Eric Laurent10351942014-05-08 18:49:52 -07004273 if (status == NO_ERROR && reconfig) {
4274 readOutputParameters_l();
4275 delete mAudioMixer;
4276 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4277 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07004278 int name = getTrackName_l(mTracks[i]->mChannelMask,
4279 mTracks[i]->mFormat, mTracks[i]->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07004280 if (name < 0) {
4281 break;
4282 }
4283 mTracks[i]->mName = name;
4284 }
Eric Laurent73e26b62015-04-27 16:55:58 -07004285 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004286 }
Eric Laurent81784c32012-11-19 14:55:58 -08004287 }
4288
4289 if (!(previousCommand & FastMixerState::IDLE)) {
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004290 ALOG_ASSERT(mFastMixer != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08004291 FastMixerStateQueue *sq = mFastMixer->sq();
4292 FastMixerState *state = sq->begin();
4293 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
4294 state->mCommand = previousCommand;
4295 sq->end();
4296 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4297 }
4298
4299 return reconfig;
4300}
4301
4302
4303void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
4304{
4305 const size_t SIZE = 256;
4306 char buffer[SIZE];
4307 String8 result;
4308
4309 PlaybackThread::dumpInternals(fd, args);
4310
Elliott Hughes87cebad2014-05-22 10:14:43 -07004311 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Eric Laurent81784c32012-11-19 14:55:58 -08004312
4313 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten4182c4e2013-07-15 14:45:07 -07004314 const FastMixerDumpState copy(mFastMixerDumpState);
Eric Laurent81784c32012-11-19 14:55:58 -08004315 copy.dump(fd);
4316
4317#ifdef STATE_QUEUE_DUMP
4318 // Similar for state queue
4319 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4320 observerCopy.dump(fd);
4321 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4322 mutatorCopy.dump(fd);
4323#endif
4324
Glenn Kasten46909e72013-02-26 09:20:22 -08004325#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08004326 // Write the tee output to a .wav file
4327 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08004328#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004329
4330#ifdef AUDIO_WATCHDOG
4331 if (mAudioWatchdog != 0) {
4332 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4333 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4334 wdCopy.dump(fd);
4335 }
4336#endif
4337}
4338
4339uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4340{
4341 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4342}
4343
4344uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4345{
4346 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4347}
4348
4349void AudioFlinger::MixerThread::cacheParameters_l()
4350{
4351 PlaybackThread::cacheParameters_l();
4352
4353 // FIXME: Relaxed timing because of a certain device that can't meet latency
4354 // Should be reduced to 2x after the vendor fixes the driver issue
4355 // increase threshold again due to low power audio mode. The way this warning
4356 // threshold is calculated and its usefulness should be reconsidered anyway.
4357 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4358}
4359
4360// ----------------------------------------------------------------------------
4361
4362AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07004363 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device, bool systemReady)
4364 : PlaybackThread(audioFlinger, output, id, device, DIRECT, systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08004365 // mLeftVolFloat, mRightVolFloat
4366{
4367}
4368
Eric Laurentbfb1b832013-01-07 09:53:42 -08004369AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4370 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07004371 ThreadBase::type_t type, bool systemReady)
4372 : PlaybackThread(audioFlinger, output, id, device, type, systemReady)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004373 // mLeftVolFloat, mRightVolFloat
4374{
4375}
4376
Eric Laurent81784c32012-11-19 14:55:58 -08004377AudioFlinger::DirectOutputThread::~DirectOutputThread()
4378{
4379}
4380
Eric Laurentbfb1b832013-01-07 09:53:42 -08004381void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
4382{
4383 audio_track_cblk_t* cblk = track->cblk();
4384 float left, right;
4385
4386 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4387 left = right = 0;
4388 } else {
4389 float typeVolume = mStreamTypes[track->streamType()].volume;
4390 float v = mMasterVolume * typeVolume;
4391 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004392 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4393 left = float_from_gain(gain_minifloat_unpack_left(vlr));
4394 if (left > GAIN_FLOAT_UNITY) {
4395 left = GAIN_FLOAT_UNITY;
4396 }
4397 left *= v;
4398 right = float_from_gain(gain_minifloat_unpack_right(vlr));
4399 if (right > GAIN_FLOAT_UNITY) {
4400 right = GAIN_FLOAT_UNITY;
4401 }
4402 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004403 }
4404
4405 if (lastTrack) {
4406 if (left != mLeftVolFloat || right != mRightVolFloat) {
4407 mLeftVolFloat = left;
4408 mRightVolFloat = right;
4409
4410 // Convert volumes from float to 8.24
4411 uint32_t vl = (uint32_t)(left * (1 << 24));
4412 uint32_t vr = (uint32_t)(right * (1 << 24));
4413
4414 // Delegate volume control to effect in track effect chain if needed
4415 // only one effect chain can be present on DirectOutputThread, so if
4416 // there is one, the track is connected to it
4417 if (!mEffectChains.isEmpty()) {
4418 mEffectChains[0]->setVolume_l(&vl, &vr);
4419 left = (float)vl / (1 << 24);
4420 right = (float)vr / (1 << 24);
4421 }
4422 if (mOutput->stream->set_volume) {
4423 mOutput->stream->set_volume(mOutput->stream, left, right);
4424 }
4425 }
4426 }
4427}
4428
4429
Eric Laurent81784c32012-11-19 14:55:58 -08004430AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4431 Vector< sp<Track> > *tracksToRemove
4432)
4433{
Eric Laurentd595b7c2013-04-03 17:27:56 -07004434 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08004435 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004436 bool doHwPause = false;
4437 bool doHwResume = false;
4438 bool flushPending = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004439
4440 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07004441 for (size_t i = 0; i < count; i++) {
4442 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08004443 // The track died recently
4444 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004445 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08004446 }
4447
4448 Track* const track = t.get();
4449 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07004450 // Only consider last track started for volume and mixer state control.
4451 // In theory an older track could underrun and restart after the new one starts
4452 // but as we only care about the transition phase between two tracks on a
4453 // direct output, it is not a problem to ignore the underrun case.
4454 sp<Track> l = mLatestActiveTrack.promote();
4455 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08004456
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004457 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004458 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004459 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004460 doHwPause = true;
4461 mHwPaused = true;
4462 }
4463 tracksToRemove->add(track);
4464 } else if (track->isFlushPending()) {
4465 track->flushAck();
4466 if (last) {
4467 flushPending = true;
4468 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004469 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004470 track->resumeAck();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004471 if (last && mHwPaused) {
4472 doHwResume = true;
4473 mHwPaused = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004474 }
4475 }
4476
Eric Laurent81784c32012-11-19 14:55:58 -08004477 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08004478 // for all its buffers to be filled before processing it.
4479 // Allow draining the buffer in case the client
4480 // app does not call stop() and relies on underrun to stop:
4481 // hence the test on (track->mRetryCount > 1).
4482 // If retryCount<=1 then track is about to underrun and be removed.
Eric Laurent81784c32012-11-19 14:55:58 -08004483 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08004484 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
4485 && (track->mRetryCount > 1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004486 minFrames = mNormalFrameCount;
4487 } else {
4488 minFrames = 1;
4489 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004490
Eric Laurentab5cdba2014-06-09 17:22:27 -07004491 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4492 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08004493 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004494 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08004495
4496 if (track->mFillingUpStatus == Track::FS_FILLED) {
4497 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004498 // make sure processVolume_l() will apply new volume even if 0
4499 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004500 if (!mHwSupportsPause) {
4501 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08004502 }
4503 }
4504
4505 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004506 processVolume_l(track, last);
4507 if (last) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004508 // reset retry count
4509 track->mRetryCount = kMaxTrackRetriesDirect;
4510 mActiveTrack = t;
4511 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004512 if (usesHwAvSync() && mHwPaused) {
4513 doHwResume = true;
4514 mHwPaused = false;
4515 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004516 }
Eric Laurent81784c32012-11-19 14:55:58 -08004517 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004518 // clear effect chain input buffer if the last active track started underruns
4519 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07004520 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004521 mEffectChains[0]->clearInputBuffer();
4522 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004523 if (track->isStopping_1()) {
4524 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07004525 if (last && mHwPaused) {
4526 doHwResume = true;
4527 mHwPaused = false;
4528 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004529 }
4530 if ((track->sharedBuffer() != 0) || track->isStopped() ||
4531 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004532 // We have consumed all the buffers of this track.
4533 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07004534 size_t audioHALFrames;
4535 if (audio_is_linear_pcm(mFormat)) {
4536 audioHALFrames = (latency_l() * mSampleRate) / 1000;
4537 } else {
4538 audioHALFrames = 0;
4539 }
4540
Eric Laurent81784c32012-11-19 14:55:58 -08004541 size_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07004542 if (mStandby || !last ||
4543 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004544 if (track->isStopping_2()) {
4545 track->mState = TrackBase::STOPPED;
4546 }
Eric Laurent81784c32012-11-19 14:55:58 -08004547 if (track->isStopped()) {
4548 track->reset();
4549 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004550 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08004551 }
4552 } else {
4553 // No buffers for this track. Give it a few chances to
4554 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07004555 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08004556 if (--(track->mRetryCount) <= 0) {
4557 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07004558 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004559 // indicate to client process that the track was disabled because of underrun;
4560 // it will then automatically call start() when data is available
4561 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004562 } else if (last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004563 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004564 if (usesHwAvSync() && !mHwPaused && !mStandby) {
4565 doHwPause = true;
4566 mHwPaused = true;
4567 }
Eric Laurent81784c32012-11-19 14:55:58 -08004568 }
4569 }
4570 }
4571 }
4572
Eric Laurentd1f69b02014-12-15 14:33:13 -08004573 // if an active track did not command a flush, check for pending flush on stopped tracks
4574 if (!flushPending) {
4575 for (size_t i = 0; i < mTracks.size(); i++) {
4576 if (mTracks[i]->isFlushPending()) {
4577 mTracks[i]->flushAck();
4578 flushPending = true;
4579 }
4580 }
4581 }
4582
4583 // make sure the pause/flush/resume sequence is executed in the right order.
4584 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4585 // before flush and then resume HW. This can happen in case of pause/flush/resume
4586 // if resume is received before pause is executed.
4587 if (mHwSupportsPause && !mStandby &&
4588 (doHwPause || (flushPending && !mHwPaused && (count != 0)))) {
4589 mOutput->stream->pause(mOutput->stream);
4590 }
4591 if (flushPending) {
4592 flushHw_l();
4593 }
4594 if (mHwSupportsPause && !mStandby && doHwResume) {
4595 mOutput->stream->resume(mOutput->stream);
4596 }
Eric Laurent81784c32012-11-19 14:55:58 -08004597 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004598 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004599
4600 return mixerStatus;
4601}
4602
4603void AudioFlinger::DirectOutputThread::threadLoop_mix()
4604{
Eric Laurent81784c32012-11-19 14:55:58 -08004605 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08004606 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004607 // output audio to hardware
4608 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07004609 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004610 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08004611 status_t status = mActiveTrack->getNextBuffer(&buffer);
4612 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08004613 memset(curBuf, 0, frameCount * mFrameSize);
4614 break;
4615 }
4616 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
4617 frameCount -= buffer.frameCount;
4618 curBuf += buffer.frameCount * mFrameSize;
4619 mActiveTrack->releaseBuffer(&buffer);
4620 }
Andy Hung2098f272014-02-27 14:00:06 -08004621 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004622 sleepTime = 0;
4623 standbyTime = systemTime() + standbyDelay;
4624 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004625}
4626
4627void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
4628{
Eric Laurentd1f69b02014-12-15 14:33:13 -08004629 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004630 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004631 sleepTime = idleSleepTime;
4632 return;
4633 }
Eric Laurent81784c32012-11-19 14:55:58 -08004634 if (sleepTime == 0) {
4635 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4636 sleepTime = activeSleepTime;
4637 } else {
4638 sleepTime = idleSleepTime;
4639 }
4640 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08004641 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004642 sleepTime = 0;
4643 }
4644}
4645
Eric Laurentd1f69b02014-12-15 14:33:13 -08004646void AudioFlinger::DirectOutputThread::threadLoop_exit()
4647{
4648 {
4649 Mutex::Autolock _l(mLock);
4650 bool flushPending = false;
4651 for (size_t i = 0; i < mTracks.size(); i++) {
4652 if (mTracks[i]->isFlushPending()) {
4653 mTracks[i]->flushAck();
4654 flushPending = true;
4655 }
4656 }
4657 if (flushPending) {
4658 flushHw_l();
4659 }
4660 }
4661 PlaybackThread::threadLoop_exit();
4662}
4663
4664// must be called with thread mutex locked
4665bool AudioFlinger::DirectOutputThread::shouldStandby_l()
4666{
4667 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07004668 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004669
4670 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4671 // after a timeout and we will enter standby then.
4672 if (mTracks.size() > 0) {
4673 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07004674 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
4675 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004676 }
4677
Eric Laurentb369caf2015-03-30 20:51:47 -07004678 return !mStandby && !(trackPaused || (usesHwAvSync() && mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08004679}
4680
Eric Laurent81784c32012-11-19 14:55:58 -08004681// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004682int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Andy Hunge8a1ced2014-05-09 15:02:21 -07004683 audio_format_t format __unused, int sessionId __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004684{
4685 return 0;
4686}
4687
4688// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004689void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004690{
4691}
4692
Eric Laurent10351942014-05-08 18:49:52 -07004693// checkForNewParameter_l() must be called with ThreadBase::mLock held
4694bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
4695 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004696{
4697 bool reconfig = false;
4698
Eric Laurent10351942014-05-08 18:49:52 -07004699 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004700
Eric Laurent10351942014-05-08 18:49:52 -07004701 AudioParameter param = AudioParameter(keyValuePair);
4702 int value;
4703 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4704 // forward device change to effects that have requested to be
4705 // aware of attached audio device.
4706 if (value != AUDIO_DEVICE_NONE) {
4707 mOutDevice = value;
4708 for (size_t i = 0; i < mEffectChains.size(); i++) {
4709 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07004710 }
4711 }
Eric Laurent81784c32012-11-19 14:55:58 -08004712 }
Eric Laurent10351942014-05-08 18:49:52 -07004713 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4714 // do not accept frame count changes if tracks are open as the track buffer
4715 // size depends on frame count and correct behavior would not be garantied
4716 // if frame count is changed after track creation
4717 if (!mTracks.isEmpty()) {
4718 status = INVALID_OPERATION;
4719 } else {
4720 reconfig = true;
4721 }
4722 }
4723 if (status == NO_ERROR) {
4724 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4725 keyValuePair.string());
4726 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004727 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004728 mStandby = true;
4729 mBytesWritten = 0;
4730 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4731 keyValuePair.string());
4732 }
4733 if (status == NO_ERROR && reconfig) {
4734 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07004735 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004736 }
4737 }
4738
Eric Laurent81784c32012-11-19 14:55:58 -08004739 return reconfig;
4740}
4741
4742uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
4743{
4744 uint32_t time;
4745 if (audio_is_linear_pcm(mFormat)) {
4746 time = PlaybackThread::activeSleepTimeUs();
4747 } else {
4748 time = 10000;
4749 }
4750 return time;
4751}
4752
4753uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
4754{
4755 uint32_t time;
4756 if (audio_is_linear_pcm(mFormat)) {
4757 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
4758 } else {
4759 time = 10000;
4760 }
4761 return time;
4762}
4763
4764uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
4765{
4766 uint32_t time;
4767 if (audio_is_linear_pcm(mFormat)) {
4768 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
4769 } else {
4770 time = 10000;
4771 }
4772 return time;
4773}
4774
4775void AudioFlinger::DirectOutputThread::cacheParameters_l()
4776{
4777 PlaybackThread::cacheParameters_l();
4778
4779 // use shorter standby delay as on normal output to release
4780 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07004781 // no delay on outputs with HW A/V sync
4782 if (usesHwAvSync()) {
4783 standbyDelay = 0;
4784 } else if (audio_is_linear_pcm(mFormat)) {
Eric Laurent972a1732013-09-04 09:42:59 -07004785 standbyDelay = microseconds(activeSleepTime*2);
4786 } else {
4787 standbyDelay = kOffloadStandbyDelayNs;
4788 }
Eric Laurent81784c32012-11-19 14:55:58 -08004789}
4790
Eric Laurente659ef42014-09-29 13:06:46 -07004791void AudioFlinger::DirectOutputThread::flushHw_l()
4792{
Phil Burk062e67a2015-02-11 13:40:50 -08004793 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08004794 mHwPaused = false;
Eric Laurente659ef42014-09-29 13:06:46 -07004795}
4796
Eric Laurent81784c32012-11-19 14:55:58 -08004797// ----------------------------------------------------------------------------
4798
Eric Laurentbfb1b832013-01-07 09:53:42 -08004799AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07004800 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004801 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07004802 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07004803 mWriteAckSequence(0),
4804 mDrainSequence(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004805{
4806}
4807
4808AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
4809{
4810}
4811
4812void AudioFlinger::AsyncCallbackThread::onFirstRef()
4813{
4814 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
4815}
4816
4817bool AudioFlinger::AsyncCallbackThread::threadLoop()
4818{
4819 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004820 uint32_t writeAckSequence;
4821 uint32_t drainSequence;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004822
4823 {
4824 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08004825 while (!((mWriteAckSequence & 1) ||
4826 (mDrainSequence & 1) ||
4827 exitPending())) {
4828 mWaitWorkCV.wait(mLock);
4829 }
4830
Eric Laurentbfb1b832013-01-07 09:53:42 -08004831 if (exitPending()) {
4832 break;
4833 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004834 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
4835 mWriteAckSequence, mDrainSequence);
4836 writeAckSequence = mWriteAckSequence;
4837 mWriteAckSequence &= ~1;
4838 drainSequence = mDrainSequence;
4839 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004840 }
4841 {
Eric Laurent4de95592013-09-26 15:28:21 -07004842 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
4843 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004844 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004845 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004846 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004847 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004848 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004849 }
4850 }
4851 }
4852 }
4853 return false;
4854}
4855
4856void AudioFlinger::AsyncCallbackThread::exit()
4857{
4858 ALOGV("AsyncCallbackThread::exit");
4859 Mutex::Autolock _l(mLock);
4860 requestExit();
4861 mWaitWorkCV.broadcast();
4862}
4863
Eric Laurent3b4529e2013-09-05 18:09:19 -07004864void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004865{
4866 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004867 // bit 0 is cleared
4868 mWriteAckSequence = sequence << 1;
4869}
4870
4871void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
4872{
4873 Mutex::Autolock _l(mLock);
4874 // ignore unexpected callbacks
4875 if (mWriteAckSequence & 2) {
4876 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004877 mWaitWorkCV.signal();
4878 }
4879}
4880
Eric Laurent3b4529e2013-09-05 18:09:19 -07004881void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004882{
4883 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004884 // bit 0 is cleared
4885 mDrainSequence = sequence << 1;
4886}
4887
4888void AudioFlinger::AsyncCallbackThread::resetDraining()
4889{
4890 Mutex::Autolock _l(mLock);
4891 // ignore unexpected callbacks
4892 if (mDrainSequence & 2) {
4893 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004894 mWaitWorkCV.signal();
4895 }
4896}
4897
4898
4899// ----------------------------------------------------------------------------
4900AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07004901 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady)
4902 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady),
Eric Laurentd7e59222013-11-15 12:02:28 -08004903 mPausedBytesRemaining(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004904{
Eric Laurentfd477972013-10-25 18:10:40 -07004905 //FIXME: mStandby should be set to true by ThreadBase constructor
4906 mStandby = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004907}
4908
Eric Laurentbfb1b832013-01-07 09:53:42 -08004909void AudioFlinger::OffloadThread::threadLoop_exit()
4910{
4911 if (mFlushPending || mHwPaused) {
4912 // If a flush is pending or track was paused, just discard buffered data
4913 flushHw_l();
4914 } else {
4915 mMixerStatus = MIXER_DRAIN_ALL;
4916 threadLoop_drain();
4917 }
Uday Gupta56604aa2014-05-13 11:19:17 -07004918 if (mUseAsyncWrite) {
4919 ALOG_ASSERT(mCallbackThread != 0);
4920 mCallbackThread->exit();
4921 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004922 PlaybackThread::threadLoop_exit();
4923}
4924
4925AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
4926 Vector< sp<Track> > *tracksToRemove
4927)
4928{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004929 size_t count = mActiveTracks.size();
4930
4931 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07004932 bool doHwPause = false;
4933 bool doHwResume = false;
4934
Eric Laurentede6c3b2013-09-19 14:37:46 -07004935 ALOGV("OffloadThread::prepareTracks_l active tracks %d", count);
4936
Eric Laurentbfb1b832013-01-07 09:53:42 -08004937 // find out which tracks need to be processed
4938 for (size_t i = 0; i < count; i++) {
4939 sp<Track> t = mActiveTracks[i].promote();
4940 // The track died recently
4941 if (t == 0) {
4942 continue;
4943 }
4944 Track* const track = t.get();
4945 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07004946 // Only consider last track started for volume and mixer state control.
4947 // In theory an older track could underrun and restart after the new one starts
4948 // but as we only care about the transition phase between two tracks on a
4949 // direct output, it is not a problem to ignore the underrun case.
4950 sp<Track> l = mLatestActiveTrack.promote();
4951 bool last = l.get() == track;
4952
Haynes Mathew George7844f672014-01-15 12:32:55 -08004953 if (track->isInvalid()) {
4954 ALOGW("An invalidated track shouldn't be in active list");
4955 tracksToRemove->add(track);
4956 continue;
4957 }
4958
4959 if (track->mState == TrackBase::IDLE) {
4960 ALOGW("An idle track shouldn't be in active list");
4961 continue;
4962 }
4963
Eric Laurentbfb1b832013-01-07 09:53:42 -08004964 if (track->isPausing()) {
4965 track->setPaused();
4966 if (last) {
4967 if (!mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07004968 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004969 mHwPaused = true;
4970 }
4971 // If we were part way through writing the mixbuffer to
4972 // the HAL we must save this until we resume
4973 // BUG - this will be wrong if a different track is made active,
4974 // in that case we want to discard the pending data in the
4975 // mixbuffer and tell the client to present it again when the
4976 // track is resumed
4977 mPausedWriteLength = mCurrentWriteLength;
4978 mPausedBytesRemaining = mBytesRemaining;
4979 mBytesRemaining = 0; // stop writing
4980 }
4981 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08004982 } else if (track->isFlushPending()) {
4983 track->flushAck();
4984 if (last) {
4985 mFlushPending = true;
4986 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08004987 } else if (track->isResumePending()){
4988 track->resumeAck();
4989 if (last) {
4990 if (mPausedBytesRemaining) {
4991 // Need to continue write that was interrupted
4992 mCurrentWriteLength = mPausedWriteLength;
4993 mBytesRemaining = mPausedBytesRemaining;
4994 mPausedBytesRemaining = 0;
4995 }
4996 if (mHwPaused) {
4997 doHwResume = true;
4998 mHwPaused = false;
4999 // threadLoop_mix() will handle the case that we need to
5000 // resume an interrupted write
5001 }
5002 // enable write to audio HAL
5003 sleepTime = 0;
5004
5005 // Do not handle new data in this iteration even if track->framesReady()
5006 mixerStatus = MIXER_TRACKS_ENABLED;
5007 }
5008 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07005009 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005010 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005011 if (track->mFillingUpStatus == Track::FS_FILLED) {
5012 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07005013 // make sure processVolume_l() will apply new volume even if 0
5014 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005015 }
5016
5017 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08005018 sp<Track> previousTrack = mPreviousTrack.promote();
5019 if (previousTrack != 0) {
5020 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08005021 // Flush any data still being written from last track
5022 mBytesRemaining = 0;
5023 if (mPausedBytesRemaining) {
5024 // Last track was paused so we also need to flush saved
5025 // mixbuffer state and invalidate track so that it will
5026 // re-submit that unwritten data when it is next resumed
5027 mPausedBytesRemaining = 0;
5028 // Invalidate is a bit drastic - would be more efficient
5029 // to have a flag to tell client that some of the
5030 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08005031 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005032 }
5033 // flush data already sent to the DSP if changing audio session as audio
5034 // comes from a different source. Also invalidate previous track to force a
5035 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08005036 if (previousTrack->sessionId() != track->sessionId()) {
5037 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005038 }
5039 }
5040 }
5041 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005042 // reset retry count
5043 track->mRetryCount = kMaxTrackRetriesOffload;
5044 mActiveTrack = t;
5045 mixerStatus = MIXER_TRACKS_READY;
5046 }
5047 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005048 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005049 if (track->isStopping_1()) {
5050 // Hardware buffer can hold a large amount of audio so we must
5051 // wait for all current track's data to drain before we say
5052 // that the track is stopped.
5053 if (mBytesRemaining == 0) {
5054 // Only start draining when all data in mixbuffer
5055 // has been written
5056 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
5057 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005058 // do not drain if no data was ever sent to HAL (mStandby == true)
5059 if (last && !mStandby) {
Eric Laurent1b9f9b12013-11-12 19:10:17 -08005060 // do not modify drain sequence if we are already draining. This happens
5061 // when resuming from pause after drain.
5062 if ((mDrainSequence & 1) == 0) {
5063 sleepTime = 0;
5064 standbyTime = systemTime() + standbyDelay;
5065 mixerStatus = MIXER_DRAIN_TRACK;
5066 mDrainSequence += 2;
5067 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005068 if (mHwPaused) {
5069 // It is possible to move from PAUSED to STOPPING_1 without
5070 // a resume so we must ensure hardware is running
Eric Laurent1b9f9b12013-11-12 19:10:17 -08005071 doHwResume = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005072 mHwPaused = false;
5073 }
5074 }
5075 }
5076 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005077 // Drain has completed or we are in standby, signal presentation complete
5078 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005079 track->mState = TrackBase::STOPPED;
5080 size_t audioHALFrames =
5081 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
5082 size_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08005083 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005084 track->presentationComplete(framesWritten, audioHALFrames);
5085 track->reset();
5086 tracksToRemove->add(track);
5087 }
5088 } else {
5089 // No buffers for this track. Give it a few chances to
5090 // fill a buffer, then remove it from active list.
5091 if (--(track->mRetryCount) <= 0) {
5092 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
5093 track->name());
5094 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08005095 // indicate to client process that the track was disabled because of underrun;
5096 // it will then automatically call start() when data is available
5097 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005098 } else if (last){
5099 mixerStatus = MIXER_TRACKS_ENABLED;
5100 }
5101 }
5102 }
5103 // compute volume for this track
5104 processVolume_l(track, last);
5105 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005106
Eric Laurentea0fade2013-10-04 16:23:48 -07005107 // make sure the pause/flush/resume sequence is executed in the right order.
5108 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5109 // before flush and then resume HW. This can happen in case of pause/flush/resume
5110 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07005111 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurent972a1732013-09-04 09:42:59 -07005112 mOutput->stream->pause(mOutput->stream);
5113 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005114 if (mFlushPending) {
5115 flushHw_l();
5116 mFlushPending = false;
5117 }
Eric Laurentfd477972013-10-25 18:10:40 -07005118 if (!mStandby && doHwResume) {
Eric Laurent972a1732013-09-04 09:42:59 -07005119 mOutput->stream->resume(mOutput->stream);
5120 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005121
Eric Laurentbfb1b832013-01-07 09:53:42 -08005122 // remove all the tracks that need to be...
5123 removeTracks_l(*tracksToRemove);
5124
5125 return mixerStatus;
5126}
5127
Eric Laurentbfb1b832013-01-07 09:53:42 -08005128// must be called with thread mutex locked
5129bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
5130{
Eric Laurent3b4529e2013-09-05 18:09:19 -07005131 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
5132 mWriteAckSequence, mDrainSequence);
5133 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005134 return true;
5135 }
5136 return false;
5137}
5138
Eric Laurentbfb1b832013-01-07 09:53:42 -08005139bool AudioFlinger::OffloadThread::waitingAsyncCallback()
5140{
5141 Mutex::Autolock _l(mLock);
5142 return waitingAsyncCallback_l();
5143}
5144
5145void AudioFlinger::OffloadThread::flushHw_l()
5146{
Eric Laurente659ef42014-09-29 13:06:46 -07005147 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005148 // Flush anything still waiting in the mixbuffer
5149 mCurrentWriteLength = 0;
5150 mBytesRemaining = 0;
5151 mPausedWriteLength = 0;
5152 mPausedBytesRemaining = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08005153
Eric Laurentbfb1b832013-01-07 09:53:42 -08005154 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005155 // discard any pending drain or write ack by incrementing sequence
5156 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5157 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005158 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005159 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5160 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005161 }
5162}
5163
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08005164void AudioFlinger::OffloadThread::onAddNewTrack_l()
5165{
5166 sp<Track> previousTrack = mPreviousTrack.promote();
5167 sp<Track> latestTrack = mLatestActiveTrack.promote();
5168
5169 if (previousTrack != 0 && latestTrack != 0 &&
5170 (previousTrack->sessionId() != latestTrack->sessionId())) {
5171 mFlushPending = true;
5172 }
5173 PlaybackThread::onAddNewTrack_l();
5174}
5175
Eric Laurentbfb1b832013-01-07 09:53:42 -08005176// ----------------------------------------------------------------------------
5177
Eric Laurent81784c32012-11-19 14:55:58 -08005178AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07005179 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08005180 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
Eric Laurent72e3f392015-05-20 14:43:50 -07005181 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08005182 mWaitTimeMs(UINT_MAX)
5183{
5184 addOutputTrack(mainThread);
5185}
5186
5187AudioFlinger::DuplicatingThread::~DuplicatingThread()
5188{
5189 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5190 mOutputTracks[i]->destroy();
5191 }
5192}
5193
5194void AudioFlinger::DuplicatingThread::threadLoop_mix()
5195{
5196 // mix buffers...
5197 if (outputsReady(outputTracks)) {
5198 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
5199 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08005200 if (mMixerBufferValid) {
5201 memset(mMixerBuffer, 0, mMixerBufferSize);
5202 } else {
5203 memset(mSinkBuffer, 0, mSinkBufferSize);
5204 }
Eric Laurent81784c32012-11-19 14:55:58 -08005205 }
5206 sleepTime = 0;
5207 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005208 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005209 standbyTime = systemTime() + standbyDelay;
5210}
5211
5212void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
5213{
5214 if (sleepTime == 0) {
5215 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5216 sleepTime = activeSleepTime;
5217 } else {
5218 sleepTime = idleSleepTime;
5219 }
5220 } else if (mBytesWritten != 0) {
5221 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5222 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005223 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005224 } else {
5225 // flush remaining overflow buffers in output tracks
5226 writeFrames = 0;
5227 }
5228 sleepTime = 0;
5229 }
5230}
5231
Eric Laurentbfb1b832013-01-07 09:53:42 -08005232ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005233{
5234 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08005235 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005236 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07005237 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08005238 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005239}
5240
5241void AudioFlinger::DuplicatingThread::threadLoop_standby()
5242{
5243 // DuplicatingThread implements standby by stopping all tracks
5244 for (size_t i = 0; i < outputTracks.size(); i++) {
5245 outputTracks[i]->stop();
5246 }
5247}
5248
5249void AudioFlinger::DuplicatingThread::saveOutputTracks()
5250{
5251 outputTracks = mOutputTracks;
5252}
5253
5254void AudioFlinger::DuplicatingThread::clearOutputTracks()
5255{
5256 outputTracks.clear();
5257}
5258
5259void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
5260{
5261 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08005262 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
5263 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
5264 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
5265 const size_t frameCount =
5266 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
5267 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
5268 // from different OutputTracks and their associated MixerThreads (e.g. one may
5269 // nearly empty and the other may be dropping data).
5270
5271 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08005272 this,
5273 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08005274 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08005275 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005276 frameCount,
5277 IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08005278 if (outputTrack->cblk() != NULL) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005279 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
Eric Laurent81784c32012-11-19 14:55:58 -08005280 mOutputTracks.add(outputTrack);
Andy Hungc25b84a2015-01-14 19:04:10 -08005281 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005282 updateWaitTime_l();
5283 }
5284}
5285
5286void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
5287{
5288 Mutex::Autolock _l(mLock);
5289 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5290 if (mOutputTracks[i]->thread() == thread) {
5291 mOutputTracks[i]->destroy();
5292 mOutputTracks.removeAt(i);
5293 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07005294 if (thread->getOutput() == mOutput) {
5295 mOutput = NULL;
5296 }
Eric Laurent81784c32012-11-19 14:55:58 -08005297 return;
5298 }
5299 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07005300 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005301}
5302
5303// caller must hold mLock
5304void AudioFlinger::DuplicatingThread::updateWaitTime_l()
5305{
5306 mWaitTimeMs = UINT_MAX;
5307 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5308 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
5309 if (strong != 0) {
5310 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
5311 if (waitTimeMs < mWaitTimeMs) {
5312 mWaitTimeMs = waitTimeMs;
5313 }
5314 }
5315 }
5316}
5317
5318
5319bool AudioFlinger::DuplicatingThread::outputsReady(
5320 const SortedVector< sp<OutputTrack> > &outputTracks)
5321{
5322 for (size_t i = 0; i < outputTracks.size(); i++) {
5323 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
5324 if (thread == 0) {
5325 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
5326 outputTracks[i].get());
5327 return false;
5328 }
5329 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5330 // see note at standby() declaration
5331 if (playbackThread->standby() && !playbackThread->isSuspended()) {
5332 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
5333 thread.get());
5334 return false;
5335 }
5336 }
5337 return true;
5338}
5339
5340uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
5341{
5342 return (mWaitTimeMs * 1000) / 2;
5343}
5344
5345void AudioFlinger::DuplicatingThread::cacheParameters_l()
5346{
5347 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
5348 updateWaitTime_l();
5349
5350 MixerThread::cacheParameters_l();
5351}
5352
5353// ----------------------------------------------------------------------------
5354// Record
5355// ----------------------------------------------------------------------------
5356
5357AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5358 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08005359 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08005360 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07005361 audio_devices_t inDevice,
5362 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08005363#ifdef TEE_SINK
5364 , const sp<NBAIO_Sink>& teeSink
5365#endif
5366 ) :
Eric Laurent72e3f392015-05-20 14:43:50 -07005367 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005368 mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005369 // mRsmpInFrames and mRsmpInFramesP2 are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005370 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08005371#ifdef TEE_SINK
5372 , mTeeSink(teeSink)
5373#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07005374 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
5375 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005376 // mFastCapture below
5377 , mFastCaptureFutex(0)
5378 // mInputSource
5379 // mPipeSink
5380 // mPipeSource
5381 , mPipeFramesP2(0)
5382 // mPipeMemory
5383 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005384 , mFastTrackAvail(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005385{
Glenn Kastend7dca052015-03-05 16:05:54 -08005386 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
5387 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08005388
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005389 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005390
5391 // create an NBAIO source for the HAL input stream, and negotiate
5392 mInputSource = new AudioStreamInSource(input->stream);
5393 size_t numCounterOffers = 0;
5394 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
5395 ssize_t index = mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
5396 ALOG_ASSERT(index == 0);
5397
5398 // initialize fast capture depending on configuration
5399 bool initFastCapture;
5400 switch (kUseFastCapture) {
5401 case FastCapture_Never:
5402 initFastCapture = false;
5403 break;
5404 case FastCapture_Always:
5405 initFastCapture = true;
5406 break;
5407 case FastCapture_Static:
5408 uint32_t primaryOutputSampleRate;
5409 {
5410 AutoMutex _l(audioFlinger->mHardwareLock);
5411 primaryOutputSampleRate = audioFlinger->mPrimaryOutputSampleRate;
5412 }
5413 initFastCapture =
5414 // either capture sample rate is same as (a reasonable) primary output sample rate
Andy Hungdb4c0312015-05-06 08:46:52 -07005415 ((isMusicRate(primaryOutputSampleRate) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005416 (mSampleRate == primaryOutputSampleRate)) ||
5417 // or primary output sample rate is unknown, and capture sample rate is reasonable
5418 ((primaryOutputSampleRate == 0) &&
Andy Hungdb4c0312015-05-06 08:46:52 -07005419 isMusicRate(mSampleRate))) &&
Glenn Kasten9f81de32014-07-27 15:02:23 -07005420 // and the buffer size is < 12 ms
5421 (mFrameCount * 1000) / mSampleRate < 12;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005422 break;
5423 // case FastCapture_Dynamic:
5424 }
5425
5426 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07005427 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005428 NBAIO_Format format = mInputSource->format();
Glenn Kasten49d00ad2014-07-21 11:22:03 -07005429 size_t pipeFramesP2 = roundup(mSampleRate / 25); // double-buffering of 20 ms each
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005430 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
5431 void *pipeBuffer;
5432 const sp<MemoryDealer> roHeap(readOnlyHeap());
5433 sp<IMemory> pipeMemory;
5434 if ((roHeap == 0) ||
5435 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
5436 (pipeBuffer = pipeMemory->pointer()) == NULL) {
5437 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
5438 goto failed;
5439 }
5440 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
5441 memset(pipeBuffer, 0, pipeSize);
5442 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
5443 const NBAIO_Format offers[1] = {format};
5444 size_t numCounterOffers = 0;
5445 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
5446 ALOG_ASSERT(index == 0);
5447 mPipeSink = pipe;
5448 PipeReader *pipeReader = new PipeReader(*pipe);
5449 numCounterOffers = 0;
5450 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
5451 ALOG_ASSERT(index == 0);
5452 mPipeSource = pipeReader;
5453 mPipeFramesP2 = pipeFramesP2;
5454 mPipeMemory = pipeMemory;
5455
5456 // create fast capture
5457 mFastCapture = new FastCapture();
5458 FastCaptureStateQueue *sq = mFastCapture->sq();
5459#ifdef STATE_QUEUE_DUMP
5460 // FIXME
5461#endif
5462 FastCaptureState *state = sq->begin();
5463 state->mCblk = NULL;
5464 state->mInputSource = mInputSource.get();
5465 state->mInputSourceGen++;
5466 state->mPipeSink = pipe;
5467 state->mPipeSinkGen++;
5468 state->mFrameCount = mFrameCount;
5469 state->mCommand = FastCaptureState::COLD_IDLE;
5470 // already done in constructor initialization list
5471 //mFastCaptureFutex = 0;
5472 state->mColdFutexAddr = &mFastCaptureFutex;
5473 state->mColdGen++;
5474 state->mDumpState = &mFastCaptureDumpState;
5475#ifdef TEE_SINK
5476 // FIXME
5477#endif
5478 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
5479 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
5480 sq->end();
5481 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5482
5483 // start the fast capture
5484 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
5485 pid_t tid = mFastCapture->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07005486 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005487#ifdef AUDIO_WATCHDOG
5488 // FIXME
5489#endif
5490
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005491 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005492 }
5493failed: ;
5494
5495 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08005496}
5497
Eric Laurent81784c32012-11-19 14:55:58 -08005498AudioFlinger::RecordThread::~RecordThread()
5499{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005500 if (mFastCapture != 0) {
5501 FastCaptureStateQueue *sq = mFastCapture->sq();
5502 FastCaptureState *state = sq->begin();
5503 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5504 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5505 if (old == -1) {
5506 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5507 }
5508 }
5509 state->mCommand = FastCaptureState::EXIT;
5510 sq->end();
5511 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5512 mFastCapture->join();
5513 mFastCapture.clear();
5514 }
5515 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07005516 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07005517 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08005518}
5519
5520void AudioFlinger::RecordThread::onFirstRef()
5521{
Glenn Kastend7dca052015-03-05 16:05:54 -08005522 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08005523}
5524
Eric Laurent81784c32012-11-19 14:55:58 -08005525bool AudioFlinger::RecordThread::threadLoop()
5526{
Eric Laurent81784c32012-11-19 14:55:58 -08005527 nsecs_t lastWarning = 0;
5528
5529 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08005530
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005531reacquire_wakelock:
5532 sp<RecordTrack> activeTrack;
Glenn Kasten2b806402013-11-20 16:37:38 -08005533 int activeTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005534 {
5535 Mutex::Autolock _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005536 size_t size = mActiveTracks.size();
5537 activeTracksGen = mActiveTracksGen;
5538 if (size > 0) {
5539 // FIXME an arbitrary choice
5540 activeTrack = mActiveTracks[0];
5541 acquireWakeLock_l(activeTrack->uid());
5542 if (size > 1) {
5543 SortedVector<int> tmp;
5544 for (size_t i = 0; i < size; i++) {
5545 tmp.add(mActiveTracks[i]->uid());
5546 }
5547 updateWakeLockUids_l(tmp);
5548 }
5549 } else {
5550 acquireWakeLock_l(-1);
5551 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005552 }
5553
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005554 // used to request a deferred sleep, to be executed later while mutex is unlocked
5555 uint32_t sleepUs = 0;
5556
5557 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005558 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005559 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07005560
Glenn Kasten5edadd42013-08-14 16:30:49 -07005561 // sleep with mutex unlocked
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005562 if (sleepUs > 0) {
Glenn Kastene7754022014-10-31 12:11:26 -07005563 ATRACE_BEGIN("sleep");
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005564 usleep(sleepUs);
Glenn Kastene7754022014-10-31 12:11:26 -07005565 ATRACE_END();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005566 sleepUs = 0;
Glenn Kasten5edadd42013-08-14 16:30:49 -07005567 }
5568
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005569 // activeTracks accumulates a copy of a subset of mActiveTracks
5570 Vector< sp<RecordTrack> > activeTracks;
5571
Glenn Kasten735f45f2014-08-18 15:51:59 -07005572 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005573 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07005574
Glenn Kasten735f45f2014-08-18 15:51:59 -07005575 // reference to a fast track which is about to be removed
5576 sp<RecordTrack> fastTrackToRemove;
5577
Eric Laurent81784c32012-11-19 14:55:58 -08005578 { // scope for mLock
5579 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08005580
Eric Laurent021cf962014-05-13 10:18:14 -07005581 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005582
Eric Laurent000a4192014-01-29 15:17:32 -08005583 // check exitPending here because checkForNewParameters_l() and
5584 // checkForNewParameters_l() can temporarily release mLock
5585 if (exitPending()) {
5586 break;
5587 }
5588
Glenn Kasten2b806402013-11-20 16:37:38 -08005589 // if no active track(s), then standby and release wakelock
5590 size_t size = mActiveTracks.size();
5591 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07005592 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005593 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08005594 releaseWakeLock_l();
5595 ALOGV("RecordThread: loop stopping");
5596 // go to sleep
5597 mWaitWorkCV.wait(mLock);
5598 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005599 goto reacquire_wakelock;
5600 }
5601
Glenn Kasten2b806402013-11-20 16:37:38 -08005602 if (mActiveTracksGen != activeTracksGen) {
5603 activeTracksGen = mActiveTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005604 SortedVector<int> tmp;
Glenn Kasten2b806402013-11-20 16:37:38 -08005605 for (size_t i = 0; i < size; i++) {
5606 tmp.add(mActiveTracks[i]->uid());
5607 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005608 updateWakeLockUids_l(tmp);
Eric Laurent81784c32012-11-19 14:55:58 -08005609 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005610
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005611 bool doBroadcast = false;
5612 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07005613
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005614 activeTrack = mActiveTracks[i];
5615 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07005616 if (activeTrack->isFastTrack()) {
5617 ALOG_ASSERT(fastTrackToRemove == 0);
5618 fastTrackToRemove = activeTrack;
5619 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005620 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08005621 mActiveTracks.remove(activeTrack);
5622 mActiveTracksGen++;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005623 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07005624 continue;
5625 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005626
5627 TrackBase::track_state activeTrackState = activeTrack->mState;
5628 switch (activeTrackState) {
5629
5630 case TrackBase::PAUSING:
5631 mActiveTracks.remove(activeTrack);
5632 mActiveTracksGen++;
5633 doBroadcast = true;
5634 size--;
5635 continue;
5636
5637 case TrackBase::STARTING_1:
5638 sleepUs = 10000;
5639 i++;
5640 continue;
5641
5642 case TrackBase::STARTING_2:
5643 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005644 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07005645 activeTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005646 break;
5647
5648 case TrackBase::ACTIVE:
5649 break;
5650
5651 case TrackBase::IDLE:
5652 i++;
5653 continue;
5654
5655 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08005656 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07005657 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005658
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005659 activeTracks.add(activeTrack);
5660 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07005661
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005662 if (activeTrack->isFastTrack()) {
5663 ALOG_ASSERT(!mFastTrackAvail);
5664 ALOG_ASSERT(fastTrack == 0);
5665 fastTrack = activeTrack;
5666 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005667 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005668 if (doBroadcast) {
5669 mStartStopCond.broadcast();
5670 }
5671
5672 // sleep if there are no active tracks to process
5673 if (activeTracks.size() == 0) {
5674 if (sleepUs == 0) {
5675 sleepUs = kRecordThreadSleepUs;
5676 }
5677 continue;
5678 }
5679 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07005680
Eric Laurent81784c32012-11-19 14:55:58 -08005681 lockEffectChains_l(effectChains);
5682 }
5683
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005684 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07005685
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005686 size_t size = effectChains.size();
5687 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005688 // thread mutex is not locked, but effect chain is locked
5689 effectChains[i]->process_l();
5690 }
5691
Glenn Kasten735f45f2014-08-18 15:51:59 -07005692 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005693 if (mFastCapture != 0) {
5694 FastCaptureStateQueue *sq = mFastCapture->sq();
5695 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07005696 bool didModify = false;
5697 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005698 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
5699 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
5700 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5701 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5702 if (old == -1) {
5703 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5704 }
5705 }
5706 state->mCommand = FastCaptureState::READ_WRITE;
5707#if 0 // FIXME
5708 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08005709 FastThreadDumpState::kSamplingNforLowRamDevice :
5710 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005711#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07005712 didModify = true;
5713 }
5714 audio_track_cblk_t *cblkOld = state->mCblk;
5715 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
5716 if (cblkNew != cblkOld) {
5717 state->mCblk = cblkNew;
5718 // block until acked if removing a fast track
5719 if (cblkOld != NULL) {
5720 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
5721 }
5722 didModify = true;
5723 }
5724 sq->end(didModify);
5725 if (didModify) {
5726 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005727#if 0
5728 if (kUseFastCapture == FastCapture_Dynamic) {
5729 mNormalSource = mPipeSource;
5730 }
5731#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005732 }
5733 }
5734
Glenn Kasten735f45f2014-08-18 15:51:59 -07005735 // now run the fast track destructor with thread mutex unlocked
5736 fastTrackToRemove.clear();
5737
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005738 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
5739 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
5740 // slow, then this RecordThread will overrun by not calling HAL read often enough.
5741 // If destination is non-contiguous, first read past the nominal end of buffer, then
5742 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005743
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005744 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005745 ssize_t framesRead;
5746
5747 // If an NBAIO source is present, use it to read the normal capture's data
5748 if (mPipeSource != 0) {
5749 size_t framesToRead = mBufferSize / mFrameSize;
Andy Hung57446612015-04-19 23:56:46 -07005750 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005751 framesToRead, AudioBufferProvider::kInvalidPTS);
5752 if (framesRead == 0) {
5753 // since pipe is non-blocking, simulate blocking input
5754 sleepUs = (framesToRead * 1000000LL) / mSampleRate;
5755 }
5756 // otherwise use the HAL / AudioStreamIn directly
5757 } else {
5758 ssize_t bytesRead = mInput->stream->read(mInput->stream,
Andy Hung57446612015-04-19 23:56:46 -07005759 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005760 if (bytesRead < 0) {
5761 framesRead = bytesRead;
5762 } else {
5763 framesRead = bytesRead / mFrameSize;
5764 }
5765 }
5766
5767 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
5768 ALOGE("read failed: framesRead=%d", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005769 // Force input into standby so that it tries to recover at next read attempt
5770 inputStandBy();
5771 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005772 }
5773 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005774 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005775 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005776 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005777
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005778 if (mTeeSink != 0) {
Andy Hung57446612015-04-19 23:56:46 -07005779 (void) mTeeSink->write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005780 }
5781 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005782 {
5783 size_t part1 = mRsmpInFramesP2 - rear;
5784 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07005785 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005786 (framesRead - part1) * mFrameSize);
5787 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005788 }
5789 rear = mRsmpInRear += framesRead;
5790
5791 size = activeTracks.size();
5792 // loop over each active track
5793 for (size_t i = 0; i < size; i++) {
5794 activeTrack = activeTracks[i];
5795
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005796 // skip fast tracks, as those are handled directly by FastCapture
5797 if (activeTrack->isFastTrack()) {
5798 continue;
5799 }
5800
Andy Hung73c02e42015-03-29 01:13:58 -07005801 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07005802 // TODO: Update the activeTrack buffer converter in case of reconfigure.
5803
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005804 enum {
5805 OVERRUN_UNKNOWN,
5806 OVERRUN_TRUE,
5807 OVERRUN_FALSE
5808 } overrun = OVERRUN_UNKNOWN;
5809
5810 // loop over getNextBuffer to handle circular sink
5811 for (;;) {
5812
5813 activeTrack->mSink.frameCount = ~0;
5814 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
5815 size_t framesOut = activeTrack->mSink.frameCount;
5816 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
5817
Andy Hung73c02e42015-03-29 01:13:58 -07005818 // check available frames and handle overrun conditions
5819 // if the record track isn't draining fast enough.
5820 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005821 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07005822 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
5823 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005824 overrun = OVERRUN_TRUE;
5825 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005826 if (framesOut == 0 || framesIn == 0) {
5827 break;
5828 }
5829
Andy Hung6770c6f2015-04-07 13:43:36 -07005830 // Don't allow framesOut to be larger than what is possible with resampling
5831 // from framesIn.
5832 // This isn't strictly necessary but helps limit buffer resizing in
5833 // RecordBufferConverter. TODO: remove when no longer needed.
5834 framesOut = min(framesOut,
5835 destinationFramesPossible(
5836 framesIn, mSampleRate, activeTrack->mSampleRate));
Andy Hung97a893e2015-03-29 01:03:07 -07005837 // process frames from the RecordThread buffer provider to the RecordTrack buffer
5838 framesOut = activeTrack->mRecordBufferConverter->convert(
5839 activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005840
5841 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
5842 overrun = OVERRUN_FALSE;
5843 }
5844
5845 if (activeTrack->mFramesToDrop == 0) {
5846 if (framesOut > 0) {
5847 activeTrack->mSink.frameCount = framesOut;
5848 activeTrack->releaseBuffer(&activeTrack->mSink);
5849 }
5850 } else {
5851 // FIXME could do a partial drop of framesOut
5852 if (activeTrack->mFramesToDrop > 0) {
5853 activeTrack->mFramesToDrop -= framesOut;
5854 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005855 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005856 }
5857 } else {
5858 activeTrack->mFramesToDrop += framesOut;
5859 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
5860 activeTrack->mSyncStartEvent->isCancelled()) {
5861 ALOGW("Synced record %s, session %d, trigger session %d",
5862 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
5863 activeTrack->sessionId(),
5864 (activeTrack->mSyncStartEvent != 0) ?
5865 activeTrack->mSyncStartEvent->triggerSession() : 0);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005866 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005867 }
5868 }
5869 }
5870
5871 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005872 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005873 }
5874 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005875
5876 switch (overrun) {
5877 case OVERRUN_TRUE:
5878 // client isn't retrieving buffers fast enough
5879 if (!activeTrack->setOverflow()) {
5880 nsecs_t now = systemTime();
5881 // FIXME should lastWarning per track?
5882 if ((now - lastWarning) > kWarningThrottleNs) {
5883 ALOGW("RecordThread: buffer overflow");
5884 lastWarning = now;
5885 }
5886 }
5887 break;
5888 case OVERRUN_FALSE:
5889 activeTrack->clearOverflow();
5890 break;
5891 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005892 break;
5893 }
5894
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005895 }
5896
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005897unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08005898 // enable changes in effect chain
5899 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005900 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08005901 }
5902
Glenn Kasten93e471f2013-08-19 08:40:07 -07005903 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08005904
5905 {
5906 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07005907 for (size_t i = 0; i < mTracks.size(); i++) {
5908 sp<RecordTrack> track = mTracks[i];
5909 track->invalidate();
5910 }
Glenn Kasten2b806402013-11-20 16:37:38 -08005911 mActiveTracks.clear();
5912 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08005913 mStartStopCond.broadcast();
5914 }
5915
5916 releaseWakeLock();
5917
5918 ALOGV("RecordThread %p exiting", this);
5919 return false;
5920}
5921
Glenn Kasten93e471f2013-08-19 08:40:07 -07005922void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08005923{
5924 if (!mStandby) {
5925 inputStandBy();
5926 mStandby = true;
5927 }
5928}
5929
5930void AudioFlinger::RecordThread::inputStandBy()
5931{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005932 // Idle the fast capture if it's currently running
5933 if (mFastCapture != 0) {
5934 FastCaptureStateQueue *sq = mFastCapture->sq();
5935 FastCaptureState *state = sq->begin();
5936 if (!(state->mCommand & FastCaptureState::IDLE)) {
5937 state->mCommand = FastCaptureState::COLD_IDLE;
5938 state->mColdFutexAddr = &mFastCaptureFutex;
5939 state->mColdGen++;
5940 mFastCaptureFutex = 0;
5941 sq->end();
5942 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
5943 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
5944#if 0
5945 if (kUseFastCapture == FastCapture_Dynamic) {
5946 // FIXME
5947 }
5948#endif
5949#ifdef AUDIO_WATCHDOG
5950 // FIXME
5951#endif
5952 } else {
5953 sq->end(false /*didModify*/);
5954 }
5955 }
Eric Laurent81784c32012-11-19 14:55:58 -08005956 mInput->stream->common.standby(&mInput->stream->common);
5957}
5958
Glenn Kasten05997e22014-03-13 15:08:33 -07005959// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07005960sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08005961 const sp<AudioFlinger::Client>& client,
5962 uint32_t sampleRate,
5963 audio_format_t format,
5964 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08005965 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08005966 int sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07005967 size_t *notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005968 int uid,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07005969 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08005970 pid_t tid,
5971 status_t *status)
5972{
Glenn Kasten74935e42013-12-19 08:56:45 -08005973 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005974 sp<RecordTrack> track;
5975 status_t lStatus;
5976
Glenn Kasten90e58b12013-07-31 16:16:02 -07005977 // client expresses a preference for FAST, but we get the final say
5978 if (*flags & IAudioFlinger::TRACK_FAST) {
5979 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07005980 // we formerly checked for a callback handler (non-0 tid),
5981 // but that is no longer required for TRANSFER_OBTAIN mode
5982 //
Glenn Kasten74105912014-07-03 12:28:53 -07005983 // frame count is not specified, or is exactly the pipe depth
5984 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005985 // PCM data
5986 audio_is_linear_pcm(format) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005987 // native format
5988 (format == mFormat) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005989 // native channel mask
5990 (channelMask == mChannelMask) &&
5991 // native hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07005992 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005993 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005994 hasFastCapture() &&
5995 // there are sufficient fast track slots available
5996 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07005997 ) {
Glenn Kasten74105912014-07-03 12:28:53 -07005998 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%u mFrameCount=%u",
Glenn Kasten90e58b12013-07-31 16:16:02 -07005999 frameCount, mFrameCount);
6000 } else {
Glenn Kasten74105912014-07-03 12:28:53 -07006001 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%u mFrameCount=%u mPipeFramesP2=%u "
6002 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006003 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Glenn Kasten74105912014-07-03 12:28:53 -07006004 frameCount, mFrameCount, mPipeFramesP2,
6005 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
6006 hasFastCapture(), tid, mFastTrackAvail);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006007 *flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kasten74105912014-07-03 12:28:53 -07006008 }
6009 }
6010
6011 // compute track buffer size in frames, and suggest the notification frame count
6012 if (*flags & IAudioFlinger::TRACK_FAST) {
6013 // fast track: frame count is exactly the pipe depth
6014 frameCount = mPipeFramesP2;
6015 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
6016 *notificationFrames = mFrameCount;
6017 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006018 // not fast track: max notification period is resampled equivalent of one HAL buffer time
6019 // or 20 ms if there is a fast capture
6020 // TODO This could be a roundupRatio inline, and const
6021 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
6022 * sampleRate + mSampleRate - 1) / mSampleRate;
6023 // minimum number of notification periods is at least kMinNotifications,
6024 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
6025 static const size_t kMinNotifications = 3;
6026 static const uint32_t kMinMs = 30;
6027 // TODO This could be a roundupRatio inline
6028 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
6029 // TODO This could be a roundupRatio inline
6030 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
6031 maxNotificationFrames;
6032 const size_t minFrameCount = maxNotificationFrames *
6033 max(kMinNotifications, minNotificationsByMs);
6034 frameCount = max(frameCount, minFrameCount);
6035 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
6036 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07006037 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07006038 }
Glenn Kasten74935e42013-12-19 08:56:45 -08006039 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07006040
Glenn Kasten15e57982013-09-24 11:52:37 -07006041 lStatus = initCheck();
6042 if (lStatus != NO_ERROR) {
6043 ALOGE("createRecordTrack_l() audio driver not initialized");
6044 goto Exit;
6045 }
Eric Laurent81784c32012-11-19 14:55:58 -08006046
6047 { // scope for mLock
6048 Mutex::Autolock _l(mLock);
6049
6050 track = new RecordTrack(this, client, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07006051 format, channelMask, frameCount, NULL, sessionId, uid,
6052 *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08006053
Glenn Kasten03003332013-08-06 15:40:54 -07006054 lStatus = track->initCheck();
6055 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07006056 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08006057 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08006058 goto Exit;
6059 }
6060 mTracks.add(track);
6061
6062 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6063 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6064 mAudioFlinger->btNrecIsOff();
6065 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6066 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006067
6068 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
6069 pid_t callingPid = IPCThreadState::self()->getCallingPid();
6070 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
6071 // so ask activity manager to do this on our behalf
6072 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
6073 }
Eric Laurent81784c32012-11-19 14:55:58 -08006074 }
Glenn Kasten05997e22014-03-13 15:08:33 -07006075
Eric Laurent81784c32012-11-19 14:55:58 -08006076 lStatus = NO_ERROR;
6077
6078Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07006079 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08006080 return track;
6081}
6082
6083status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
6084 AudioSystem::sync_event_t event,
6085 int triggerSession)
6086{
6087 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
6088 sp<ThreadBase> strongMe = this;
6089 status_t status = NO_ERROR;
6090
6091 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006092 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006093 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006094 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08006095 triggerSession,
6096 recordTrack->sessionId(),
6097 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006098 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08006099 // Sync event can be cancelled by the trigger session if the track is not in a
6100 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006101 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006102 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006103 } else {
6104 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006105 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006106 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08006107 }
6108 }
6109
6110 {
Glenn Kasten47c20702013-08-13 15:37:35 -07006111 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08006112 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006113 if (mActiveTracks.indexOf(recordTrack) >= 0) {
6114 if (recordTrack->mState == TrackBase::PAUSING) {
6115 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006116 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006117 } else {
6118 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08006119 }
6120 return status;
6121 }
6122
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006123 // TODO consider other ways of handling this, such as changing the state to :STARTING and
6124 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
6125 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006126 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08006127 mActiveTracks.add(recordTrack);
6128 mActiveTracksGen++;
Eric Laurent83b88082014-06-20 18:31:16 -07006129 status_t status = NO_ERROR;
6130 if (recordTrack->isExternalTrack()) {
6131 mLock.unlock();
Eric Laurent4dc68062014-07-28 17:26:49 -07006132 status = AudioSystem::startInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006133 mLock.lock();
6134 // FIXME should verify that recordTrack is still in mActiveTracks
6135 if (status != NO_ERROR) {
6136 mActiveTracks.remove(recordTrack);
6137 mActiveTracksGen++;
6138 recordTrack->clearSyncStartEvent();
6139 ALOGV("RecordThread::start error %d", status);
6140 return status;
6141 }
Eric Laurent81784c32012-11-19 14:55:58 -08006142 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006143 // Catch up with current buffer indices if thread is already running.
6144 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
6145 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
6146 // see previously buffered data before it called start(), but with greater risk of overrun.
6147
Andy Hung73c02e42015-03-29 01:13:58 -07006148 recordTrack->mResamplerBufferProvider->reset();
Andy Hung97a893e2015-03-29 01:03:07 -07006149 // clear any converter state as new data will be discontinuous
6150 recordTrack->mRecordBufferConverter->reset();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006151 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08006152 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08006153 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08006154 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006155 ALOGV("Record failed to start");
6156 status = BAD_VALUE;
6157 goto startError;
6158 }
Eric Laurent81784c32012-11-19 14:55:58 -08006159 return status;
6160 }
Glenn Kasten7c027242012-12-26 14:43:16 -08006161
Eric Laurent81784c32012-11-19 14:55:58 -08006162startError:
Eric Laurent83b88082014-06-20 18:31:16 -07006163 if (recordTrack->isExternalTrack()) {
Eric Laurent4dc68062014-07-28 17:26:49 -07006164 AudioSystem::stopInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006165 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006166 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006167 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08006168 return status;
6169}
6170
Eric Laurent81784c32012-11-19 14:55:58 -08006171void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6172{
6173 sp<SyncEvent> strongEvent = event.promote();
6174
6175 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08006176 sp<RefBase> ptr = strongEvent->cookie().promote();
6177 if (ptr != 0) {
6178 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
6179 recordTrack->handleSyncStartEvent(strongEvent);
6180 }
Eric Laurent81784c32012-11-19 14:55:58 -08006181 }
6182}
6183
Glenn Kastena8356f62013-07-25 14:37:52 -07006184bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08006185 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07006186 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006187 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08006188 return false;
6189 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006190 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08006191 recordTrack->mState = TrackBase::PAUSING;
6192 // do not wait for mStartStopCond if exiting
6193 if (exitPending()) {
6194 return true;
6195 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006196 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08006197 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006198 // if we have been restarted, recordTrack is in mActiveTracks here
6199 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006200 ALOGV("Record stopped OK");
6201 return true;
6202 }
6203 return false;
6204}
6205
Glenn Kasten0f11b512014-01-31 16:18:54 -08006206bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08006207{
6208 return false;
6209}
6210
Glenn Kasten0f11b512014-01-31 16:18:54 -08006211status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006212{
6213#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
6214 if (!isValidSyncEvent(event)) {
6215 return BAD_VALUE;
6216 }
6217
6218 int eventSession = event->triggerSession();
6219 status_t ret = NAME_NOT_FOUND;
6220
6221 Mutex::Autolock _l(mLock);
6222
6223 for (size_t i = 0; i < mTracks.size(); i++) {
6224 sp<RecordTrack> track = mTracks[i];
6225 if (eventSession == track->sessionId()) {
6226 (void) track->setSyncEvent(event);
6227 ret = NO_ERROR;
6228 }
6229 }
6230 return ret;
6231#else
6232 return BAD_VALUE;
6233#endif
6234}
6235
6236// destroyTrack_l() must be called with ThreadBase::mLock held
6237void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6238{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006239 track->terminate();
6240 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08006241 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08006242 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006243 removeTrack_l(track);
6244 }
6245}
6246
6247void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6248{
6249 mTracks.remove(track);
6250 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006251 if (track->isFastTrack()) {
6252 ALOG_ASSERT(!mFastTrackAvail);
6253 mFastTrackAvail = true;
6254 }
Eric Laurent81784c32012-11-19 14:55:58 -08006255}
6256
6257void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6258{
6259 dumpInternals(fd, args);
6260 dumpTracks(fd, args);
6261 dumpEffectChains(fd, args);
6262}
6263
6264void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6265{
Elliott Hughes87cebad2014-05-22 10:14:43 -07006266 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08006267
Glenn Kasten44182c22015-03-05 17:12:23 -08006268 dumpBase(fd, args);
6269
6270 if (mActiveTracks.size() == 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006271 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006272 }
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006273 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006274 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08006275
6276 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
6277 const FastCaptureDumpState copy(mFastCaptureDumpState);
6278 copy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006279}
6280
Glenn Kasten0f11b512014-01-31 16:18:54 -08006281void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006282{
6283 const size_t SIZE = 256;
6284 char buffer[SIZE];
6285 String8 result;
6286
Marco Nelissenb2208842014-02-07 14:00:50 -08006287 size_t numtracks = mTracks.size();
6288 size_t numactive = mActiveTracks.size();
6289 size_t numactiveseen = 0;
Elliott Hughes87cebad2014-05-22 10:14:43 -07006290 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08006291 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006292 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08006293 RecordTrack::appendDumpHeader(result);
6294 for (size_t i = 0; i < numtracks ; ++i) {
6295 sp<RecordTrack> track = mTracks[i];
6296 if (track != 0) {
6297 bool active = mActiveTracks.indexOf(track) >= 0;
6298 if (active) {
6299 numactiveseen++;
6300 }
6301 track->dump(buffer, SIZE, active);
6302 result.append(buffer);
6303 }
Eric Laurent81784c32012-11-19 14:55:58 -08006304 }
Marco Nelissenb2208842014-02-07 14:00:50 -08006305 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006306 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006307 }
6308
Marco Nelissenb2208842014-02-07 14:00:50 -08006309 if (numactiveseen != numactive) {
6310 snprintf(buffer, SIZE, " The following tracks are in the active list but"
6311 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006312 result.append(buffer);
6313 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08006314 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08006315 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08006316 if (mTracks.indexOf(track) < 0) {
6317 track->dump(buffer, SIZE, true);
6318 result.append(buffer);
6319 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006320 }
Eric Laurent81784c32012-11-19 14:55:58 -08006321
6322 }
6323 write(fd, result.string(), result.size());
6324}
6325
Andy Hung73c02e42015-03-29 01:13:58 -07006326
6327void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
6328{
6329 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6330 RecordThread *recordThread = (RecordThread *) threadBase.get();
6331 mRsmpInFront = recordThread->mRsmpInRear;
6332 mRsmpInUnrel = 0;
6333}
6334
6335void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
6336 size_t *framesAvailable, bool *hasOverrun)
6337{
6338 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6339 RecordThread *recordThread = (RecordThread *) threadBase.get();
6340 const int32_t rear = recordThread->mRsmpInRear;
6341 const int32_t front = mRsmpInFront;
6342 const ssize_t filled = rear - front;
6343
6344 size_t framesIn;
6345 bool overrun = false;
6346 if (filled < 0) {
6347 // should not happen, but treat like a massive overrun and re-sync
6348 framesIn = 0;
6349 mRsmpInFront = rear;
6350 overrun = true;
6351 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
6352 framesIn = (size_t) filled;
6353 } else {
6354 // client is not keeping up with server, but give it latest data
6355 framesIn = recordThread->mRsmpInFrames;
6356 mRsmpInFront = /* front = */ rear - framesIn;
6357 overrun = true;
6358 }
6359 if (framesAvailable != NULL) {
6360 *framesAvailable = framesIn;
6361 }
6362 if (hasOverrun != NULL) {
6363 *hasOverrun = overrun;
6364 }
6365}
6366
Eric Laurent81784c32012-11-19 14:55:58 -08006367// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006368status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
6369 AudioBufferProvider::Buffer* buffer, int64_t pts __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006370{
Andy Hung73c02e42015-03-29 01:13:58 -07006371 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006372 if (threadBase == 0) {
6373 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006374 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006375 return NOT_ENOUGH_DATA;
6376 }
6377 RecordThread *recordThread = (RecordThread *) threadBase.get();
6378 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07006379 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07006380 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006381 // FIXME should not be P2 (don't want to increase latency)
6382 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006383 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07006384 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006385 front &= recordThread->mRsmpInFramesP2 - 1;
6386 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07006387 if (part1 > (size_t) filled) {
6388 part1 = filled;
6389 }
6390 size_t ask = buffer->frameCount;
6391 ALOG_ASSERT(ask > 0);
6392 if (part1 > ask) {
6393 part1 = ask;
6394 }
6395 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07006396 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07006397 buffer->raw = NULL;
6398 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07006399 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07006400 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08006401 }
6402
Andy Hung57446612015-04-19 23:56:46 -07006403 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07006404 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07006405 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08006406 return NO_ERROR;
6407}
6408
6409// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006410void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
6411 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006412{
Glenn Kasten85948432013-08-19 12:09:05 -07006413 size_t stepCount = buffer->frameCount;
6414 if (stepCount == 0) {
6415 return;
6416 }
Andy Hung73c02e42015-03-29 01:13:58 -07006417 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
6418 mRsmpInUnrel -= stepCount;
6419 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07006420 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006421 buffer->frameCount = 0;
6422}
6423
Andy Hung97a893e2015-03-29 01:03:07 -07006424AudioFlinger::RecordThread::RecordBufferConverter::RecordBufferConverter(
6425 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6426 uint32_t srcSampleRate,
6427 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6428 uint32_t dstSampleRate) :
6429 mSrcChannelMask(AUDIO_CHANNEL_INVALID), // updateParameters will set following vars
6430 // mSrcFormat
6431 // mSrcSampleRate
6432 // mDstChannelMask
6433 // mDstFormat
6434 // mDstSampleRate
6435 // mSrcChannelCount
6436 // mDstChannelCount
6437 // mDstFrameSize
6438 mBuf(NULL), mBufFrames(0), mBufFrameSize(0),
Andy Hungd330ee42015-04-20 13:23:41 -07006439 mResampler(NULL),
6440 mIsLegacyDownmix(false),
6441 mIsLegacyUpmix(false),
6442 mRequiresFloat(false),
6443 mInputConverterProvider(NULL)
Andy Hung97a893e2015-03-29 01:03:07 -07006444{
6445 (void)updateParameters(srcChannelMask, srcFormat, srcSampleRate,
6446 dstChannelMask, dstFormat, dstSampleRate);
6447}
6448
6449AudioFlinger::RecordThread::RecordBufferConverter::~RecordBufferConverter() {
6450 free(mBuf);
6451 delete mResampler;
Andy Hungd330ee42015-04-20 13:23:41 -07006452 delete mInputConverterProvider;
Andy Hung97a893e2015-03-29 01:03:07 -07006453}
6454
6455size_t AudioFlinger::RecordThread::RecordBufferConverter::convert(void *dst,
6456 AudioBufferProvider *provider, size_t frames)
6457{
Andy Hungd330ee42015-04-20 13:23:41 -07006458 if (mInputConverterProvider != NULL) {
6459 mInputConverterProvider->setBufferProvider(provider);
6460 provider = mInputConverterProvider;
6461 }
6462
6463 if (mResampler == NULL) {
Andy Hung97a893e2015-03-29 01:03:07 -07006464 ALOGVV("NO RESAMPLING sampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6465 mSrcSampleRate, mSrcFormat, mDstFormat);
6466
6467 AudioBufferProvider::Buffer buffer;
6468 for (size_t i = frames; i > 0; ) {
6469 buffer.frameCount = i;
6470 status_t status = provider->getNextBuffer(&buffer, 0);
6471 if (status != OK || buffer.frameCount == 0) {
6472 frames -= i; // cannot fill request.
6473 break;
6474 }
Andy Hungd330ee42015-04-20 13:23:41 -07006475 // format convert to destination buffer
6476 convertNoResampler(dst, buffer.raw, buffer.frameCount);
Andy Hung97a893e2015-03-29 01:03:07 -07006477
6478 dst = (int8_t*)dst + buffer.frameCount * mDstFrameSize;
6479 i -= buffer.frameCount;
6480 provider->releaseBuffer(&buffer);
6481 }
6482 } else {
6483 ALOGVV("RESAMPLING mSrcSampleRate:%u mDstSampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6484 mSrcSampleRate, mDstSampleRate, mSrcFormat, mDstFormat);
6485
Andy Hungd330ee42015-04-20 13:23:41 -07006486 // reallocate buffer if needed
6487 if (mBufFrameSize != 0 && mBufFrames < frames) {
6488 free(mBuf);
6489 mBufFrames = frames;
6490 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
6491 }
Andy Hung97a893e2015-03-29 01:03:07 -07006492 // resampler accumulates, but we only have one source track
Andy Hungd330ee42015-04-20 13:23:41 -07006493 memset(mBuf, 0, frames * mBufFrameSize);
6494 frames = mResampler->resample((int32_t*)mBuf, frames, provider);
6495 // format convert to destination buffer
6496 convertResampler(dst, mBuf, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006497 }
6498 return frames;
6499}
6500
6501status_t AudioFlinger::RecordThread::RecordBufferConverter::updateParameters(
6502 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6503 uint32_t srcSampleRate,
6504 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6505 uint32_t dstSampleRate)
6506{
6507 // quick evaluation if there is any change.
6508 if (mSrcFormat == srcFormat
6509 && mSrcChannelMask == srcChannelMask
6510 && mSrcSampleRate == srcSampleRate
6511 && mDstFormat == dstFormat
6512 && mDstChannelMask == dstChannelMask
6513 && mDstSampleRate == dstSampleRate) {
6514 return NO_ERROR;
6515 }
6516
Andy Hungdb4c0312015-05-06 08:46:52 -07006517 ALOGV("RecordBufferConverter updateParameters srcMask:%#x dstMask:%#x"
6518 " srcFormat:%#x dstFormat:%#x srcRate:%u dstRate:%u",
6519 srcChannelMask, dstChannelMask, srcFormat, dstFormat, srcSampleRate, dstSampleRate);
Andy Hung97a893e2015-03-29 01:03:07 -07006520 const bool valid =
6521 audio_is_input_channel(srcChannelMask)
6522 && audio_is_input_channel(dstChannelMask)
6523 && audio_is_valid_format(srcFormat) && audio_is_linear_pcm(srcFormat)
6524 && audio_is_valid_format(dstFormat) && audio_is_linear_pcm(dstFormat)
6525 && (srcSampleRate <= dstSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX)
6526 ; // no upsampling checks for now
6527 if (!valid) {
6528 return BAD_VALUE;
6529 }
6530
6531 mSrcFormat = srcFormat;
6532 mSrcChannelMask = srcChannelMask;
6533 mSrcSampleRate = srcSampleRate;
6534 mDstFormat = dstFormat;
6535 mDstChannelMask = dstChannelMask;
6536 mDstSampleRate = dstSampleRate;
6537
6538 // compute derived parameters
6539 mSrcChannelCount = audio_channel_count_from_in_mask(srcChannelMask);
6540 mDstChannelCount = audio_channel_count_from_in_mask(dstChannelMask);
6541 mDstFrameSize = mDstChannelCount * audio_bytes_per_sample(mDstFormat);
6542
Andy Hungd330ee42015-04-20 13:23:41 -07006543 // do we need to resample?
6544 delete mResampler;
6545 mResampler = NULL;
6546 if (mSrcSampleRate != mDstSampleRate) {
6547 mResampler = AudioResampler::create(AUDIO_FORMAT_PCM_FLOAT,
6548 mSrcChannelCount, mDstSampleRate);
6549 mResampler->setSampleRate(mSrcSampleRate);
6550 mResampler->setVolume(AudioMixer::UNITY_GAIN_FLOAT, AudioMixer::UNITY_GAIN_FLOAT);
6551 }
6552
6553 // are we running legacy channel conversion modes?
6554 mIsLegacyDownmix = (mSrcChannelMask == AUDIO_CHANNEL_IN_STEREO
6555 || mSrcChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK)
6556 && mDstChannelMask == AUDIO_CHANNEL_IN_MONO;
6557 mIsLegacyUpmix = mSrcChannelMask == AUDIO_CHANNEL_IN_MONO
6558 && (mDstChannelMask == AUDIO_CHANNEL_IN_STEREO
6559 || mDstChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK);
6560
6561 // do we need to process in float?
6562 mRequiresFloat = mResampler != NULL || mIsLegacyDownmix || mIsLegacyUpmix;
6563
6564 // do we need a staging buffer to convert for destination (we can still optimize this)?
6565 // we use mBufFrameSize > 0 to indicate both frame size as well as buffer necessity
6566 if (mResampler != NULL) {
6567 mBufFrameSize = max(mSrcChannelCount, FCC_2)
6568 * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
6569 } else if ((mIsLegacyUpmix || mIsLegacyDownmix) && mDstFormat != AUDIO_FORMAT_PCM_FLOAT) {
6570 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
6571 } else if (mSrcChannelMask != mDstChannelMask && mDstFormat != mSrcFormat) {
Andy Hung97a893e2015-03-29 01:03:07 -07006572 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(mSrcFormat);
6573 } else {
6574 mBufFrameSize = 0;
6575 }
6576 mBufFrames = 0; // force the buffer to be resized.
6577
Andy Hungd330ee42015-04-20 13:23:41 -07006578 // do we need an input converter buffer provider to give us float?
6579 delete mInputConverterProvider;
6580 mInputConverterProvider = NULL;
6581 if (mRequiresFloat && mSrcFormat != AUDIO_FORMAT_PCM_FLOAT) {
6582 mInputConverterProvider = new ReformatBufferProvider(
6583 audio_channel_count_from_in_mask(mSrcChannelMask),
6584 mSrcFormat,
6585 AUDIO_FORMAT_PCM_FLOAT,
6586 256 /* provider buffer frame count */);
6587 }
6588
6589 // do we need a remixer to do channel mask conversion
6590 if (!mIsLegacyDownmix && !mIsLegacyUpmix && mSrcChannelMask != mDstChannelMask) {
6591 (void) memcpy_by_index_array_initialization_from_channel_mask(
6592 mIdxAry, ARRAY_SIZE(mIdxAry), mDstChannelMask, mSrcChannelMask);
Andy Hung97a893e2015-03-29 01:03:07 -07006593 }
6594 return NO_ERROR;
6595}
6596
Andy Hungd330ee42015-04-20 13:23:41 -07006597void AudioFlinger::RecordThread::RecordBufferConverter::convertNoResampler(
6598 void *dst, const void *src, size_t frames)
Andy Hung97a893e2015-03-29 01:03:07 -07006599{
Andy Hungd330ee42015-04-20 13:23:41 -07006600 // src is native type unless there is legacy upmix or downmix, whereupon it is float.
Andy Hung97a893e2015-03-29 01:03:07 -07006601 if (mBufFrameSize != 0 && mBufFrames < frames) {
6602 free(mBuf);
6603 mBufFrames = frames;
6604 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
6605 }
Andy Hungd330ee42015-04-20 13:23:41 -07006606 // do we need to do legacy upmix and downmix?
6607 if (mIsLegacyUpmix || mIsLegacyDownmix) {
Andy Hung97a893e2015-03-29 01:03:07 -07006608 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07006609 if (mIsLegacyUpmix) {
6610 upmix_to_stereo_float_from_mono_float((float *)dstBuf,
6611 (const float *)src, frames);
6612 } else /*mIsLegacyDownmix */ {
6613 downmix_to_mono_float_from_stereo_float((float *)dstBuf,
6614 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006615 }
Andy Hungd330ee42015-04-20 13:23:41 -07006616 if (mBuf != NULL) {
6617 memcpy_by_audio_format(dst, mDstFormat, mBuf, AUDIO_FORMAT_PCM_FLOAT,
6618 frames * mDstChannelCount);
6619 }
6620 return;
6621 }
6622 // do we need to do channel mask conversion?
6623 if (mSrcChannelMask != mDstChannelMask) {
Andy Hung97a893e2015-03-29 01:03:07 -07006624 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07006625 memcpy_by_index_array(dstBuf, mDstChannelCount,
6626 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mSrcFormat), frames);
6627 if (dstBuf == dst) {
6628 return; // format is the same
6629 }
6630 }
6631 // convert to destination buffer
6632 const void *convertBuf = mBuf != NULL ? mBuf : src;
6633 memcpy_by_audio_format(dst, mDstFormat, convertBuf, mSrcFormat,
6634 frames * mDstChannelCount);
6635}
6636
6637void AudioFlinger::RecordThread::RecordBufferConverter::convertResampler(
6638 void *dst, /*not-a-const*/ void *src, size_t frames)
6639{
6640 // src buffer format is ALWAYS float when entering this routine
6641 if (mIsLegacyUpmix) {
6642 ; // mono to stereo already handled by resampler
6643 } else if (mIsLegacyDownmix
6644 || (mSrcChannelMask == mDstChannelMask && mSrcChannelCount == 1)) {
6645 // the resampler outputs stereo for mono input channel (a feature?)
6646 // must convert to mono
6647 downmix_to_mono_float_from_stereo_float((float *)src,
6648 (const float *)src, frames);
6649 } else if (mSrcChannelMask != mDstChannelMask) {
6650 // convert to mono channel again for channel mask conversion (could be skipped
6651 // with further optimization).
Andy Hung97a893e2015-03-29 01:03:07 -07006652 if (mSrcChannelCount == 1) {
Andy Hungd330ee42015-04-20 13:23:41 -07006653 downmix_to_mono_float_from_stereo_float((float *)src,
6654 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006655 }
Andy Hungd330ee42015-04-20 13:23:41 -07006656 // convert to destination format (in place, OK as float is larger than other types)
6657 if (mDstFormat != AUDIO_FORMAT_PCM_FLOAT) {
6658 memcpy_by_audio_format(src, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
6659 frames * mSrcChannelCount);
6660 }
6661 // channel convert and save to dst
6662 memcpy_by_index_array(dst, mDstChannelCount,
6663 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mDstFormat), frames);
6664 return;
Andy Hung97a893e2015-03-29 01:03:07 -07006665 }
Andy Hungd330ee42015-04-20 13:23:41 -07006666 // convert to destination format and save to dst
6667 memcpy_by_audio_format(dst, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
6668 frames * mDstChannelCount);
Andy Hung97a893e2015-03-29 01:03:07 -07006669}
6670
Eric Laurent10351942014-05-08 18:49:52 -07006671bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
6672 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006673{
6674 bool reconfig = false;
6675
Eric Laurent10351942014-05-08 18:49:52 -07006676 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006677
Eric Laurent10351942014-05-08 18:49:52 -07006678 audio_format_t reqFormat = mFormat;
6679 uint32_t samplingRate = mSampleRate;
6680 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
Andy Hungd330ee42015-04-20 13:23:41 -07006681 // possible that we are > 2 channels, use channel index mask
6682 if (channelMask == AUDIO_CHANNEL_INVALID && mChannelCount <= FCC_8) {
6683 audio_channel_mask_for_index_assignment_from_count(mChannelCount);
6684 }
Eric Laurent10351942014-05-08 18:49:52 -07006685
6686 AudioParameter param = AudioParameter(keyValuePair);
6687 int value;
6688 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
6689 // channel count change can be requested. Do we mandate the first client defines the
6690 // HAL sampling rate and channel count or do we allow changes on the fly?
6691 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6692 samplingRate = value;
6693 reconfig = true;
6694 }
6695 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07006696 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07006697 status = BAD_VALUE;
6698 } else {
6699 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08006700 reconfig = true;
6701 }
Eric Laurent10351942014-05-08 18:49:52 -07006702 }
6703 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
6704 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07006705 if (!audio_is_input_channel(mask) ||
6706 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07006707 status = BAD_VALUE;
6708 } else {
6709 channelMask = mask;
6710 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006711 }
Eric Laurent10351942014-05-08 18:49:52 -07006712 }
6713 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6714 // do not accept frame count changes if tracks are open as the track buffer
6715 // size depends on frame count and correct behavior would not be guaranteed
6716 // if frame count is changed after track creation
6717 if (mActiveTracks.size() > 0) {
6718 status = INVALID_OPERATION;
6719 } else {
6720 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006721 }
Eric Laurent10351942014-05-08 18:49:52 -07006722 }
6723 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6724 // forward device change to effects that have requested to be
6725 // aware of attached audio device.
6726 for (size_t i = 0; i < mEffectChains.size(); i++) {
6727 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08006728 }
Eric Laurent81784c32012-11-19 14:55:58 -08006729
Eric Laurent10351942014-05-08 18:49:52 -07006730 // store input device and output device but do not forward output device to audio HAL.
6731 // Note that status is ignored by the caller for output device
6732 // (see AudioFlinger::setParameters()
6733 if (audio_is_output_devices(value)) {
6734 mOutDevice = value;
6735 status = BAD_VALUE;
6736 } else {
6737 mInDevice = value;
6738 // disable AEC and NS if the device is a BT SCO headset supporting those
6739 // pre processings
6740 if (mTracks.size() > 0) {
6741 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6742 mAudioFlinger->btNrecIsOff();
6743 for (size_t i = 0; i < mTracks.size(); i++) {
6744 sp<RecordTrack> track = mTracks[i];
6745 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
6746 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08006747 }
6748 }
6749 }
Eric Laurent10351942014-05-08 18:49:52 -07006750 }
6751 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
6752 mAudioSource != (audio_source_t)value) {
6753 // forward device change to effects that have requested to be
6754 // aware of attached audio device.
6755 for (size_t i = 0; i < mEffectChains.size(); i++) {
6756 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08006757 }
Eric Laurent10351942014-05-08 18:49:52 -07006758 mAudioSource = (audio_source_t)value;
6759 }
Glenn Kastene198c362013-08-13 09:13:36 -07006760
Eric Laurent10351942014-05-08 18:49:52 -07006761 if (status == NO_ERROR) {
6762 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6763 keyValuePair.string());
6764 if (status == INVALID_OPERATION) {
6765 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006766 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6767 keyValuePair.string());
Eric Laurent10351942014-05-08 18:49:52 -07006768 }
6769 if (reconfig) {
6770 if (status == BAD_VALUE &&
Andy Hung97a893e2015-03-29 01:03:07 -07006771 audio_is_linear_pcm(mInput->stream->common.get_format(&mInput->stream->common)) &&
6772 audio_is_linear_pcm(reqFormat) &&
Eric Laurent10351942014-05-08 18:49:52 -07006773 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
Andy Hung97a893e2015-03-29 01:03:07 -07006774 <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate)) &&
Andy Hunge5412692014-05-16 11:25:07 -07006775 audio_channel_count_from_in_mask(
Andy Hungd1abb8f2015-05-05 23:42:34 -07006776 mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07006777 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006778 }
Eric Laurent10351942014-05-08 18:49:52 -07006779 if (status == NO_ERROR) {
6780 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07006781 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08006782 }
6783 }
Eric Laurent81784c32012-11-19 14:55:58 -08006784 }
Eric Laurent10351942014-05-08 18:49:52 -07006785
Eric Laurent81784c32012-11-19 14:55:58 -08006786 return reconfig;
6787}
6788
6789String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6790{
Eric Laurent81784c32012-11-19 14:55:58 -08006791 Mutex::Autolock _l(mLock);
6792 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07006793 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08006794 }
6795
Glenn Kastend8ea6992013-07-16 14:17:15 -07006796 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
6797 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08006798 free(s);
6799 return out_s8;
6800}
6801
Eric Laurent73e26b62015-04-27 16:55:58 -07006802void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event) {
6803 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
6804
6805 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08006806
6807 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07006808 case AUDIO_INPUT_OPENED:
6809 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07006810 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07006811 desc->mChannelMask = mChannelMask;
6812 desc->mSamplingRate = mSampleRate;
6813 desc->mFormat = mFormat;
6814 desc->mFrameCount = mFrameCount;
6815 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006816 break;
6817
Eric Laurent73e26b62015-04-27 16:55:58 -07006818 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08006819 default:
6820 break;
6821 }
Eric Laurent73e26b62015-04-27 16:55:58 -07006822 mAudioFlinger->ioConfigChanged(event, desc);
Eric Laurent81784c32012-11-19 14:55:58 -08006823}
6824
Glenn Kastendeca2ae2014-02-07 10:25:56 -08006825void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006826{
Eric Laurent81784c32012-11-19 14:55:58 -08006827 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
6828 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Andy Hunge5412692014-05-16 11:25:07 -07006829 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Andy Hungd330ee42015-04-20 13:23:41 -07006830 if (mChannelCount > FCC_8) {
6831 ALOGE("HAL channel count %d > %d", mChannelCount, FCC_8);
6832 }
Andy Hung463be252014-07-10 16:56:07 -07006833 mHALFormat = mInput->stream->common.get_format(&mInput->stream->common);
6834 mFormat = mHALFormat;
Andy Hungd330ee42015-04-20 13:23:41 -07006835 if (!audio_is_linear_pcm(mFormat)) {
6836 ALOGE("HAL format %#x is not linear pcm", mFormat);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07006837 }
Eric Laurent665470b2014-07-03 16:37:08 -07006838 mFrameSize = audio_stream_in_frame_size(mInput->stream);
Glenn Kasten548efc92012-11-29 08:48:51 -08006839 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
6840 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006841 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08006842 // 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 -07006843 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08006844 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006845 // A larger value should allow more old data to be read after a track calls start(),
6846 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07006847 //
6848 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08006849 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07006850 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07006851 free(mRsmpInBuffer);
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006852
6853 // TODO optimize audio capture buffer sizes ...
6854 // Here we calculate the size of the sliding buffer used as a source
6855 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
6856 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
6857 // be better to have it derived from the pipe depth in the long term.
6858 // The current value is higher than necessary. However it should not add to latency.
6859
Glenn Kasten85948432013-08-19 12:09:05 -07006860 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Andy Hung57446612015-04-19 23:56:46 -07006861 (void)posix_memalign(&mRsmpInBuffer, 32, (mRsmpInFramesP2 + mFrameCount - 1) * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006862
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006863 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
6864 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08006865}
6866
Glenn Kasten5f972c02014-01-13 09:59:31 -08006867uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08006868{
6869 Mutex::Autolock _l(mLock);
6870 if (initCheck() != NO_ERROR) {
6871 return 0;
6872 }
6873
6874 return mInput->stream->get_input_frames_lost(mInput->stream);
6875}
6876
6877uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
6878{
6879 Mutex::Autolock _l(mLock);
6880 uint32_t result = 0;
6881 if (getEffectChain_l(sessionId) != 0) {
6882 result = EFFECT_SESSION;
6883 }
6884
6885 for (size_t i = 0; i < mTracks.size(); ++i) {
6886 if (sessionId == mTracks[i]->sessionId()) {
6887 result |= TRACK_SESSION;
6888 break;
6889 }
6890 }
6891
6892 return result;
6893}
6894
6895KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
6896{
6897 KeyedVector<int, bool> ids;
6898 Mutex::Autolock _l(mLock);
6899 for (size_t j = 0; j < mTracks.size(); ++j) {
6900 sp<RecordThread::RecordTrack> track = mTracks[j];
6901 int sessionId = track->sessionId();
6902 if (ids.indexOfKey(sessionId) < 0) {
6903 ids.add(sessionId, true);
6904 }
6905 }
6906 return ids;
6907}
6908
6909AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
6910{
6911 Mutex::Autolock _l(mLock);
6912 AudioStreamIn *input = mInput;
6913 mInput = NULL;
6914 return input;
6915}
6916
6917// this method must always be called either with ThreadBase mLock held or inside the thread loop
6918audio_stream_t* AudioFlinger::RecordThread::stream() const
6919{
6920 if (mInput == NULL) {
6921 return NULL;
6922 }
6923 return &mInput->stream->common;
6924}
6925
6926status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6927{
6928 // only one chain per input thread
6929 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07006930 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08006931 return INVALID_OPERATION;
6932 }
6933 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07006934 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08006935 chain->setInBuffer(NULL);
6936 chain->setOutBuffer(NULL);
6937
6938 checkSuspendOnAddEffectChain_l(chain);
6939
Eric Laurent1b928682014-10-02 19:41:47 -07006940 // make sure enabled pre processing effects state is communicated to the HAL as we
6941 // just moved them to a new input stream.
6942 chain->syncHalEffectsState();
6943
Eric Laurent81784c32012-11-19 14:55:58 -08006944 mEffectChains.add(chain);
6945
6946 return NO_ERROR;
6947}
6948
6949size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6950{
6951 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
6952 ALOGW_IF(mEffectChains.size() != 1,
6953 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6954 chain.get(), mEffectChains.size(), this);
6955 if (mEffectChains.size() == 1) {
6956 mEffectChains.removeAt(0);
6957 }
6958 return 0;
6959}
6960
Eric Laurent1c333e22014-05-20 10:48:17 -07006961status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
6962 audio_patch_handle_t *handle)
6963{
6964 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07006965
6966 // store new device and send to effects
6967 mInDevice = patch->sources[0].ext.device.type;
Eric Laurent296fb132015-05-01 11:38:42 -07006968 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07006969 for (size_t i = 0; i < mEffectChains.size(); i++) {
6970 mEffectChains[i]->setDevice_l(mInDevice);
6971 }
6972
6973 // disable AEC and NS if the device is a BT SCO headset supporting those
6974 // pre processings
6975 if (mTracks.size() > 0) {
6976 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6977 mAudioFlinger->btNrecIsOff();
6978 for (size_t i = 0; i < mTracks.size(); i++) {
6979 sp<RecordTrack> track = mTracks[i];
6980 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
6981 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
6982 }
6983 }
6984
6985 // store new source and send to effects
6986 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
6987 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07006988 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07006989 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07006990 }
Eric Laurent054d9d32015-04-24 08:48:48 -07006991 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006992
Eric Laurent054d9d32015-04-24 08:48:48 -07006993 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006994 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
6995 status = hwDevice->create_audio_patch(hwDevice,
6996 patch->num_sources,
6997 patch->sources,
6998 patch->num_sinks,
6999 patch->sinks,
7000 handle);
7001 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007002 char *address;
7003 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
7004 address = audio_device_address_to_parameter(
7005 patch->sources[0].ext.device.type,
7006 patch->sources[0].ext.device.address);
7007 } else {
7008 address = (char *)calloc(1, 1);
7009 }
7010 AudioParameter param = AudioParameter(String8(address));
7011 free(address);
7012 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING),
7013 (int)patch->sources[0].ext.device.type);
7014 param.addInt(String8(AUDIO_PARAMETER_STREAM_INPUT_SOURCE),
7015 (int)patch->sinks[0].ext.mix.usecase.source);
7016 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7017 param.toString().string());
7018 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07007019 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007020
Eric Laurent296fb132015-05-01 11:38:42 -07007021 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
7022
Eric Laurent1c333e22014-05-20 10:48:17 -07007023 return status;
7024}
7025
7026status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
7027{
7028 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007029
7030 mInDevice = AUDIO_DEVICE_NONE;
7031
Eric Laurent1c333e22014-05-20 10:48:17 -07007032 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
7033 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
7034 status = hwDevice->release_audio_patch(hwDevice, handle);
7035 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007036 AudioParameter param;
7037 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
7038 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7039 param.toString().string());
Eric Laurent1c333e22014-05-20 10:48:17 -07007040 }
7041 return status;
7042}
7043
Eric Laurent83b88082014-06-20 18:31:16 -07007044void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
7045{
7046 Mutex::Autolock _l(mLock);
7047 mTracks.add(record);
7048}
7049
7050void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
7051{
7052 Mutex::Autolock _l(mLock);
7053 destroyTrack_l(record);
7054}
7055
7056void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
7057{
7058 ThreadBase::getAudioPortConfig(config);
7059 config->role = AUDIO_PORT_ROLE_SINK;
7060 config->ext.mix.hw_module = mInput->audioHwDev->handle();
7061 config->ext.mix.usecase.source = mAudioSource;
7062}
Eric Laurent1c333e22014-05-20 10:48:17 -07007063
Glenn Kasten63238ef2015-03-02 15:50:29 -08007064} // namespace android