blob: d9f1a83ad85c20b7c08b8e6c21605f5efbb586cc [file] [log] [blame]
Eric Laurent81784c32012-11-19 14:55:58 -08001/*
2**
3** Copyright 2012, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
Alex Ray371eb972012-11-30 11:11:54 -080021#define ATRACE_TAG ATRACE_TAG_AUDIO
Eric Laurent81784c32012-11-19 14:55:58 -080022
Glenn Kasten153b9fe2013-07-15 11:23:36 -070023#include "Configuration.h"
Eric Laurent81784c32012-11-19 14:55:58 -080024#include <math.h>
25#include <fcntl.h>
Glenn Kastenad8510a2015-02-17 16:24:07 -080026#include <linux/futex.h>
Eric Laurent81784c32012-11-19 14:55:58 -080027#include <sys/stat.h>
Glenn Kastenad8510a2015-02-17 16:24:07 -080028#include <sys/syscall.h>
Eric Laurent81784c32012-11-19 14:55:58 -080029#include <cutils/properties.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070030#include <media/AudioParameter.h>
Andy Hungcd044842014-08-07 11:04:34 -070031#include <media/AudioResamplerPublic.h>
Eric Laurent81784c32012-11-19 14:55:58 -080032#include <utils/Log.h>
Alex Ray371eb972012-11-30 11:11:54 -080033#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080034
35#include <private/media/AudioTrackShared.h>
36#include <hardware/audio.h>
37#include <audio_effects/effect_ns.h>
38#include <audio_effects/effect_aec.h>
39#include <audio_utils/primitives.h>
Andy Hung98ef9782014-03-04 14:46:50 -080040#include <audio_utils/format.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070041#include <audio_utils/minifloat.h>
Eric Laurent81784c32012-11-19 14:55:58 -080042
43// NBAIO implementations
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070044#include <media/nbaio/AudioStreamInSource.h>
Eric Laurent81784c32012-11-19 14:55:58 -080045#include <media/nbaio/AudioStreamOutSink.h>
46#include <media/nbaio/MonoPipe.h>
47#include <media/nbaio/MonoPipeReader.h>
48#include <media/nbaio/Pipe.h>
49#include <media/nbaio/PipeReader.h>
50#include <media/nbaio/SourceAudioBufferProvider.h>
51
52#include <powermanager/PowerManager.h>
53
54#include <common_time/cc_helper.h>
55#include <common_time/local_clock.h>
56
57#include "AudioFlinger.h"
58#include "AudioMixer.h"
Andy Hungd330ee42015-04-20 13:23:41 -070059#include "BufferProviders.h"
Eric Laurent81784c32012-11-19 14:55:58 -080060#include "FastMixer.h"
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070061#include "FastCapture.h"
Eric Laurent81784c32012-11-19 14:55:58 -080062#include "ServiceUtilities.h"
63#include "SchedulingPolicyService.h"
64
Eric Laurent81784c32012-11-19 14:55:58 -080065#ifdef ADD_BATTERY_DATA
66#include <media/IMediaPlayerService.h>
67#include <media/IMediaDeathNotifier.h>
68#endif
69
Eric Laurent81784c32012-11-19 14:55:58 -080070#ifdef DEBUG_CPU_USAGE
71#include <cpustats/CentralTendencyStatistics.h>
72#include <cpustats/ThreadCpuUsage.h>
73#endif
74
75// ----------------------------------------------------------------------------
76
77// Note: the following macro is used for extremely verbose logging message. In
78// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
79// 0; but one side effect of this is to turn all LOGV's as well. Some messages
80// are so verbose that we want to suppress them even when we have ALOG_ASSERT
81// turned on. Do not uncomment the #def below unless you really know what you
82// are doing and want to see all of the extremely verbose messages.
83//#define VERY_VERY_VERBOSE_LOGGING
84#ifdef VERY_VERY_VERBOSE_LOGGING
85#define ALOGVV ALOGV
86#else
87#define ALOGVV(a...) do { } while(0)
88#endif
89
Andy Hung6770c6f2015-04-07 13:43:36 -070090// TODO: Move these macro/inlines to a header file.
Glenn Kasten49d00ad2014-07-21 11:22:03 -070091#define max(a, b) ((a) > (b) ? (a) : (b))
Andy Hung6770c6f2015-04-07 13:43:36 -070092template <typename T>
93static inline T min(const T& a, const T& b)
94{
95 return a < b ? a : b;
96}
Glenn Kasten49d00ad2014-07-21 11:22:03 -070097
Andy Hungd330ee42015-04-20 13:23:41 -070098#ifndef ARRAY_SIZE
99#define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
100#endif
101
Eric Laurent81784c32012-11-19 14:55:58 -0800102namespace android {
103
104// retry counts for buffer fill timeout
105// 50 * ~20msecs = 1 second
106static const int8_t kMaxTrackRetries = 50;
107static const int8_t kMaxTrackStartupRetries = 50;
108// allow less retry attempts on direct output thread.
109// direct outputs can be a scarce resource in audio hardware and should
110// be released as quickly as possible.
111static const int8_t kMaxTrackRetriesDirect = 2;
112
113// don't warn about blocked writes or record buffer overflows more often than this
114static const nsecs_t kWarningThrottleNs = seconds(5);
115
116// RecordThread loop sleep time upon application overrun or audio HAL read error
117static const int kRecordThreadSleepUs = 5000;
118
Eric Laurent10351942014-05-08 18:49:52 -0700119// maximum time to wait in sendConfigEvent_l() for a status to be received
120static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800121
122// minimum sleep time for the mixer thread loop when tracks are active but in underrun
123static const uint32_t kMinThreadSleepTimeUs = 5000;
124// maximum divider applied to the active sleep time in the mixer thread loop
125static const uint32_t kMaxThreadSleepTimeShift = 2;
126
Andy Hung09a50072014-02-27 14:30:47 -0800127// minimum normal sink buffer size, expressed in milliseconds rather than frames
128static const uint32_t kMinNormalSinkBufferSizeMs = 20;
129// maximum normal sink buffer size
130static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800131
Eric Laurent972a1732013-09-04 09:42:59 -0700132// Offloaded output thread standby delay: allows track transition without going to standby
133static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
134
Eric Laurent81784c32012-11-19 14:55:58 -0800135// Whether to use fast mixer
136static const enum {
137 FastMixer_Never, // never initialize or use: for debugging only
138 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
139 // normal mixer multiplier is 1
140 FastMixer_Static, // initialize if needed, then use all the time if initialized,
141 // multiplier is calculated based on min & max normal mixer buffer size
142 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
143 // multiplier is calculated based on min & max normal mixer buffer size
144 // FIXME for FastMixer_Dynamic:
145 // Supporting this option will require fixing HALs that can't handle large writes.
146 // For example, one HAL implementation returns an error from a large write,
147 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
148 // We could either fix the HAL implementations, or provide a wrapper that breaks
149 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
150} kUseFastMixer = FastMixer_Static;
151
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700152// Whether to use fast capture
153static const enum {
154 FastCapture_Never, // never initialize or use: for debugging only
155 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
156 FastCapture_Static, // initialize if needed, then use all the time if initialized
157} kUseFastCapture = FastCapture_Static;
158
Eric Laurent81784c32012-11-19 14:55:58 -0800159// Priorities for requestPriority
160static const int kPriorityAudioApp = 2;
161static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700162static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800163
164// IAudioFlinger::createTrack() reports back to client the total size of shared memory area
165// for the track. The client then sub-divides this into smaller buffers for its use.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800166// Currently the client uses N-buffering by default, but doesn't tell us about the value of N.
167// So for now we just assume that client is double-buffered for fast tracks.
168// FIXME It would be better for client to tell AudioFlinger the value of N,
169// so AudioFlinger could allocate the right amount of memory.
Eric Laurent81784c32012-11-19 14:55:58 -0800170// See the client's minBufCount and mNotificationFramesAct calculations for details.
Glenn Kasten03490092014-05-27 12:30:54 -0700171
172// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800173static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800174
Glenn Kasten03490092014-05-27 12:30:54 -0700175// The minimum and maximum allowed values
176static const int kFastTrackMultiplierMin = 1;
177static const int kFastTrackMultiplierMax = 2;
178
179// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
180static int sFastTrackMultiplier = kFastTrackMultiplier;
181
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700182// See Thread::readOnlyHeap().
183// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
184// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
185// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Glenn Kasten9f81de32014-07-27 15:02:23 -0700186static const size_t kRecordThreadReadOnlyHeapSize = 0x2000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700187
Eric Laurent81784c32012-11-19 14:55:58 -0800188// ----------------------------------------------------------------------------
189
Glenn Kasten03490092014-05-27 12:30:54 -0700190static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
191
192static void sFastTrackMultiplierInit()
193{
194 char value[PROPERTY_VALUE_MAX];
195 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
196 char *endptr;
197 unsigned long ul = strtoul(value, &endptr, 0);
198 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
199 sFastTrackMultiplier = (int) ul;
200 }
201 }
202}
203
204// ----------------------------------------------------------------------------
205
Eric Laurent81784c32012-11-19 14:55:58 -0800206#ifdef ADD_BATTERY_DATA
207// To collect the amplifier usage
208static void addBatteryData(uint32_t params) {
209 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
210 if (service == NULL) {
211 // it already logged
212 return;
213 }
214
215 service->addBatteryData(params);
216}
217#endif
218
219
220// ----------------------------------------------------------------------------
221// CPU Stats
222// ----------------------------------------------------------------------------
223
224class CpuStats {
225public:
226 CpuStats();
227 void sample(const String8 &title);
228#ifdef DEBUG_CPU_USAGE
229private:
230 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
231 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
232
233 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
234
235 int mCpuNum; // thread's current CPU number
236 int mCpukHz; // frequency of thread's current CPU in kHz
237#endif
238};
239
240CpuStats::CpuStats()
241#ifdef DEBUG_CPU_USAGE
242 : mCpuNum(-1), mCpukHz(-1)
243#endif
244{
245}
246
Glenn Kasten0f11b512014-01-31 16:18:54 -0800247void CpuStats::sample(const String8 &title
248#ifndef DEBUG_CPU_USAGE
249 __unused
250#endif
251 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800252#ifdef DEBUG_CPU_USAGE
253 // get current thread's delta CPU time in wall clock ns
254 double wcNs;
255 bool valid = mCpuUsage.sampleAndEnable(wcNs);
256
257 // record sample for wall clock statistics
258 if (valid) {
259 mWcStats.sample(wcNs);
260 }
261
262 // get the current CPU number
263 int cpuNum = sched_getcpu();
264
265 // get the current CPU frequency in kHz
266 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
267
268 // check if either CPU number or frequency changed
269 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
270 mCpuNum = cpuNum;
271 mCpukHz = cpukHz;
272 // ignore sample for purposes of cycles
273 valid = false;
274 }
275
276 // if no change in CPU number or frequency, then record sample for cycle statistics
277 if (valid && mCpukHz > 0) {
278 double cycles = wcNs * cpukHz * 0.000001;
279 mHzStats.sample(cycles);
280 }
281
282 unsigned n = mWcStats.n();
283 // mCpuUsage.elapsed() is expensive, so don't call it every loop
284 if ((n & 127) == 1) {
285 long long elapsed = mCpuUsage.elapsed();
286 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
287 double perLoop = elapsed / (double) n;
288 double perLoop100 = perLoop * 0.01;
289 double perLoop1k = perLoop * 0.001;
290 double mean = mWcStats.mean();
291 double stddev = mWcStats.stddev();
292 double minimum = mWcStats.minimum();
293 double maximum = mWcStats.maximum();
294 double meanCycles = mHzStats.mean();
295 double stddevCycles = mHzStats.stddev();
296 double minCycles = mHzStats.minimum();
297 double maxCycles = mHzStats.maximum();
298 mCpuUsage.resetElapsed();
299 mWcStats.reset();
300 mHzStats.reset();
301 ALOGD("CPU usage for %s over past %.1f secs\n"
302 " (%u mixer loops at %.1f mean ms per loop):\n"
303 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
304 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
305 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
306 title.string(),
307 elapsed * .000000001, n, perLoop * .000001,
308 mean * .001,
309 stddev * .001,
310 minimum * .001,
311 maximum * .001,
312 mean / perLoop100,
313 stddev / perLoop100,
314 minimum / perLoop100,
315 maximum / perLoop100,
316 meanCycles / perLoop1k,
317 stddevCycles / perLoop1k,
318 minCycles / perLoop1k,
319 maxCycles / perLoop1k);
320
321 }
322 }
323#endif
324};
325
326// ----------------------------------------------------------------------------
327// ThreadBase
328// ----------------------------------------------------------------------------
329
Glenn Kasten97b7b752014-09-28 13:04:24 -0700330// static
331const char *AudioFlinger::ThreadBase::threadTypeToString(AudioFlinger::ThreadBase::type_t type)
332{
333 switch (type) {
334 case MIXER:
335 return "MIXER";
336 case DIRECT:
337 return "DIRECT";
338 case DUPLICATING:
339 return "DUPLICATING";
340 case RECORD:
341 return "RECORD";
342 case OFFLOAD:
343 return "OFFLOAD";
344 default:
345 return "unknown";
346 }
347}
348
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800349String8 devicesToString(audio_devices_t devices)
350{
351 static const struct mapping {
352 audio_devices_t mDevices;
353 const char * mString;
354 } mappingsOut[] = {
355 AUDIO_DEVICE_OUT_EARPIECE, "EARPIECE",
356 AUDIO_DEVICE_OUT_SPEAKER, "SPEAKER",
357 AUDIO_DEVICE_OUT_WIRED_HEADSET, "WIRED_HEADSET",
358 AUDIO_DEVICE_OUT_WIRED_HEADPHONE, "WIRED_HEADPHONE",
Glenn Kasten84d61ca2015-05-06 18:32:13 -0700359 AUDIO_DEVICE_OUT_BLUETOOTH_SCO, "BLUETOOTH_SCO",
360 AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET, "BLUETOOTH_SCO_HEADSET",
361 AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT, "BLUETOOTH_SCO_CARKIT",
362 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, "BLUETOOTH_A2DP",
363 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES, "BLUETOOTH_A2DP_HEADPHONES",
364 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER, "BLUETOOTH_A2DP_SPEAKER",
365 AUDIO_DEVICE_OUT_AUX_DIGITAL, "AUX_DIGITAL",
366 AUDIO_DEVICE_OUT_HDMI, "HDMI",
367 AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET, "ANLG_DOCK_HEADSET",
368 AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET, "DGTL_DOCK_HEADSET",
369 AUDIO_DEVICE_OUT_USB_ACCESSORY, "USB_ACCESSORY",
370 AUDIO_DEVICE_OUT_USB_DEVICE, "USB_DEVICE",
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800371 AUDIO_DEVICE_OUT_TELEPHONY_TX, "TELEPHONY_TX",
Glenn Kasten84d61ca2015-05-06 18:32:13 -0700372 AUDIO_DEVICE_OUT_LINE, "LINE",
373 AUDIO_DEVICE_OUT_HDMI_ARC, "HDMI_ARC",
374 AUDIO_DEVICE_OUT_SPDIF, "SPDIF",
375 AUDIO_DEVICE_OUT_FM, "FM",
376 AUDIO_DEVICE_OUT_AUX_LINE, "AUX_LINE",
377 AUDIO_DEVICE_OUT_SPEAKER_SAFE, "SPEAKER_SAFE",
Eric Laurentb9d73332015-06-30 17:09:20 -0700378 AUDIO_DEVICE_OUT_IP, "IP",
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800379 AUDIO_DEVICE_NONE, "NONE", // must be last
380 }, mappingsIn[] = {
Glenn Kasten84d61ca2015-05-06 18:32:13 -0700381 AUDIO_DEVICE_IN_COMMUNICATION, "COMMUNICATION",
382 AUDIO_DEVICE_IN_AMBIENT, "AMBIENT",
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800383 AUDIO_DEVICE_IN_BUILTIN_MIC, "BUILTIN_MIC",
Glenn Kasten84d61ca2015-05-06 18:32:13 -0700384 AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET, "BLUETOOTH_SCO_HEADSET",
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800385 AUDIO_DEVICE_IN_WIRED_HEADSET, "WIRED_HEADSET",
Glenn Kasten84d61ca2015-05-06 18:32:13 -0700386 AUDIO_DEVICE_IN_AUX_DIGITAL, "AUX_DIGITAL",
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800387 AUDIO_DEVICE_IN_VOICE_CALL, "VOICE_CALL",
Glenn Kasten84d61ca2015-05-06 18:32:13 -0700388 AUDIO_DEVICE_IN_TELEPHONY_RX, "TELEPHONY_RX",
389 AUDIO_DEVICE_IN_BACK_MIC, "BACK_MIC",
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800390 AUDIO_DEVICE_IN_REMOTE_SUBMIX, "REMOTE_SUBMIX",
Glenn Kasten84d61ca2015-05-06 18:32:13 -0700391 AUDIO_DEVICE_IN_ANLG_DOCK_HEADSET, "ANLG_DOCK_HEADSET",
392 AUDIO_DEVICE_IN_DGTL_DOCK_HEADSET, "DGTL_DOCK_HEADSET",
393 AUDIO_DEVICE_IN_USB_ACCESSORY, "USB_ACCESSORY",
394 AUDIO_DEVICE_IN_USB_DEVICE, "USB_DEVICE",
395 AUDIO_DEVICE_IN_FM_TUNER, "FM_TUNER",
396 AUDIO_DEVICE_IN_TV_TUNER, "TV_TUNER",
397 AUDIO_DEVICE_IN_LINE, "LINE",
398 AUDIO_DEVICE_IN_SPDIF, "SPDIF",
399 AUDIO_DEVICE_IN_BLUETOOTH_A2DP, "BLUETOOTH_A2DP",
400 AUDIO_DEVICE_IN_LOOPBACK, "LOOPBACK",
Eric Laurentb9d73332015-06-30 17:09:20 -0700401 AUDIO_DEVICE_IN_IP, "IP",
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800402 AUDIO_DEVICE_NONE, "NONE", // must be last
403 };
404 String8 result;
405 audio_devices_t allDevices = AUDIO_DEVICE_NONE;
406 const mapping *entry;
407 if (devices & AUDIO_DEVICE_BIT_IN) {
408 devices &= ~AUDIO_DEVICE_BIT_IN;
409 entry = mappingsIn;
410 } else {
411 entry = mappingsOut;
412 }
413 for ( ; entry->mDevices != AUDIO_DEVICE_NONE; entry++) {
414 allDevices = (audio_devices_t) (allDevices | entry->mDevices);
415 if (devices & entry->mDevices) {
416 if (!result.isEmpty()) {
417 result.append("|");
418 }
419 result.append(entry->mString);
420 }
421 }
422 if (devices & ~allDevices) {
423 if (!result.isEmpty()) {
424 result.append("|");
425 }
426 result.appendFormat("0x%X", devices & ~allDevices);
427 }
428 if (result.isEmpty()) {
429 result.append(entry->mString);
430 }
431 return result;
432}
433
434String8 inputFlagsToString(audio_input_flags_t flags)
435{
436 static const struct mapping {
437 audio_input_flags_t mFlag;
438 const char * mString;
439 } mappings[] = {
440 AUDIO_INPUT_FLAG_FAST, "FAST",
441 AUDIO_INPUT_FLAG_HW_HOTWORD, "HW_HOTWORD",
442 AUDIO_INPUT_FLAG_NONE, "NONE", // must be last
443 };
444 String8 result;
445 audio_input_flags_t allFlags = AUDIO_INPUT_FLAG_NONE;
446 const mapping *entry;
447 for (entry = mappings; entry->mFlag != AUDIO_INPUT_FLAG_NONE; entry++) {
448 allFlags = (audio_input_flags_t) (allFlags | entry->mFlag);
449 if (flags & entry->mFlag) {
450 if (!result.isEmpty()) {
451 result.append("|");
452 }
453 result.append(entry->mString);
454 }
455 }
456 if (flags & ~allFlags) {
457 if (!result.isEmpty()) {
458 result.append("|");
459 }
460 result.appendFormat("0x%X", flags & ~allFlags);
461 }
462 if (result.isEmpty()) {
463 result.append(entry->mString);
464 }
465 return result;
466}
467
468String8 outputFlagsToString(audio_output_flags_t flags)
Glenn Kasten97b7b752014-09-28 13:04:24 -0700469{
470 static const struct mapping {
471 audio_output_flags_t mFlag;
472 const char * mString;
473 } mappings[] = {
474 AUDIO_OUTPUT_FLAG_DIRECT, "DIRECT",
475 AUDIO_OUTPUT_FLAG_PRIMARY, "PRIMARY",
476 AUDIO_OUTPUT_FLAG_FAST, "FAST",
477 AUDIO_OUTPUT_FLAG_DEEP_BUFFER, "DEEP_BUFFER",
Glenn Kastendfb0e112015-02-18 14:33:39 -0800478 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD, "COMPRESS_OFFLOAD",
Glenn Kasten97b7b752014-09-28 13:04:24 -0700479 AUDIO_OUTPUT_FLAG_NON_BLOCKING, "NON_BLOCKING",
480 AUDIO_OUTPUT_FLAG_HW_AV_SYNC, "HW_AV_SYNC",
481 AUDIO_OUTPUT_FLAG_NONE, "NONE", // must be last
482 };
483 String8 result;
484 audio_output_flags_t allFlags = AUDIO_OUTPUT_FLAG_NONE;
485 const mapping *entry;
486 for (entry = mappings; entry->mFlag != AUDIO_OUTPUT_FLAG_NONE; entry++) {
487 allFlags = (audio_output_flags_t) (allFlags | entry->mFlag);
488 if (flags & entry->mFlag) {
489 if (!result.isEmpty()) {
490 result.append("|");
491 }
492 result.append(entry->mString);
493 }
494 }
495 if (flags & ~allFlags) {
496 if (!result.isEmpty()) {
497 result.append("|");
498 }
499 result.appendFormat("0x%X", flags & ~allFlags);
500 }
501 if (result.isEmpty()) {
502 result.append(entry->mString);
503 }
504 return result;
505}
506
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800507const char *sourceToString(audio_source_t source)
508{
509 switch (source) {
510 case AUDIO_SOURCE_DEFAULT: return "default";
511 case AUDIO_SOURCE_MIC: return "mic";
512 case AUDIO_SOURCE_VOICE_UPLINK: return "voice uplink";
513 case AUDIO_SOURCE_VOICE_DOWNLINK: return "voice downlink";
514 case AUDIO_SOURCE_VOICE_CALL: return "voice call";
515 case AUDIO_SOURCE_CAMCORDER: return "camcorder";
516 case AUDIO_SOURCE_VOICE_RECOGNITION: return "voice recognition";
517 case AUDIO_SOURCE_VOICE_COMMUNICATION: return "voice communication";
518 case AUDIO_SOURCE_REMOTE_SUBMIX: return "remote submix";
519 case AUDIO_SOURCE_FM_TUNER: return "FM tuner";
520 case AUDIO_SOURCE_HOTWORD: return "hotword";
521 default: return "unknown";
522 }
523}
524
Eric Laurent81784c32012-11-19 14:55:58 -0800525AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -0700526 audio_devices_t outDevice, audio_devices_t inDevice, type_t type, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -0800527 : Thread(false /*canCallJava*/),
528 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700529 mAudioFlinger(audioFlinger),
Glenn Kasten70949c42013-08-06 07:40:12 -0700530 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800531 // are set by PlaybackThread::readOutputParameters_l() or
532 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700533 //FIXME: mStandby should be true here. Is this some kind of hack?
Eric Laurent81784c32012-11-19 14:55:58 -0800534 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700535 mPrevOutDevice(AUDIO_DEVICE_NONE), mPrevInDevice(AUDIO_DEVICE_NONE),
536 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Eric Laurent81784c32012-11-19 14:55:58 -0800537 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700538 mDeathRecipient(new PMDeathRecipient(this)),
539 mSystemReady(systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -0800540{
Eric Laurent296fb132015-05-01 11:38:42 -0700541 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800542}
543
544AudioFlinger::ThreadBase::~ThreadBase()
545{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700546 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700547 mConfigEvents.clear();
548
Eric Laurent81784c32012-11-19 14:55:58 -0800549 // do not lock the mutex in destructor
550 releaseWakeLock_l();
551 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800552 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800553 binder->unlinkToDeath(mDeathRecipient);
554 }
555}
556
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700557status_t AudioFlinger::ThreadBase::readyToRun()
558{
559 status_t status = initCheck();
560 if (status == NO_ERROR) {
561 ALOGI("AudioFlinger's thread %p ready to run", this);
562 } else {
563 ALOGE("No working audio driver found.");
564 }
565 return status;
566}
567
Eric Laurent81784c32012-11-19 14:55:58 -0800568void AudioFlinger::ThreadBase::exit()
569{
570 ALOGV("ThreadBase::exit");
571 // do any cleanup required for exit to succeed
572 preExit();
573 {
574 // This lock prevents the following race in thread (uniprocessor for illustration):
575 // if (!exitPending()) {
576 // // context switch from here to exit()
577 // // exit() calls requestExit(), what exitPending() observes
578 // // exit() calls signal(), which is dropped since no waiters
579 // // context switch back from exit() to here
580 // mWaitWorkCV.wait(...);
581 // // now thread is hung
582 // }
583 AutoMutex lock(mLock);
584 requestExit();
585 mWaitWorkCV.broadcast();
586 }
587 // When Thread::requestExitAndWait is made virtual and this method is renamed to
588 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
589 requestExitAndWait();
590}
591
592status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
593{
594 status_t status;
595
596 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
597 Mutex::Autolock _l(mLock);
598
Eric Laurent10351942014-05-08 18:49:52 -0700599 return sendSetParameterConfigEvent_l(keyValuePairs);
600}
601
602// sendConfigEvent_l() must be called with ThreadBase::mLock held
603// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
604status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
605{
606 status_t status = NO_ERROR;
607
Eric Laurent72e3f392015-05-20 14:43:50 -0700608 if (event->mRequiresSystemReady && !mSystemReady) {
609 event->mWaitStatus = false;
610 mPendingConfigEvents.add(event);
611 return status;
612 }
Eric Laurent10351942014-05-08 18:49:52 -0700613 mConfigEvents.add(event);
614 ALOGV("sendConfigEvent_l() num events %d event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800615 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700616 mLock.unlock();
617 {
618 Mutex::Autolock _l(event->mLock);
619 while (event->mWaitStatus) {
620 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
621 event->mStatus = TIMED_OUT;
622 event->mWaitStatus = false;
623 }
624 }
625 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800626 }
Eric Laurent10351942014-05-08 18:49:52 -0700627 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800628 return status;
629}
630
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700631void AudioFlinger::ThreadBase::sendIoConfigEvent(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800632{
633 Mutex::Autolock _l(mLock);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700634 sendIoConfigEvent_l(event, pid);
Eric Laurent81784c32012-11-19 14:55:58 -0800635}
636
637// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700638void AudioFlinger::ThreadBase::sendIoConfigEvent_l(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800639{
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700640 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid);
Eric Laurent10351942014-05-08 18:49:52 -0700641 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800642}
643
Eric Laurent72e3f392015-05-20 14:43:50 -0700644void AudioFlinger::ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio)
645{
646 Mutex::Autolock _l(mLock);
647 sendPrioConfigEvent_l(pid, tid, prio);
648}
649
Eric Laurent81784c32012-11-19 14:55:58 -0800650// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
651void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
652{
Eric Laurent10351942014-05-08 18:49:52 -0700653 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio);
654 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800655}
656
Eric Laurent10351942014-05-08 18:49:52 -0700657// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
658status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800659{
Eric Laurent10351942014-05-08 18:49:52 -0700660 sp<ConfigEvent> configEvent = (ConfigEvent *)new SetParameterConfigEvent(keyValuePair);
661 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700662}
663
Eric Laurent1c333e22014-05-20 10:48:17 -0700664status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
665 const struct audio_patch *patch,
666 audio_patch_handle_t *handle)
667{
668 Mutex::Autolock _l(mLock);
669 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
670 status_t status = sendConfigEvent_l(configEvent);
671 if (status == NO_ERROR) {
672 CreateAudioPatchConfigEventData *data =
673 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
674 *handle = data->mHandle;
675 }
676 return status;
677}
678
679status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
680 const audio_patch_handle_t handle)
681{
682 Mutex::Autolock _l(mLock);
683 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
684 return sendConfigEvent_l(configEvent);
685}
686
687
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700688// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700689void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700690{
Eric Laurent10351942014-05-08 18:49:52 -0700691 bool configChanged = false;
692
Eric Laurent81784c32012-11-19 14:55:58 -0800693 while (!mConfigEvents.isEmpty()) {
Eric Laurent10351942014-05-08 18:49:52 -0700694 ALOGV("processConfigEvents_l() remaining events %d", mConfigEvents.size());
695 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800696 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700697 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700698 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700699 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
700 // FIXME Need to understand why this has to be done asynchronously
701 int err = requestPriority(data->mPid, data->mTid, data->mPrio,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700702 true /*asynchronous*/);
703 if (err != 0) {
704 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700705 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700706 }
707 } break;
708 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700709 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700710 ioConfigChanged(data->mEvent, data->mPid);
Eric Laurent10351942014-05-08 18:49:52 -0700711 } break;
712 case CFG_EVENT_SET_PARAMETER: {
713 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
714 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
715 configChanged = true;
Glenn Kastend5418eb2013-08-14 13:11:06 -0700716 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700717 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700718 case CFG_EVENT_CREATE_AUDIO_PATCH: {
719 CreateAudioPatchConfigEventData *data =
720 (CreateAudioPatchConfigEventData *)event->mData.get();
721 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
722 } break;
723 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
724 ReleaseAudioPatchConfigEventData *data =
725 (ReleaseAudioPatchConfigEventData *)event->mData.get();
726 event->mStatus = releaseAudioPatch_l(data->mHandle);
727 } break;
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700728 default:
Eric Laurent10351942014-05-08 18:49:52 -0700729 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700730 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800731 }
Eric Laurent10351942014-05-08 18:49:52 -0700732 {
733 Mutex::Autolock _l(event->mLock);
734 if (event->mWaitStatus) {
735 event->mWaitStatus = false;
736 event->mCond.signal();
737 }
738 }
739 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
740 }
741
742 if (configChanged) {
743 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800744 }
Eric Laurent81784c32012-11-19 14:55:58 -0800745}
746
Marco Nelissenb2208842014-02-07 14:00:50 -0800747String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
748 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700749 const audio_channel_representation_t representation =
750 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700751
752 switch (representation) {
753 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
754 if (output) {
755 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
756 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
757 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
758 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
759 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
760 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
761 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
762 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
763 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
764 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
765 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
766 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
767 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
768 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
769 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
770 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
771 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
772 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
773 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
774 } else {
775 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
776 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
777 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
778 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
779 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
780 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
781 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
782 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
783 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
784 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
785 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
786 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
787 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
788 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
789 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
790 }
791 const int len = s.length();
792 if (len > 2) {
793 char *str = s.lockBuffer(len); // needed?
794 s.unlockBuffer(len - 2); // remove trailing ", "
795 }
796 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800797 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700798 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
799 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
800 return s;
801 default:
802 s.appendFormat("unknown mask, representation:%d bits:%#x",
803 representation, audio_channel_mask_get_bits(mask));
804 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800805 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800806}
807
Glenn Kasten0f11b512014-01-31 16:18:54 -0800808void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800809{
810 const size_t SIZE = 256;
811 char buffer[SIZE];
812 String8 result;
813
814 bool locked = AudioFlinger::dumpTryLock(mLock);
815 if (!locked) {
Glenn Kasten97b7b752014-09-28 13:04:24 -0700816 dprintf(fd, "thread %p may be deadlocked\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -0800817 }
818
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800819 dprintf(fd, " Thread name: %s\n", mThreadName);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700820 dprintf(fd, " I/O handle: %d\n", mId);
821 dprintf(fd, " TID: %d\n", getTid());
822 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700823 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700824 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700825 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat));
Elliott Hughes87cebad2014-05-22 10:14:43 -0700826 dprintf(fd, " HAL buffer size: %u bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700827 dprintf(fd, " Channel count: %u\n", mChannelCount);
828 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800829 channelMaskToString(mChannelMask, mType != RECORD).string());
Glenn Kasten97b7b752014-09-28 13:04:24 -0700830 dprintf(fd, " Format: 0x%x (%s)\n", mFormat, formatToString(mFormat));
831 dprintf(fd, " Frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700832 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800833 size_t numConfig = mConfigEvents.size();
834 if (numConfig) {
835 for (size_t i = 0; i < numConfig; i++) {
836 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700837 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800838 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700839 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800840 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700841 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800842 }
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800843 dprintf(fd, " Output device: %#x (%s)\n", mOutDevice, devicesToString(mOutDevice).string());
844 dprintf(fd, " Input device: %#x (%s)\n", mInDevice, devicesToString(mInDevice).string());
845 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, sourceToString(mAudioSource));
Eric Laurent81784c32012-11-19 14:55:58 -0800846
847 if (locked) {
848 mLock.unlock();
849 }
850}
851
852void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
853{
854 const size_t SIZE = 256;
855 char buffer[SIZE];
856 String8 result;
857
Marco Nelissenb2208842014-02-07 14:00:50 -0800858 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000859 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800860 write(fd, buffer, strlen(buffer));
861
Marco Nelissenb2208842014-02-07 14:00:50 -0800862 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800863 sp<EffectChain> chain = mEffectChains[i];
864 if (chain != 0) {
865 chain->dump(fd, args);
866 }
867 }
868}
869
Marco Nelissene14a5d62013-10-03 08:51:24 -0700870void AudioFlinger::ThreadBase::acquireWakeLock(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800871{
872 Mutex::Autolock _l(mLock);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700873 acquireWakeLock_l(uid);
Eric Laurent81784c32012-11-19 14:55:58 -0800874}
875
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100876String16 AudioFlinger::ThreadBase::getWakeLockTag()
877{
878 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -0800879 case MIXER:
880 return String16("AudioMix");
881 case DIRECT:
882 return String16("AudioDirectOut");
883 case DUPLICATING:
884 return String16("AudioDup");
885 case RECORD:
886 return String16("AudioIn");
887 case OFFLOAD:
888 return String16("AudioOffload");
889 default:
890 ALOG_ASSERT(false);
891 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100892 }
893}
894
Marco Nelissene14a5d62013-10-03 08:51:24 -0700895void AudioFlinger::ThreadBase::acquireWakeLock_l(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800896{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800897 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800898 if (mPowerManager != 0) {
899 sp<IBinder> binder = new BBinder();
Marco Nelissene14a5d62013-10-03 08:51:24 -0700900 status_t status;
901 if (uid >= 0) {
Eric Laurent547789d2013-10-04 11:46:55 -0700902 status = mPowerManager->acquireWakeLockWithUid(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700903 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100904 getWakeLockTag(),
Marco Nelissene14a5d62013-10-03 08:51:24 -0700905 String16("media"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700906 uid,
907 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700908 } else {
Eric Laurent547789d2013-10-04 11:46:55 -0700909 status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700910 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100911 getWakeLockTag(),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700912 String16("media"),
913 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700914 }
Eric Laurent81784c32012-11-19 14:55:58 -0800915 if (status == NO_ERROR) {
916 mWakeLockToken = binder;
917 }
Glenn Kastend7dca052015-03-05 16:05:54 -0800918 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Eric Laurent81784c32012-11-19 14:55:58 -0800919 }
920}
921
922void AudioFlinger::ThreadBase::releaseWakeLock()
923{
924 Mutex::Autolock _l(mLock);
925 releaseWakeLock_l();
926}
927
928void AudioFlinger::ThreadBase::releaseWakeLock_l()
929{
930 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800931 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -0800932 if (mPowerManager != 0) {
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700933 mPowerManager->releaseWakeLock(mWakeLockToken, 0,
934 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800935 }
936 mWakeLockToken.clear();
937 }
938}
939
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800940void AudioFlinger::ThreadBase::updateWakeLockUids(const SortedVector<int> &uids) {
941 Mutex::Autolock _l(mLock);
942 updateWakeLockUids_l(uids);
943}
944
945void AudioFlinger::ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -0700946 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800947 // use checkService() to avoid blocking if power service is not up yet
948 sp<IBinder> binder =
949 defaultServiceManager()->checkService(String16("power"));
950 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800951 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800952 } else {
953 mPowerManager = interface_cast<IPowerManager>(binder);
954 binder->linkToDeath(mDeathRecipient);
955 }
956 }
957}
958
959void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<int> &uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800960 getPowerManager_l();
961 if (mWakeLockToken == NULL) {
962 ALOGE("no wake lock to update!");
963 return;
964 }
965 if (mPowerManager != 0) {
966 sp<IBinder> binder = new BBinder();
967 status_t status;
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700968 status = mPowerManager->updateWakeLockUids(mWakeLockToken, uids.size(), uids.array(),
969 true /* FIXME force oneway contrary to .aidl */);
Glenn Kastend7dca052015-03-05 16:05:54 -0800970 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800971 }
972}
973
Eric Laurent81784c32012-11-19 14:55:58 -0800974void AudioFlinger::ThreadBase::clearPowerManager()
975{
976 Mutex::Autolock _l(mLock);
977 releaseWakeLock_l();
978 mPowerManager.clear();
979}
980
Glenn Kasten0f11b512014-01-31 16:18:54 -0800981void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800982{
983 sp<ThreadBase> thread = mThread.promote();
984 if (thread != 0) {
985 thread->clearPowerManager();
986 }
987 ALOGW("power manager service died !!!");
988}
989
990void AudioFlinger::ThreadBase::setEffectSuspended(
991 const effect_uuid_t *type, bool suspend, int sessionId)
992{
993 Mutex::Autolock _l(mLock);
994 setEffectSuspended_l(type, suspend, sessionId);
995}
996
997void AudioFlinger::ThreadBase::setEffectSuspended_l(
998 const effect_uuid_t *type, bool suspend, int sessionId)
999{
1000 sp<EffectChain> chain = getEffectChain_l(sessionId);
1001 if (chain != 0) {
1002 if (type != NULL) {
1003 chain->setEffectSuspended_l(type, suspend);
1004 } else {
1005 chain->setEffectSuspendedAll_l(suspend);
1006 }
1007 }
1008
1009 updateSuspendedSessions_l(type, suspend, sessionId);
1010}
1011
1012void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1013{
1014 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1015 if (index < 0) {
1016 return;
1017 }
1018
1019 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1020 mSuspendedSessions.valueAt(index);
1021
1022 for (size_t i = 0; i < sessionEffects.size(); i++) {
1023 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
1024 for (int j = 0; j < desc->mRefCount; j++) {
1025 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1026 chain->setEffectSuspendedAll_l(true);
1027 } else {
1028 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1029 desc->mType.timeLow);
1030 chain->setEffectSuspended_l(&desc->mType, true);
1031 }
1032 }
1033 }
1034}
1035
1036void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1037 bool suspend,
1038 int sessionId)
1039{
1040 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1041
1042 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1043
1044 if (suspend) {
1045 if (index >= 0) {
1046 sessionEffects = mSuspendedSessions.valueAt(index);
1047 } else {
1048 mSuspendedSessions.add(sessionId, sessionEffects);
1049 }
1050 } else {
1051 if (index < 0) {
1052 return;
1053 }
1054 sessionEffects = mSuspendedSessions.valueAt(index);
1055 }
1056
1057
1058 int key = EffectChain::kKeyForSuspendAll;
1059 if (type != NULL) {
1060 key = type->timeLow;
1061 }
1062 index = sessionEffects.indexOfKey(key);
1063
1064 sp<SuspendedSessionDesc> desc;
1065 if (suspend) {
1066 if (index >= 0) {
1067 desc = sessionEffects.valueAt(index);
1068 } else {
1069 desc = new SuspendedSessionDesc();
1070 if (type != NULL) {
1071 desc->mType = *type;
1072 }
1073 sessionEffects.add(key, desc);
1074 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1075 }
1076 desc->mRefCount++;
1077 } else {
1078 if (index < 0) {
1079 return;
1080 }
1081 desc = sessionEffects.valueAt(index);
1082 if (--desc->mRefCount == 0) {
1083 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1084 sessionEffects.removeItemsAt(index);
1085 if (sessionEffects.isEmpty()) {
1086 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1087 sessionId);
1088 mSuspendedSessions.removeItem(sessionId);
1089 }
1090 }
1091 }
1092 if (!sessionEffects.isEmpty()) {
1093 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1094 }
1095}
1096
1097void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1098 bool enabled,
1099 int sessionId)
1100{
1101 Mutex::Autolock _l(mLock);
1102 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1103}
1104
1105void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1106 bool enabled,
1107 int sessionId)
1108{
1109 if (mType != RECORD) {
1110 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1111 // another session. This gives the priority to well behaved effect control panels
1112 // and applications not using global effects.
1113 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1114 // global effects
1115 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
1116 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1117 }
1118 }
1119
1120 sp<EffectChain> chain = getEffectChain_l(sessionId);
1121 if (chain != 0) {
1122 chain->checkSuspendOnEffectEnabled(effect, enabled);
1123 }
1124}
1125
1126// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1127sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1128 const sp<AudioFlinger::Client>& client,
1129 const sp<IEffectClient>& effectClient,
1130 int32_t priority,
1131 int sessionId,
1132 effect_descriptor_t *desc,
1133 int *enabled,
Glenn Kasten9156ef32013-08-06 15:39:08 -07001134 status_t *status)
Eric Laurent81784c32012-11-19 14:55:58 -08001135{
1136 sp<EffectModule> effect;
1137 sp<EffectHandle> handle;
1138 status_t lStatus;
1139 sp<EffectChain> chain;
1140 bool chainCreated = false;
1141 bool effectCreated = false;
1142 bool effectRegistered = false;
1143
1144 lStatus = initCheck();
1145 if (lStatus != NO_ERROR) {
1146 ALOGW("createEffect_l() Audio driver not initialized.");
1147 goto Exit;
1148 }
1149
Andy Hung98ef9782014-03-04 14:46:50 -08001150 // Reject any effect on Direct output threads for now, since the format of
1151 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1152 if (mType == DIRECT) {
1153 ALOGW("createEffect_l() Cannot add effect %s on Direct output type thread %s",
Glenn Kastend7dca052015-03-05 16:05:54 -08001154 desc->name, mThreadName);
Andy Hung98ef9782014-03-04 14:46:50 -08001155 lStatus = BAD_VALUE;
1156 goto Exit;
1157 }
1158
Andy Hung389cfdb2014-08-07 17:49:53 -07001159 // Reject any effect on mixer or duplicating multichannel sinks.
Andy Hung9a592762014-07-21 21:56:01 -07001160 // TODO: fix both format and multichannel issues with effects.
Andy Hung389cfdb2014-08-07 17:49:53 -07001161 if ((mType == MIXER || mType == DUPLICATING) && mChannelCount != FCC_2) {
1162 ALOGW("createEffect_l() Cannot add effect %s for multichannel(%d) %s threads",
1163 desc->name, mChannelCount, mType == MIXER ? "MIXER" : "DUPLICATING");
Andy Hung9a592762014-07-21 21:56:01 -07001164 lStatus = BAD_VALUE;
1165 goto Exit;
1166 }
1167
Eric Laurent5baf2af2013-09-12 17:37:00 -07001168 // Allow global effects only on offloaded and mixer threads
1169 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1170 switch (mType) {
1171 case MIXER:
1172 case OFFLOAD:
1173 break;
1174 case DIRECT:
1175 case DUPLICATING:
1176 case RECORD:
1177 default:
Glenn Kastend7dca052015-03-05 16:05:54 -08001178 ALOGW("createEffect_l() Cannot add global effect %s on thread %s",
1179 desc->name, mThreadName);
Eric Laurent5baf2af2013-09-12 17:37:00 -07001180 lStatus = BAD_VALUE;
1181 goto Exit;
1182 }
Eric Laurent81784c32012-11-19 14:55:58 -08001183 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07001184
Eric Laurent81784c32012-11-19 14:55:58 -08001185 // Only Pre processor effects are allowed on input threads and only on input threads
1186 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
1187 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
1188 desc->name, desc->flags, mType);
1189 lStatus = BAD_VALUE;
1190 goto Exit;
1191 }
1192
1193 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1194
1195 { // scope for mLock
1196 Mutex::Autolock _l(mLock);
1197
1198 // check for existing effect chain with the requested audio session
1199 chain = getEffectChain_l(sessionId);
1200 if (chain == 0) {
1201 // create a new chain for this session
1202 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1203 chain = new EffectChain(this, sessionId);
1204 addEffectChain_l(chain);
1205 chain->setStrategy(getStrategyForSession_l(sessionId));
1206 chainCreated = true;
1207 } else {
1208 effect = chain->getEffectFromDesc_l(desc);
1209 }
1210
1211 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1212
1213 if (effect == 0) {
1214 int id = mAudioFlinger->nextUniqueId();
1215 // Check CPU and memory usage
1216 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
1217 if (lStatus != NO_ERROR) {
1218 goto Exit;
1219 }
1220 effectRegistered = true;
1221 // create a new effect module if none present in the chain
1222 effect = new EffectModule(this, chain, desc, id, sessionId);
1223 lStatus = effect->status();
1224 if (lStatus != NO_ERROR) {
1225 goto Exit;
1226 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07001227 effect->setOffloaded(mType == OFFLOAD, mId);
1228
Eric Laurent81784c32012-11-19 14:55:58 -08001229 lStatus = chain->addEffect_l(effect);
1230 if (lStatus != NO_ERROR) {
1231 goto Exit;
1232 }
1233 effectCreated = true;
1234
1235 effect->setDevice(mOutDevice);
1236 effect->setDevice(mInDevice);
1237 effect->setMode(mAudioFlinger->getMode());
1238 effect->setAudioSource(mAudioSource);
1239 }
1240 // create effect handle and connect it to effect module
1241 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001242 lStatus = handle->initCheck();
1243 if (lStatus == OK) {
1244 lStatus = effect->addHandle(handle.get());
1245 }
Eric Laurent81784c32012-11-19 14:55:58 -08001246 if (enabled != NULL) {
1247 *enabled = (int)effect->isEnabled();
1248 }
1249 }
1250
1251Exit:
1252 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1253 Mutex::Autolock _l(mLock);
1254 if (effectCreated) {
1255 chain->removeEffect_l(effect);
1256 }
1257 if (effectRegistered) {
1258 AudioSystem::unregisterEffect(effect->id());
1259 }
1260 if (chainCreated) {
1261 removeEffectChain_l(chain);
1262 }
1263 handle.clear();
1264 }
1265
Glenn Kasten9156ef32013-08-06 15:39:08 -07001266 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001267 return handle;
1268}
1269
1270sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
1271{
1272 Mutex::Autolock _l(mLock);
1273 return getEffect_l(sessionId, effectId);
1274}
1275
1276sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
1277{
1278 sp<EffectChain> chain = getEffectChain_l(sessionId);
1279 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1280}
1281
1282// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1283// PlaybackThread::mLock held
1284status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1285{
1286 // check for existing effect chain with the requested audio session
1287 int sessionId = effect->sessionId();
1288 sp<EffectChain> chain = getEffectChain_l(sessionId);
1289 bool chainCreated = false;
1290
Eric Laurent5baf2af2013-09-12 17:37:00 -07001291 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
1292 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
1293 this, effect->desc().name, effect->desc().flags);
1294
Eric Laurent81784c32012-11-19 14:55:58 -08001295 if (chain == 0) {
1296 // create a new chain for this session
1297 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1298 chain = new EffectChain(this, sessionId);
1299 addEffectChain_l(chain);
1300 chain->setStrategy(getStrategyForSession_l(sessionId));
1301 chainCreated = true;
1302 }
1303 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1304
1305 if (chain->getEffectFromId_l(effect->id()) != 0) {
1306 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1307 this, effect->desc().name, chain.get());
1308 return BAD_VALUE;
1309 }
1310
Eric Laurent5baf2af2013-09-12 17:37:00 -07001311 effect->setOffloaded(mType == OFFLOAD, mId);
1312
Eric Laurent81784c32012-11-19 14:55:58 -08001313 status_t status = chain->addEffect_l(effect);
1314 if (status != NO_ERROR) {
1315 if (chainCreated) {
1316 removeEffectChain_l(chain);
1317 }
1318 return status;
1319 }
1320
1321 effect->setDevice(mOutDevice);
1322 effect->setDevice(mInDevice);
1323 effect->setMode(mAudioFlinger->getMode());
1324 effect->setAudioSource(mAudioSource);
1325 return NO_ERROR;
1326}
1327
1328void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
1329
1330 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
1331 effect_descriptor_t desc = effect->desc();
1332 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1333 detachAuxEffect_l(effect->id());
1334 }
1335
1336 sp<EffectChain> chain = effect->chain().promote();
1337 if (chain != 0) {
1338 // remove effect chain if removing last effect
1339 if (chain->removeEffect_l(effect) == 0) {
1340 removeEffectChain_l(chain);
1341 }
1342 } else {
1343 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1344 }
1345}
1346
1347void AudioFlinger::ThreadBase::lockEffectChains_l(
1348 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1349{
1350 effectChains = mEffectChains;
1351 for (size_t i = 0; i < mEffectChains.size(); i++) {
1352 mEffectChains[i]->lock();
1353 }
1354}
1355
1356void AudioFlinger::ThreadBase::unlockEffectChains(
1357 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1358{
1359 for (size_t i = 0; i < effectChains.size(); i++) {
1360 effectChains[i]->unlock();
1361 }
1362}
1363
1364sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
1365{
1366 Mutex::Autolock _l(mLock);
1367 return getEffectChain_l(sessionId);
1368}
1369
1370sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const
1371{
1372 size_t size = mEffectChains.size();
1373 for (size_t i = 0; i < size; i++) {
1374 if (mEffectChains[i]->sessionId() == sessionId) {
1375 return mEffectChains[i];
1376 }
1377 }
1378 return 0;
1379}
1380
1381void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1382{
1383 Mutex::Autolock _l(mLock);
1384 size_t size = mEffectChains.size();
1385 for (size_t i = 0; i < size; i++) {
1386 mEffectChains[i]->setMode_l(mode);
1387 }
1388}
1389
Eric Laurent83b88082014-06-20 18:31:16 -07001390void AudioFlinger::ThreadBase::getAudioPortConfig(struct audio_port_config *config)
1391{
1392 config->type = AUDIO_PORT_TYPE_MIX;
1393 config->ext.mix.handle = mId;
1394 config->sample_rate = mSampleRate;
1395 config->format = mFormat;
1396 config->channel_mask = mChannelMask;
1397 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1398 AUDIO_PORT_CONFIG_FORMAT;
1399}
1400
Eric Laurent72e3f392015-05-20 14:43:50 -07001401void AudioFlinger::ThreadBase::systemReady()
1402{
1403 Mutex::Autolock _l(mLock);
1404 if (mSystemReady) {
1405 return;
1406 }
1407 mSystemReady = true;
1408
1409 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1410 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1411 }
1412 mPendingConfigEvents.clear();
1413}
1414
Eric Laurent83b88082014-06-20 18:31:16 -07001415
Eric Laurent81784c32012-11-19 14:55:58 -08001416// ----------------------------------------------------------------------------
1417// Playback
1418// ----------------------------------------------------------------------------
1419
1420AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1421 AudioStreamOut* output,
1422 audio_io_handle_t id,
1423 audio_devices_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07001424 type_t type,
1425 bool systemReady)
1426 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type, systemReady),
Andy Hung2098f272014-02-27 14:00:06 -08001427 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001428 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001429 mMixerBuffer(NULL),
1430 mMixerBufferSize(0),
1431 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1432 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001433 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001434 mEffectBuffer(NULL),
1435 mEffectBufferSize(0),
1436 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1437 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001438 mSuspended(0), mBytesWritten(0),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001439 mActiveTracksGeneration(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001440 // mStreamTypes[] initialized in constructor body
1441 mOutput(output),
1442 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
1443 mMixerStatus(MIXER_IDLE),
1444 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001445 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001446 mBytesRemaining(0),
1447 mCurrentWriteLength(0),
1448 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001449 mWriteAckSequence(0),
1450 mDrainSequence(0),
Eric Laurentede6c3b2013-09-19 14:37:46 -07001451 mSignalPending(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001452 mScreenState(AudioFlinger::mScreenState),
1453 // index 0 is reserved for normal mixer's submix
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001454 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1),
Eric Laurentd1f69b02014-12-15 14:33:13 -08001455 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001456 // mLatchD, mLatchQ,
1457 mLatchDValid(false), mLatchQValid(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001458{
Glenn Kastend7dca052015-03-05 16:05:54 -08001459 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1460 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001461
1462 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1463 // it would be safer to explicitly pass initial masterVolume/masterMute as
1464 // parameter.
1465 //
1466 // If the HAL we are using has support for master volume or master mute,
1467 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1468 // and the mute set to false).
1469 mMasterVolume = audioFlinger->masterVolume_l();
1470 mMasterMute = audioFlinger->masterMute_l();
1471 if (mOutput && mOutput->audioHwDev) {
1472 if (mOutput->audioHwDev->canSetMasterVolume()) {
1473 mMasterVolume = 1.0;
1474 }
1475
1476 if (mOutput->audioHwDev->canSetMasterMute()) {
1477 mMasterMute = false;
1478 }
1479 }
1480
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001481 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001482
Eric Laurent223fd5c2014-11-11 13:43:36 -08001483 // ++ operator does not compile
Glenn Kasten66e46352014-01-16 17:44:23 -08001484 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001485 stream = (audio_stream_type_t) (stream + 1)) {
1486 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1487 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1488 }
Eric Laurent81784c32012-11-19 14:55:58 -08001489}
1490
1491AudioFlinger::PlaybackThread::~PlaybackThread()
1492{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001493 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001494 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001495 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001496 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001497}
1498
1499void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1500{
1501 dumpInternals(fd, args);
1502 dumpTracks(fd, args);
1503 dumpEffectChains(fd, args);
1504}
1505
Glenn Kasten0f11b512014-01-31 16:18:54 -08001506void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001507{
1508 const size_t SIZE = 256;
1509 char buffer[SIZE];
1510 String8 result;
1511
Marco Nelissenb2208842014-02-07 14:00:50 -08001512 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001513 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1514 const stream_type_t *st = &mStreamTypes[i];
1515 if (i > 0) {
1516 result.appendFormat(", ");
1517 }
1518 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1519 if (st->mute) {
1520 result.append("M");
1521 }
1522 }
1523 result.append("\n");
1524 write(fd, result.string(), result.length());
1525 result.clear();
1526
Eric Laurent81784c32012-11-19 14:55:58 -08001527 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1528 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001529 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001530 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001531
1532 size_t numtracks = mTracks.size();
1533 size_t numactive = mActiveTracks.size();
Elliott Hughes87cebad2014-05-22 10:14:43 -07001534 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001535 size_t numactiveseen = 0;
1536 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07001537 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08001538 Track::appendDumpHeader(result);
1539 for (size_t i = 0; i < numtracks; ++i) {
1540 sp<Track> track = mTracks[i];
1541 if (track != 0) {
1542 bool active = mActiveTracks.indexOf(track) >= 0;
1543 if (active) {
1544 numactiveseen++;
1545 }
1546 track->dump(buffer, SIZE, active);
1547 result.append(buffer);
1548 }
1549 }
1550 } else {
1551 result.append("\n");
1552 }
1553 if (numactiveseen != numactive) {
1554 // some tracks in the active list were not in the tracks list
1555 snprintf(buffer, SIZE, " The following tracks are in the active list but"
1556 " not in the track list\n");
1557 result.append(buffer);
1558 Track::appendDumpHeader(result);
1559 for (size_t i = 0; i < numactive; ++i) {
1560 sp<Track> track = mActiveTracks[i].promote();
1561 if (track != 0 && mTracks.indexOf(track) < 0) {
1562 track->dump(buffer, SIZE, true);
1563 result.append(buffer);
1564 }
1565 }
1566 }
1567
1568 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001569}
1570
1571void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1572{
Glenn Kasten97b7b752014-09-28 13:04:24 -07001573 dprintf(fd, "\nOutput thread %p type %d (%s):\n", this, type(), threadTypeToString(type()));
Glenn Kasten44182c22015-03-05 17:12:23 -08001574
1575 dumpBase(fd, args);
1576
Elliott Hughes87cebad2014-05-22 10:14:43 -07001577 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
1578 dprintf(fd, " Last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1579 dprintf(fd, " Total writes: %d\n", mNumWrites);
1580 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1581 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1582 dprintf(fd, " Suspend count: %d\n", mSuspended);
1583 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1584 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1585 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1586 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001587 AudioStreamOut *output = mOutput;
1588 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
1589 String8 flagsAsString = outputFlagsToString(flags);
1590 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n", output, flags, flagsAsString.string());
Eric Laurent81784c32012-11-19 14:55:58 -08001591}
1592
1593// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001594
1595void AudioFlinger::PlaybackThread::onFirstRef()
1596{
Glenn Kastend7dca052015-03-05 16:05:54 -08001597 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001598}
1599
1600// ThreadBase virtuals
1601void AudioFlinger::PlaybackThread::preExit()
1602{
1603 ALOGV(" preExit()");
1604 // FIXME this is using hard-coded strings but in the future, this functionality will be
1605 // converted to use audio HAL extensions required to support tunneling
1606 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1607}
1608
1609// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1610sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1611 const sp<AudioFlinger::Client>& client,
1612 audio_stream_type_t streamType,
1613 uint32_t sampleRate,
1614 audio_format_t format,
1615 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001616 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001617 const sp<IMemory>& sharedBuffer,
1618 int sessionId,
1619 IAudioFlinger::track_flags_t *flags,
1620 pid_t tid,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001621 int uid,
Eric Laurent81784c32012-11-19 14:55:58 -08001622 status_t *status)
1623{
Glenn Kasten74935e42013-12-19 08:56:45 -08001624 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001625 sp<Track> track;
1626 status_t lStatus;
1627
1628 bool isTimed = (*flags & IAudioFlinger::TRACK_TIMED) != 0;
1629
1630 // client expresses a preference for FAST, but we get the final say
1631 if (*flags & IAudioFlinger::TRACK_FAST) {
1632 if (
1633 // not timed
1634 (!isTimed) &&
1635 // either of these use cases:
1636 (
1637 // use case 1: shared buffer with any frame count
1638 (
1639 (sharedBuffer != 0)
1640 ) ||
Glenn Kasten1dfe2f92015-03-09 12:03:14 -07001641 // use case 2: frame count is default or at least as large as HAL
Eric Laurent81784c32012-11-19 14:55:58 -08001642 (
Glenn Kasten1dfe2f92015-03-09 12:03:14 -07001643 // we formerly checked for a callback handler (non-0 tid),
1644 // but that is no longer required for TRANSFER_OBTAIN mode
Eric Laurent81784c32012-11-19 14:55:58 -08001645 ((frameCount == 0) ||
Glenn Kastenb5fed682013-12-03 09:06:43 -08001646 (frameCount >= mFrameCount))
Eric Laurent81784c32012-11-19 14:55:58 -08001647 )
1648 ) &&
1649 // PCM data
1650 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07001651 // TODO: extract as a data library function that checks that a computationally
1652 // expensive downmixer is not required: isFastOutputChannelConversion()
Andy Hung9a592762014-07-21 21:56:01 -07001653 (channelMask == mChannelMask ||
Andy Hung1f439e12015-05-19 12:57:41 -07001654 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
1655 (channelMask == AUDIO_CHANNEL_OUT_MONO
1656 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001657 // hardware sample rate
1658 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001659 // normal mixer has an associated fast mixer
1660 hasFastMixer() &&
1661 // there are sufficient fast track slots available
1662 (mFastTrackAvailMask != 0)
1663 // FIXME test that MixerThread for this fast track has a capable output HAL
1664 // FIXME add a permission test also?
1665 ) {
1666 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1667 if (frameCount == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001668 // read the fast track multiplier property the first time it is needed
1669 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1670 if (ok != 0) {
1671 ALOGE("%s pthread_once failed: %d", __func__, ok);
1672 }
1673 frameCount = mFrameCount * sFastTrackMultiplier;
Eric Laurent81784c32012-11-19 14:55:58 -08001674 }
1675 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
1676 frameCount, mFrameCount);
1677 } else {
1678 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
Andy Hung6146c082014-03-18 11:56:15 -07001679 "mFrameCount=%d format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
1680 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001681 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Andy Hung6146c082014-03-18 11:56:15 -07001682 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001683 audio_is_linear_pcm(format),
1684 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
1685 *flags &= ~IAudioFlinger::TRACK_FAST;
Andy Hung0e48d252015-01-26 11:43:15 -08001686 }
1687 }
1688 // For normal PCM streaming tracks, update minimum frame count.
1689 // For compatibility with AudioTrack calculation, buffer depth is forced
1690 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1691 // This is probably too conservative, but legacy application code may depend on it.
1692 // If you change this calculation, also review the start threshold which is related.
1693 if (!(*flags & IAudioFlinger::TRACK_FAST)
1694 && audio_is_linear_pcm(format) && sharedBuffer == 0) {
Andy Hung8edb8dc2015-03-26 19:13:55 -07001695 // this must match AudioTrack.cpp calculateMinFrameCount().
1696 // TODO: Move to a common library
Eric Laurent81784c32012-11-19 14:55:58 -08001697 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1698 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1699 if (minBufCount < 2) {
1700 minBufCount = 2;
1701 }
Andy Hung8edb8dc2015-03-26 19:13:55 -07001702 // For normal mixing tracks, if speed is > 1.0f (normal), AudioTrack
1703 // or the client should compute and pass in a larger buffer request.
Andy Hung0e48d252015-01-26 11:43:15 -08001704 size_t minFrameCount =
Andy Hung8edb8dc2015-03-26 19:13:55 -07001705 minBufCount * sourceFramesNeededWithTimestretch(
1706 sampleRate, mNormalFrameCount,
1707 mSampleRate, AUDIO_TIMESTRETCH_SPEED_NORMAL /*speed*/);
Andy Hung0e48d252015-01-26 11:43:15 -08001708 if (frameCount < minFrameCount) { // including frameCount == 0
Eric Laurent81784c32012-11-19 14:55:58 -08001709 frameCount = minFrameCount;
1710 }
Eric Laurent81784c32012-11-19 14:55:58 -08001711 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001712 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001713
Glenn Kastenc3df8382014-03-13 15:05:25 -07001714 switch (mType) {
1715
1716 case DIRECT:
Glenn Kasten993fa062014-05-02 11:14:34 -07001717 if (audio_is_linear_pcm(format)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001718 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001719 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1720 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001721 sampleRate, format, channelMask, mOutput, mFormat);
1722 lStatus = BAD_VALUE;
1723 goto Exit;
1724 }
1725 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001726 break;
1727
1728 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001729 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001730 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1731 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001732 sampleRate, format, channelMask, mOutput, mFormat);
1733 lStatus = BAD_VALUE;
1734 goto Exit;
1735 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001736 break;
1737
1738 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07001739 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001740 ALOGE("createTrack_l() Bad parameter: format %#x \""
1741 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001742 format, mOutput, mFormat);
1743 lStatus = BAD_VALUE;
1744 goto Exit;
1745 }
Andy Hungcd044842014-08-07 11:04:34 -07001746 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08001747 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1748 lStatus = BAD_VALUE;
1749 goto Exit;
1750 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001751 break;
1752
Eric Laurent81784c32012-11-19 14:55:58 -08001753 }
1754
1755 lStatus = initCheck();
1756 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07001757 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08001758 goto Exit;
1759 }
1760
1761 { // scope for mLock
1762 Mutex::Autolock _l(mLock);
1763
1764 // all tracks in same audio session must share the same routing strategy otherwise
1765 // conflicts will happen when tracks are moved from one output to another by audio policy
1766 // manager
1767 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1768 for (size_t i = 0; i < mTracks.size(); ++i) {
1769 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07001770 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001771 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1772 if (sessionId == t->sessionId() && strategy != actual) {
1773 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1774 strategy, actual);
1775 lStatus = BAD_VALUE;
1776 goto Exit;
1777 }
1778 }
1779 }
1780
1781 if (!isTimed) {
1782 track = new Track(this, client, streamType, sampleRate, format,
Eric Laurent83b88082014-06-20 18:31:16 -07001783 channelMask, frameCount, NULL, sharedBuffer,
1784 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08001785 } else {
1786 track = TimedTrack::create(this, client, streamType, sampleRate, format,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001787 channelMask, frameCount, sharedBuffer, sessionId, uid);
Eric Laurent81784c32012-11-19 14:55:58 -08001788 }
Glenn Kasten03003332013-08-06 15:40:54 -07001789
1790 // new Track always returns non-NULL,
1791 // but TimedTrack::create() is a factory that could fail by returning NULL
1792 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
1793 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08001794 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001795 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08001796 goto Exit;
1797 }
1798 mTracks.add(track);
1799
1800 sp<EffectChain> chain = getEffectChain_l(sessionId);
1801 if (chain != 0) {
1802 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1803 track->setMainBuffer(chain->inBuffer());
1804 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1805 chain->incTrackCnt();
1806 }
1807
1808 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1809 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1810 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1811 // so ask activity manager to do this on our behalf
1812 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1813 }
1814 }
1815
1816 lStatus = NO_ERROR;
1817
1818Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001819 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001820 return track;
1821}
1822
1823uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1824{
1825 return latency;
1826}
1827
1828uint32_t AudioFlinger::PlaybackThread::latency() const
1829{
1830 Mutex::Autolock _l(mLock);
1831 return latency_l();
1832}
1833uint32_t AudioFlinger::PlaybackThread::latency_l() const
1834{
1835 if (initCheck() == NO_ERROR) {
1836 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
1837 } else {
1838 return 0;
1839 }
1840}
1841
1842void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1843{
1844 Mutex::Autolock _l(mLock);
1845 // Don't apply master volume in SW if our HAL can do it for us.
1846 if (mOutput && mOutput->audioHwDev &&
1847 mOutput->audioHwDev->canSetMasterVolume()) {
1848 mMasterVolume = 1.0;
1849 } else {
1850 mMasterVolume = value;
1851 }
1852}
1853
1854void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1855{
1856 Mutex::Autolock _l(mLock);
1857 // Don't apply master mute in SW if our HAL can do it for us.
1858 if (mOutput && mOutput->audioHwDev &&
1859 mOutput->audioHwDev->canSetMasterMute()) {
1860 mMasterMute = false;
1861 } else {
1862 mMasterMute = muted;
1863 }
1864}
1865
1866void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
1867{
1868 Mutex::Autolock _l(mLock);
1869 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001870 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001871}
1872
1873void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
1874{
1875 Mutex::Autolock _l(mLock);
1876 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001877 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001878}
1879
1880float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
1881{
1882 Mutex::Autolock _l(mLock);
1883 return mStreamTypes[stream].volume;
1884}
1885
1886// addTrack_l() must be called with ThreadBase::mLock held
1887status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1888{
1889 status_t status = ALREADY_EXISTS;
1890
1891 // set retry count for buffer fill
1892 track->mRetryCount = kMaxTrackStartupRetries;
1893 if (mActiveTracks.indexOf(track) < 0) {
1894 // the track is newly added, make sure it fills up all its
1895 // buffers before playing. This is to ensure the client will
1896 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07001897 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001898 TrackBase::track_state state = track->mState;
1899 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08001900 status = AudioSystem::startOutput(mId, track->streamType(),
1901 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001902 mLock.lock();
1903 // abort track was stopped/paused while we released the lock
1904 if (state != track->mState) {
1905 if (status == NO_ERROR) {
1906 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08001907 AudioSystem::stopOutput(mId, track->streamType(),
1908 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001909 mLock.lock();
1910 }
1911 return INVALID_OPERATION;
1912 }
1913 // abort if start is rejected by audio policy manager
1914 if (status != NO_ERROR) {
1915 return PERMISSION_DENIED;
1916 }
1917#ifdef ADD_BATTERY_DATA
1918 // to track the speaker usage
1919 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
1920#endif
1921 }
1922
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001923 track->mFillingUpStatus = track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent81784c32012-11-19 14:55:58 -08001924 track->mResetDone = false;
1925 track->mPresentationCompleteFrames = 0;
1926 mActiveTracks.add(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001927 mWakeLockUids.add(track->uid());
1928 mActiveTracksGeneration++;
Eric Laurentfd477972013-10-25 18:10:40 -07001929 mLatestActiveTrack = track;
Eric Laurentd0107bc2013-06-11 14:38:48 -07001930 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1931 if (chain != 0) {
1932 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
1933 track->sessionId());
1934 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08001935 }
1936
1937 status = NO_ERROR;
1938 }
1939
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08001940 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001941 return status;
1942}
1943
Eric Laurentbfb1b832013-01-07 09:53:42 -08001944bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08001945{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001946 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08001947 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001948 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
1949 track->mState = TrackBase::STOPPED;
1950 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08001951 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07001952 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001953 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08001954 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001955
1956 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08001957}
1958
1959void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1960{
1961 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
1962 mTracks.remove(track);
1963 deleteTrackName_l(track->name());
1964 // redundant as track is about to be destroyed, for dumpsys only
1965 track->mName = -1;
1966 if (track->isFastTrack()) {
1967 int index = track->mFastIndex;
1968 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
1969 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1970 mFastTrackAvailMask |= 1 << index;
1971 // redundant as track is about to be destroyed, for dumpsys only
1972 track->mFastIndex = -1;
1973 }
1974 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1975 if (chain != 0) {
1976 chain->decTrackCnt();
1977 }
1978}
1979
Eric Laurentede6c3b2013-09-19 14:37:46 -07001980void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001981{
1982 // Thread could be blocked waiting for async
1983 // so signal it to handle state changes immediately
1984 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1985 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1986 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001987 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001988}
1989
Eric Laurent81784c32012-11-19 14:55:58 -08001990String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1991{
Eric Laurent81784c32012-11-19 14:55:58 -08001992 Mutex::Autolock _l(mLock);
1993 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07001994 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08001995 }
1996
Glenn Kastend8ea6992013-07-16 14:17:15 -07001997 char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
1998 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08001999 free(s);
2000 return out_s8;
2001}
2002
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002003void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002004 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2005 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002006
Eric Laurent73e26b62015-04-27 16:55:58 -07002007 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002008
2009 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002010 case AUDIO_OUTPUT_OPENED:
2011 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002012 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002013 desc->mChannelMask = mChannelMask;
2014 desc->mSamplingRate = mSampleRate;
2015 desc->mFormat = mFormat;
2016 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002017 // AudioFlinger::frameCount(audio_io_handle_t)
Eric Laurent73e26b62015-04-27 16:55:58 -07002018 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002019 break;
2020
Eric Laurent73e26b62015-04-27 16:55:58 -07002021 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002022 default:
2023 break;
2024 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002025 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002026}
2027
Eric Laurentbfb1b832013-01-07 09:53:42 -08002028void AudioFlinger::PlaybackThread::writeCallback()
2029{
2030 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002031 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002032}
2033
2034void AudioFlinger::PlaybackThread::drainCallback()
2035{
2036 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002037 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002038}
2039
Eric Laurent3b4529e2013-09-05 18:09:19 -07002040void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002041{
2042 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002043 // reject out of sequence requests
2044 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2045 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002046 mWaitWorkCV.signal();
2047 }
2048}
2049
Eric Laurent3b4529e2013-09-05 18:09:19 -07002050void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002051{
2052 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002053 // reject out of sequence requests
2054 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
2055 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002056 mWaitWorkCV.signal();
2057 }
2058}
2059
2060// static
2061int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
Glenn Kasten0f11b512014-01-31 16:18:54 -08002062 void *param __unused,
Eric Laurentbfb1b832013-01-07 09:53:42 -08002063 void *cookie)
2064{
2065 AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
2066 ALOGV("asyncCallback() event %d", event);
2067 switch (event) {
2068 case STREAM_CBK_EVENT_WRITE_READY:
2069 me->writeCallback();
2070 break;
2071 case STREAM_CBK_EVENT_DRAIN_READY:
2072 me->drainCallback();
2073 break;
2074 default:
2075 ALOGW("asyncCallback() unknown event %d", event);
2076 break;
2077 }
2078 return 0;
2079}
2080
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002081void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002082{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002083 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Eric Laurent81784c32012-11-19 14:55:58 -08002084 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
2085 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002086 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002087 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002088 }
Andy Hung9a592762014-07-21 21:56:01 -07002089 if ((mType == MIXER || mType == DUPLICATING)
2090 && !isValidPcmSinkChannelMask(mChannelMask)) {
2091 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2092 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002093 }
Andy Hunge5412692014-05-16 11:25:07 -07002094 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Andy Hung463be252014-07-10 16:56:07 -07002095 mHALFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
2096 mFormat = mHALFormat;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002097 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002098 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002099 }
Andy Hung6146c082014-03-18 11:56:15 -07002100 if ((mType == MIXER || mType == DUPLICATING)
2101 && !isValidPcmSinkFormat(mFormat)) {
2102 LOG_FATAL("HAL format %#x not supported for mixed output",
2103 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002104 }
Phil Burk062e67a2015-02-11 13:40:50 -08002105 mFrameSize = mOutput->getFrameSize();
Glenn Kasten70949c42013-08-06 07:40:12 -07002106 mBufferSize = mOutput->stream->common.get_buffer_size(&mOutput->stream->common);
2107 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002108 if (mFrameCount & 15) {
2109 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
2110 mFrameCount);
2111 }
2112
Eric Laurentbfb1b832013-01-07 09:53:42 -08002113 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
2114 (mOutput->stream->set_callback != NULL)) {
2115 if (mOutput->stream->set_callback(mOutput->stream,
2116 AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
2117 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002118 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002119 }
2120 }
2121
Eric Laurentd1f69b02014-12-15 14:33:13 -08002122 mHwSupportsPause = false;
2123 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
2124 if (mOutput->stream->pause != NULL) {
2125 if (mOutput->stream->resume != NULL) {
2126 mHwSupportsPause = true;
2127 } else {
2128 ALOGW("direct output implements pause but not resume");
2129 }
2130 } else if (mOutput->stream->resume != NULL) {
2131 ALOGW("direct output implements resume but not pause");
2132 }
2133 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002134 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2135 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2136 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002137
Andy Hungfbfc3952015-01-15 13:33:51 -08002138 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2139 // For best precision, we use float instead of the associated output
2140 // device format (typically PCM 16 bit).
2141
2142 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2143 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2144 mBufferSize = mFrameSize * mFrameCount;
2145
2146 // TODO: We currently use the associated output device channel mask and sample rate.
2147 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2148 // (if a valid mask) to avoid premature downmix.
2149 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2150 // instead of the output device sample rate to avoid loss of high frequency information.
2151 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2152 }
2153
Andy Hung09a50072014-02-27 14:30:47 -08002154 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002155 double multiplier = 1.0;
2156 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2157 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002158 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2159 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Eric Laurent81784c32012-11-19 14:55:58 -08002160 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2161 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2162 maxNormalFrameCount = maxNormalFrameCount & ~15;
2163 if (maxNormalFrameCount < minNormalFrameCount) {
2164 maxNormalFrameCount = minNormalFrameCount;
2165 }
2166 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2167 if (multiplier <= 1.0) {
2168 multiplier = 1.0;
2169 } else if (multiplier <= 2.0) {
2170 if (2 * mFrameCount <= maxNormalFrameCount) {
2171 multiplier = 2.0;
2172 } else {
2173 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2174 }
2175 } else {
2176 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
Andy Hung09a50072014-02-27 14:30:47 -08002177 // 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 -08002178 // track, but we sometimes have to do this to satisfy the maximum frame count
2179 // constraint)
2180 // FIXME this rounding up should not be done if no HAL SRC
2181 uint32_t truncMult = (uint32_t) multiplier;
2182 if ((truncMult & 1)) {
2183 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
2184 ++truncMult;
2185 }
2186 }
2187 multiplier = (double) truncMult;
2188 }
2189 }
2190 mNormalFrameCount = multiplier * mFrameCount;
2191 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002192 if (mType == MIXER || mType == DUPLICATING) {
2193 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2194 }
Andy Hung09a50072014-02-27 14:30:47 -08002195 ALOGI("HAL output buffer size %u frames, normal sink buffer size %u frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002196 mNormalFrameCount);
2197
Andy Hung08fb1742015-05-31 23:22:10 -07002198 // Check if we want to throttle the processing to no more than 2x normal rate
2199 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002200 mThreadThrottleTimeMs = 0;
2201 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002202 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2203
Andy Hung010a1a12014-03-13 13:57:33 -07002204 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2205 // Originally this was int16_t[] array, need to remove legacy implications.
2206 free(mSinkBuffer);
2207 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002208 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2209 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2210 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002211 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002212
Andy Hung69aed5f2014-02-25 17:24:40 -08002213 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2214 // drives the output.
2215 free(mMixerBuffer);
2216 mMixerBuffer = NULL;
2217 if (mMixerBufferEnabled) {
2218 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2219 mMixerBufferSize = mNormalFrameCount * mChannelCount
2220 * audio_bytes_per_sample(mMixerBufferFormat);
2221 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2222 }
Andy Hung98ef9782014-03-04 14:46:50 -08002223 free(mEffectBuffer);
2224 mEffectBuffer = NULL;
2225 if (mEffectBufferEnabled) {
2226 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
2227 mEffectBufferSize = mNormalFrameCount * mChannelCount
2228 * audio_bytes_per_sample(mEffectBufferFormat);
2229 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2230 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002231
Eric Laurent81784c32012-11-19 14:55:58 -08002232 // force reconfiguration of effect chains and engines to take new buffer size and audio
2233 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002234 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002235 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2236 // matter.
2237 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2238 Vector< sp<EffectChain> > effectChains = mEffectChains;
2239 for (size_t i = 0; i < effectChains.size(); i ++) {
2240 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2241 }
2242}
2243
2244
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002245status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002246{
2247 if (halFrames == NULL || dspFrames == NULL) {
2248 return BAD_VALUE;
2249 }
2250 Mutex::Autolock _l(mLock);
2251 if (initCheck() != NO_ERROR) {
2252 return INVALID_OPERATION;
2253 }
2254 size_t framesWritten = mBytesWritten / mFrameSize;
2255 *halFrames = framesWritten;
2256
2257 if (isSuspended()) {
2258 // return an estimation of rendered frames when the output is suspended
2259 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
2260 *dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0;
2261 return NO_ERROR;
2262 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002263 status_t status;
2264 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002265 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002266 *dspFrames = (size_t)frames;
2267 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002268 }
2269}
2270
2271uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
2272{
2273 Mutex::Autolock _l(mLock);
2274 uint32_t result = 0;
2275 if (getEffectChain_l(sessionId) != 0) {
2276 result = EFFECT_SESSION;
2277 }
2278
2279 for (size_t i = 0; i < mTracks.size(); ++i) {
2280 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002281 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002282 result |= TRACK_SESSION;
2283 break;
2284 }
2285 }
2286
2287 return result;
2288}
2289
2290uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
2291{
2292 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2293 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2294 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2295 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2296 }
2297 for (size_t i = 0; i < mTracks.size(); i++) {
2298 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002299 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002300 return AudioSystem::getStrategyForStream(track->streamType());
2301 }
2302 }
2303 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2304}
2305
2306
Phil Burk062e67a2015-02-11 13:40:50 -08002307AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002308{
2309 Mutex::Autolock _l(mLock);
2310 return mOutput;
2311}
2312
Phil Burk062e67a2015-02-11 13:40:50 -08002313AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002314{
2315 Mutex::Autolock _l(mLock);
2316 AudioStreamOut *output = mOutput;
2317 mOutput = NULL;
2318 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2319 // must push a NULL and wait for ack
2320 mOutputSink.clear();
2321 mPipeSink.clear();
2322 mNormalSink.clear();
2323 return output;
2324}
2325
2326// this method must always be called either with ThreadBase mLock held or inside the thread loop
2327audio_stream_t* AudioFlinger::PlaybackThread::stream() const
2328{
2329 if (mOutput == NULL) {
2330 return NULL;
2331 }
2332 return &mOutput->stream->common;
2333}
2334
2335uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2336{
2337 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2338}
2339
2340status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2341{
2342 if (!isValidSyncEvent(event)) {
2343 return BAD_VALUE;
2344 }
2345
2346 Mutex::Autolock _l(mLock);
2347
2348 for (size_t i = 0; i < mTracks.size(); ++i) {
2349 sp<Track> track = mTracks[i];
2350 if (event->triggerSession() == track->sessionId()) {
2351 (void) track->setSyncEvent(event);
2352 return NO_ERROR;
2353 }
2354 }
2355
2356 return NAME_NOT_FOUND;
2357}
2358
2359bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2360{
2361 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2362}
2363
2364void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2365 const Vector< sp<Track> >& tracksToRemove)
2366{
2367 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002368 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002369 for (size_t i = 0 ; i < count ; i++) {
2370 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002371 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002372 AudioSystem::stopOutput(mId, track->streamType(),
2373 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002374#ifdef ADD_BATTERY_DATA
2375 // to track the speaker usage
2376 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2377#endif
2378 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002379 AudioSystem::releaseOutput(mId, track->streamType(),
2380 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002381 }
Eric Laurent81784c32012-11-19 14:55:58 -08002382 }
2383 }
2384 }
Eric Laurent81784c32012-11-19 14:55:58 -08002385}
2386
2387void AudioFlinger::PlaybackThread::checkSilentMode_l()
2388{
2389 if (!mMasterMute) {
2390 char value[PROPERTY_VALUE_MAX];
2391 if (property_get("ro.audio.silent", value, "0") > 0) {
2392 char *endptr;
2393 unsigned long ul = strtoul(value, &endptr, 0);
2394 if (*endptr == '\0' && ul != 0) {
2395 ALOGD("Silence is golden");
2396 // The setprop command will not allow a property to be changed after
2397 // the first time it is set, so we don't have to worry about un-muting.
2398 setMasterMute_l(true);
2399 }
2400 }
2401 }
2402}
2403
2404// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002405ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002406{
2407 // FIXME rewrite to reduce number of system calls
2408 mLastWriteTime = systemTime();
2409 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002410 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002411 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002412
2413 // If an NBAIO sink is present, use it to write the normal mixer's submix
2414 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002415
Andy Hung010a1a12014-03-13 13:57:33 -07002416 const size_t count = mBytesRemaining / mFrameSize;
2417
Simon Wilson2d590962012-11-29 15:18:50 -08002418 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002419 // update the setpoint when AudioFlinger::mScreenState changes
2420 uint32_t screenState = AudioFlinger::mScreenState;
2421 if (screenState != mScreenState) {
2422 mScreenState = screenState;
2423 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2424 if (pipe != NULL) {
2425 pipe->setAvgFrames((mScreenState & 1) ?
2426 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2427 }
2428 }
Andy Hung010a1a12014-03-13 13:57:33 -07002429 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002430 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002431 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002432 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002433 } else {
2434 bytesWritten = framesWritten;
2435 }
Glenn Kastenefaa7ab2014-08-20 08:48:54 -07002436 mLatchDValid = false;
Glenn Kasten767094d2013-08-23 13:51:43 -07002437 status_t status = mNormalSink->getTimestamp(mLatchD.mTimestamp);
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002438 if (status == NO_ERROR) {
2439 size_t totalFramesWritten = mNormalSink->framesWritten();
2440 if (totalFramesWritten >= mLatchD.mTimestamp.mPosition) {
2441 mLatchD.mUnpresentedFrames = totalFramesWritten - mLatchD.mTimestamp.mPosition;
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002442 // mLatchD.mFramesReleased is set immediately before D is clocked into Q
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002443 mLatchDValid = true;
2444 }
2445 }
Eric Laurent81784c32012-11-19 14:55:58 -08002446 // otherwise use the HAL / AudioStreamOut directly
2447 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002448 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002449
Eric Laurentbfb1b832013-01-07 09:53:42 -08002450 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002451 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2452 mWriteAckSequence += 2;
2453 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 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002457 // FIXME We should have an implementation of timestamps for direct output threads.
2458 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002459 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002460 if (mUseAsyncWrite &&
2461 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2462 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002463 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002464 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002465 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002466 }
Eric Laurent81784c32012-11-19 14:55:58 -08002467 }
2468
Eric Laurent81784c32012-11-19 14:55:58 -08002469 mNumWrites++;
2470 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002471 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002472 return bytesWritten;
2473}
2474
2475void AudioFlinger::PlaybackThread::threadLoop_drain()
2476{
2477 if (mOutput->stream->drain) {
2478 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2479 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002480 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2481 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002482 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002483 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002484 }
2485 mOutput->stream->drain(mOutput->stream,
2486 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
2487 : AUDIO_DRAIN_ALL);
2488 }
2489}
2490
2491void AudioFlinger::PlaybackThread::threadLoop_exit()
2492{
Eric Laurent275e8e92014-11-30 15:14:47 -08002493 {
2494 Mutex::Autolock _l(mLock);
2495 for (size_t i = 0; i < mTracks.size(); i++) {
2496 sp<Track> track = mTracks[i];
2497 track->invalidate();
2498 }
2499 }
Eric Laurent81784c32012-11-19 14:55:58 -08002500}
2501
2502/*
2503The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002504 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002505 - mActiveSleepTimeUs from activeSleepTimeUs()
2506 - mIdleSleepTimeUs from idleSleepTimeUs()
2507 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only)
Eric Laurent81784c32012-11-19 14:55:58 -08002508 - maxPeriod from frame count and sample rate (MIXER only)
2509
2510The parameters that affect these derived values are:
2511 - frame count
2512 - frame size
2513 - sample rate
2514 - device type: A2DP or not
2515 - device latency
2516 - format: PCM or not
2517 - active sleep time
2518 - idle sleep time
2519*/
2520
2521void AudioFlinger::PlaybackThread::cacheParameters_l()
2522{
Andy Hung25c2dac2014-02-27 14:56:00 -08002523 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002524 mActiveSleepTimeUs = activeSleepTimeUs();
2525 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent81784c32012-11-19 14:55:58 -08002526}
2527
2528void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2529{
Glenn Kasten7c027242012-12-26 14:43:16 -08002530 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurent81784c32012-11-19 14:55:58 -08002531 this, streamType, mTracks.size());
2532 Mutex::Autolock _l(mLock);
2533
2534 size_t size = mTracks.size();
2535 for (size_t i = 0; i < size; i++) {
2536 sp<Track> t = mTracks[i];
2537 if (t->streamType() == streamType) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002538 t->invalidate();
Eric Laurent81784c32012-11-19 14:55:58 -08002539 }
2540 }
2541}
2542
2543status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2544{
2545 int session = chain->sessionId();
Andy Hung010a1a12014-03-13 13:57:33 -07002546 int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled
2547 ? mEffectBuffer : mSinkBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002548 bool ownsBuffer = false;
2549
2550 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
2551 if (session > 0) {
2552 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002553 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002554 if (mType != DIRECT) {
2555 size_t numSamples = mNormalFrameCount * mChannelCount;
2556 buffer = new int16_t[numSamples];
2557 memset(buffer, 0, numSamples * sizeof(int16_t));
2558 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2559 ownsBuffer = true;
2560 }
2561
2562 // Attach all tracks with same session ID to this chain.
2563 for (size_t i = 0; i < mTracks.size(); ++i) {
2564 sp<Track> track = mTracks[i];
2565 if (session == track->sessionId()) {
2566 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2567 buffer);
2568 track->setMainBuffer(buffer);
2569 chain->incTrackCnt();
2570 }
2571 }
2572
2573 // indicate all active tracks in the chain
2574 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2575 sp<Track> track = mActiveTracks[i].promote();
2576 if (track == 0) {
2577 continue;
2578 }
2579 if (session == track->sessionId()) {
2580 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2581 chain->incActiveTrackCnt();
2582 }
2583 }
2584 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002585 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08002586 chain->setInBuffer(buffer, ownsBuffer);
Andy Hung010a1a12014-03-13 13:57:33 -07002587 chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled
2588 ? mEffectBuffer : mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002589 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
2590 // chains list in order to be processed last as it contains output stage effects
2591 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2592 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
2593 // after track specific effects and before output stage
2594 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
2595 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
2596 // Effect chain for other sessions are inserted at beginning of effect
2597 // chains list to be processed before output mix effects. Relative order between other
2598 // sessions is not important
2599 size_t size = mEffectChains.size();
2600 size_t i = 0;
2601 for (i = 0; i < size; i++) {
2602 if (mEffectChains[i]->sessionId() < session) {
2603 break;
2604 }
2605 }
2606 mEffectChains.insertAt(chain, i);
2607 checkSuspendOnAddEffectChain_l(chain);
2608
2609 return NO_ERROR;
2610}
2611
2612size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2613{
2614 int session = chain->sessionId();
2615
2616 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2617
2618 for (size_t i = 0; i < mEffectChains.size(); i++) {
2619 if (chain == mEffectChains[i]) {
2620 mEffectChains.removeAt(i);
2621 // detach all active tracks from the chain
2622 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2623 sp<Track> track = mActiveTracks[i].promote();
2624 if (track == 0) {
2625 continue;
2626 }
2627 if (session == track->sessionId()) {
2628 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2629 chain.get(), session);
2630 chain->decActiveTrackCnt();
2631 }
2632 }
2633
2634 // detach all tracks with same session ID from this chain
2635 for (size_t i = 0; i < mTracks.size(); ++i) {
2636 sp<Track> track = mTracks[i];
2637 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002638 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002639 chain->decTrackCnt();
2640 }
2641 }
2642 break;
2643 }
2644 }
2645 return mEffectChains.size();
2646}
2647
2648status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2649 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2650{
2651 Mutex::Autolock _l(mLock);
2652 return attachAuxEffect_l(track, EffectId);
2653}
2654
2655status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2656 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2657{
2658 status_t status = NO_ERROR;
2659
2660 if (EffectId == 0) {
2661 track->setAuxBuffer(0, NULL);
2662 } else {
2663 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2664 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2665 if (effect != 0) {
2666 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2667 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2668 } else {
2669 status = INVALID_OPERATION;
2670 }
2671 } else {
2672 status = BAD_VALUE;
2673 }
2674 }
2675 return status;
2676}
2677
2678void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2679{
2680 for (size_t i = 0; i < mTracks.size(); ++i) {
2681 sp<Track> track = mTracks[i];
2682 if (track->auxEffectId() == effectId) {
2683 attachAuxEffect_l(track, 0);
2684 }
2685 }
2686}
2687
2688bool AudioFlinger::PlaybackThread::threadLoop()
2689{
2690 Vector< sp<Track> > tracksToRemove;
2691
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002692 mStandbyTimeNs = systemTime();
Eric Laurent81784c32012-11-19 14:55:58 -08002693
2694 // MIXER
2695 nsecs_t lastWarning = 0;
2696
2697 // DUPLICATING
2698 // FIXME could this be made local to while loop?
2699 writeFrames = 0;
2700
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002701 int lastGeneration = 0;
2702
Eric Laurent81784c32012-11-19 14:55:58 -08002703 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002704 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08002705
2706 if (mType == MIXER) {
2707 sleepTimeShift = 0;
2708 }
2709
2710 CpuStats cpuStats;
2711 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2712
2713 acquireWakeLock();
2714
Glenn Kasten9e58b552013-01-18 15:09:48 -08002715 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2716 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2717 // and then that string will be logged at the next convenient opportunity.
2718 const char *logString = NULL;
2719
Eric Laurent664539d2013-09-23 18:24:31 -07002720 checkSilentMode_l();
2721
Eric Laurent81784c32012-11-19 14:55:58 -08002722 while (!exitPending())
2723 {
2724 cpuStats.sample(myName);
2725
2726 Vector< sp<EffectChain> > effectChains;
2727
Eric Laurent81784c32012-11-19 14:55:58 -08002728 { // scope for mLock
2729
2730 Mutex::Autolock _l(mLock);
2731
Eric Laurent021cf962014-05-13 10:18:14 -07002732 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07002733
Glenn Kasten9e58b552013-01-18 15:09:48 -08002734 if (logString != NULL) {
2735 mNBLogWriter->logTimestamp();
2736 mNBLogWriter->log(logString);
2737 logString = NULL;
2738 }
2739
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002740 // Gather the framesReleased counters for all active tracks,
2741 // and latch them atomically with the timestamp.
2742 // FIXME We're using raw pointers as indices. A unique track ID would be a better index.
2743 mLatchD.mFramesReleased.clear();
2744 size_t size = mActiveTracks.size();
2745 for (size_t i = 0; i < size; i++) {
2746 sp<Track> t = mActiveTracks[i].promote();
2747 if (t != 0) {
2748 mLatchD.mFramesReleased.add(t.get(),
2749 t->mAudioTrackServerProxy->framesReleased());
2750 }
2751 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002752 if (mLatchDValid) {
2753 mLatchQ = mLatchD;
2754 mLatchDValid = false;
2755 mLatchQValid = true;
2756 }
2757
Eric Laurent81784c32012-11-19 14:55:58 -08002758 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002759 if (mSignalPending) {
2760 // A signal was raised while we were unlocked
2761 mSignalPending = false;
2762 } else if (waitingAsyncCallback_l()) {
2763 if (exitPending()) {
2764 break;
2765 }
Marco Nelissen078538c2015-05-12 09:17:57 -07002766 bool released = false;
2767 // The following works around a bug in the offload driver. Ideally we would release
2768 // the wake lock every time, but that causes the last offload buffer(s) to be
2769 // dropped while the device is on battery, so we need to hold a wake lock during
2770 // the drain phase.
2771 if (mBytesRemaining && !(mDrainSequence & 1)) {
2772 releaseWakeLock_l();
2773 released = true;
2774 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002775 mWakeLockUids.clear();
2776 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002777 ALOGV("wait async completion");
2778 mWaitWorkCV.wait(mLock);
2779 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07002780 if (released) {
2781 acquireWakeLock_l();
2782 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002783 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
2784 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002785
2786 continue;
2787 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002788 if ((!mActiveTracks.size() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08002789 isSuspended()) {
2790 // put audio hardware into standby after short delay
2791 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002792
2793 threadLoop_standby();
2794
2795 mStandby = true;
2796 }
2797
2798 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2799 // we're about to wait, flush the binder command buffer
2800 IPCThreadState::self()->flushCommands();
2801
2802 clearOutputTracks();
2803
2804 if (exitPending()) {
2805 break;
2806 }
2807
2808 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002809 mWakeLockUids.clear();
2810 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002811 // wait until we have something to do...
2812 ALOGV("%s going to sleep", myName.string());
2813 mWaitWorkCV.wait(mLock);
2814 ALOGV("%s waking up", myName.string());
2815 acquireWakeLock_l();
2816
2817 mMixerStatus = MIXER_IDLE;
2818 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2819 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002820 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002821 checkSilentMode_l();
2822
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002823 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
2824 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08002825 if (mType == MIXER) {
2826 sleepTimeShift = 0;
2827 }
2828
2829 continue;
2830 }
2831 }
Eric Laurent81784c32012-11-19 14:55:58 -08002832 // mMixerStatusIgnoringFastTracks is also updated internally
2833 mMixerStatus = prepareTracks_l(&tracksToRemove);
2834
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002835 // compare with previously applied list
2836 if (lastGeneration != mActiveTracksGeneration) {
2837 // update wakelock
2838 updateWakeLockUids_l(mWakeLockUids);
2839 lastGeneration = mActiveTracksGeneration;
2840 }
2841
Eric Laurent81784c32012-11-19 14:55:58 -08002842 // prevent any changes in effect chain list and in each effect chain
2843 // during mixing and effect process as the audio buffers could be deleted
2844 // or modified if an effect is created or deleted
2845 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002846 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08002847
Eric Laurentbfb1b832013-01-07 09:53:42 -08002848 if (mBytesRemaining == 0) {
2849 mCurrentWriteLength = 0;
2850 if (mMixerStatus == MIXER_TRACKS_READY) {
2851 // threadLoop_mix() sets mCurrentWriteLength
2852 threadLoop_mix();
2853 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
2854 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002855 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08002856 // must be written to HAL
2857 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002858 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08002859 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002860 }
2861 }
Andy Hung98ef9782014-03-04 14:46:50 -08002862 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002863 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08002864 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
2865 // or mSinkBuffer (if there are no effects).
2866 //
2867 // This is done pre-effects computation; if effects change to
2868 // support higher precision, this needs to move.
2869 //
2870 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002871 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08002872 if (mMixerBufferValid) {
2873 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
2874 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
2875
2876 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
2877 mNormalFrameCount * mChannelCount);
2878 }
2879
Eric Laurentbfb1b832013-01-07 09:53:42 -08002880 mBytesRemaining = mCurrentWriteLength;
2881 if (isSuspended()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002882 mSleepTimeUs = suspendSleepTimeUs();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002883 // simulate write to HAL when suspended
Andy Hung25c2dac2014-02-27 14:56:00 -08002884 mBytesWritten += mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002885 mBytesRemaining = 0;
2886 }
Eric Laurent81784c32012-11-19 14:55:58 -08002887
Eric Laurentbfb1b832013-01-07 09:53:42 -08002888 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002889 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002890 for (size_t i = 0; i < effectChains.size(); i ++) {
2891 effectChains[i]->process_l();
2892 }
Eric Laurent81784c32012-11-19 14:55:58 -08002893 }
2894 }
Eric Laurent59fe0102013-09-27 18:48:26 -07002895 // Process effect chains for offloaded thread even if no audio
2896 // was read from audio track: process only updates effect state
2897 // and thus does have to be synchronized with audio writes but may have
2898 // to be called while waiting for async write callback
2899 if (mType == OFFLOAD) {
2900 for (size_t i = 0; i < effectChains.size(); i ++) {
2901 effectChains[i]->process_l();
2902 }
2903 }
Eric Laurent81784c32012-11-19 14:55:58 -08002904
Andy Hung98ef9782014-03-04 14:46:50 -08002905 // Only if the Effects buffer is enabled and there is data in the
2906 // Effects buffer (buffer valid), we need to
2907 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002908 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08002909 if (mEffectBufferValid) {
2910 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
2911 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
2912 mNormalFrameCount * mChannelCount);
2913 }
2914
Eric Laurent81784c32012-11-19 14:55:58 -08002915 // enable changes in effect chain
2916 unlockEffectChains(effectChains);
2917
Eric Laurentbfb1b832013-01-07 09:53:42 -08002918 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002919 // mSleepTimeUs == 0 means we must write to audio hardware
2920 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07002921 ssize_t ret = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002922 if (mBytesRemaining) {
Andy Hung08fb1742015-05-31 23:22:10 -07002923 ret = threadLoop_write();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002924 if (ret < 0) {
2925 mBytesRemaining = 0;
2926 } else {
2927 mBytesWritten += ret;
2928 mBytesRemaining -= ret;
2929 }
2930 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
2931 (mMixerStatus == MIXER_DRAIN_ALL)) {
2932 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08002933 }
Andy Hung08fb1742015-05-31 23:22:10 -07002934 if (mType == MIXER && !mStandby) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07002935 // write blocked detection
2936 nsecs_t now = systemTime();
2937 nsecs_t delta = now - mLastWriteTime;
Andy Hung08fb1742015-05-31 23:22:10 -07002938 if (delta > maxPeriod) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07002939 mNumDelayedWrites++;
2940 if ((now - lastWarning) > kWarningThrottleNs) {
2941 ATRACE_NAME("underrun");
2942 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2943 ns2ms(delta), mNumDelayedWrites, this);
2944 lastWarning = now;
2945 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002946 }
Andy Hung08fb1742015-05-31 23:22:10 -07002947
2948 if (mThreadThrottle
2949 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
2950 && ret > 0) { // we wrote something
2951 // Limit MixerThread data processing to no more than twice the
2952 // expected processing rate.
2953 //
2954 // This helps prevent underruns with NuPlayer and other applications
2955 // which may set up buffers that are close to the minimum size, or use
2956 // deep buffers, and rely on a double-buffering sleep strategy to fill.
2957 //
2958 // The throttle smooths out sudden large data drains from the device,
2959 // e.g. when it comes out of standby, which often causes problems with
2960 // (1) mixer threads without a fast mixer (which has its own warm-up)
2961 // (2) minimum buffer sized tracks (even if the track is full,
2962 // the app won't fill fast enough to handle the sudden draw).
2963
2964 const int32_t deltaMs = delta / 1000000;
2965 const int32_t throttleMs = mHalfBufferMs - deltaMs;
2966 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
2967 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07002968 // notify of throttle start on verbose log
2969 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
2970 "mixer(%p) throttle begin:"
2971 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07002972 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07002973 mThreadThrottleTimeMs += throttleMs;
2974 } else {
2975 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
2976 if (diff > 0) {
2977 // notify of throttle end on debug log
2978 ALOGD("mixer(%p) throttle end: throttle time(%u)", this, diff);
2979 mThreadThrottleEndMs = mThreadThrottleTimeMs;
2980 }
Andy Hung08fb1742015-05-31 23:22:10 -07002981 }
2982 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002983 }
Eric Laurent81784c32012-11-19 14:55:58 -08002984
Eric Laurentbfb1b832013-01-07 09:53:42 -08002985 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07002986 ATRACE_BEGIN("sleep");
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002987 usleep(mSleepTimeUs);
Glenn Kastene7754022014-10-31 12:11:26 -07002988 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002989 }
Eric Laurent81784c32012-11-19 14:55:58 -08002990 }
2991
2992 // Finally let go of removed track(s), without the lock held
2993 // since we can't guarantee the destructors won't acquire that
2994 // same lock. This will also mutate and push a new fast mixer state.
2995 threadLoop_removeTracks(tracksToRemove);
2996 tracksToRemove.clear();
2997
2998 // FIXME I don't understand the need for this here;
2999 // it was in the original code but maybe the
3000 // assignment in saveOutputTracks() makes this unnecessary?
3001 clearOutputTracks();
3002
3003 // Effect chains will be actually deleted here if they were removed from
3004 // mEffectChains list during mixing or effects processing
3005 effectChains.clear();
3006
3007 // FIXME Note that the above .clear() is no longer necessary since effectChains
3008 // is now local to this block, but will keep it for now (at least until merge done).
3009 }
3010
Eric Laurentbfb1b832013-01-07 09:53:42 -08003011 threadLoop_exit();
3012
Eric Laurentcf817a22014-08-04 20:36:31 -07003013 if (!mStandby) {
3014 threadLoop_standby();
3015 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003016 }
3017
3018 releaseWakeLock();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003019 mWakeLockUids.clear();
3020 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08003021
3022 ALOGV("Thread %p type %d exiting", this, mType);
3023 return false;
3024}
3025
Eric Laurentbfb1b832013-01-07 09:53:42 -08003026// removeTracks_l() must be called with ThreadBase::mLock held
3027void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3028{
3029 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07003030 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003031 for (size_t i=0 ; i<count ; i++) {
3032 const sp<Track>& track = tracksToRemove.itemAt(i);
3033 mActiveTracks.remove(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003034 mWakeLockUids.remove(track->uid());
3035 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003036 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
3037 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3038 if (chain != 0) {
3039 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
3040 track->sessionId());
3041 chain->decActiveTrackCnt();
3042 }
3043 if (track->isTerminated()) {
3044 removeTrack_l(track);
3045 }
3046 }
3047 }
3048
3049}
Eric Laurent81784c32012-11-19 14:55:58 -08003050
Eric Laurentaccc1472013-09-20 09:36:34 -07003051status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3052{
3053 if (mNormalSink != 0) {
3054 return mNormalSink->getTimestamp(timestamp);
3055 }
Andy Hung9a1c8892014-12-03 11:37:42 -08003056 if ((mType == OFFLOAD || mType == DIRECT)
3057 && mOutput != NULL && mOutput->stream->get_presentation_position) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003058 uint64_t position64;
Phil Burk062e67a2015-02-11 13:40:50 -08003059 int ret = mOutput->getPresentationPosition(&position64, &timestamp.mTime);
Eric Laurentaccc1472013-09-20 09:36:34 -07003060 if (ret == 0) {
3061 timestamp.mPosition = (uint32_t)position64;
3062 return NO_ERROR;
3063 }
3064 }
3065 return INVALID_OPERATION;
3066}
Eric Laurent1c333e22014-05-20 10:48:17 -07003067
Eric Laurent054d9d32015-04-24 08:48:48 -07003068status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
3069 audio_patch_handle_t *handle)
3070{
3071 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3072 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3073 if (mFastMixer != 0) {
3074 FastMixerStateQueue *sq = mFastMixer->sq();
3075 FastMixerState *state = sq->begin();
3076 if (!(state->mCommand & FastMixerState::IDLE)) {
3077 previousCommand = state->mCommand;
3078 state->mCommand = FastMixerState::HOT_IDLE;
3079 sq->end();
3080 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3081 } else {
3082 sq->end(false /*didModify*/);
3083 }
3084 }
3085 status_t status = PlaybackThread::createAudioPatch_l(patch, handle);
3086
3087 if (!(previousCommand & FastMixerState::IDLE)) {
3088 ALOG_ASSERT(mFastMixer != 0);
3089 FastMixerStateQueue *sq = mFastMixer->sq();
3090 FastMixerState *state = sq->begin();
3091 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3092 state->mCommand = previousCommand;
3093 sq->end();
3094 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3095 }
3096
3097 return status;
3098}
3099
Eric Laurent1c333e22014-05-20 10:48:17 -07003100status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3101 audio_patch_handle_t *handle)
3102{
3103 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003104
3105 // store new device and send to effects
3106 audio_devices_t type = AUDIO_DEVICE_NONE;
3107 for (unsigned int i = 0; i < patch->num_sinks; i++) {
3108 type |= patch->sinks[i].ext.device.type;
3109 }
3110
3111#ifdef ADD_BATTERY_DATA
3112 // when changing the audio output device, call addBatteryData to notify
3113 // the change
3114 if (mOutDevice != type) {
3115 uint32_t params = 0;
3116 // check whether speaker is on
3117 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3118 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003119 }
3120
Eric Laurent054d9d32015-04-24 08:48:48 -07003121 audio_devices_t deviceWithoutSpeaker
3122 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3123 // check if any other device (except speaker) is on
3124 if (type & deviceWithoutSpeaker) {
3125 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3126 }
3127
3128 if (params != 0) {
3129 addBatteryData(params);
3130 }
3131 }
3132#endif
3133
3134 for (size_t i = 0; i < mEffectChains.size(); i++) {
3135 mEffectChains[i]->setDevice_l(type);
3136 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003137
3138 // mPrevOutDevice is the latest device set by createAudioPatch_l(). It is not set when
3139 // the thread is created so that the first patch creation triggers an ioConfigChanged callback
3140 bool configChanged = mPrevOutDevice != type;
Eric Laurent054d9d32015-04-24 08:48:48 -07003141 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003142 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003143
3144 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003145 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
3146 status = hwDevice->create_audio_patch(hwDevice,
3147 patch->num_sources,
3148 patch->sources,
3149 patch->num_sinks,
3150 patch->sinks,
3151 handle);
3152 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003153 char *address;
3154 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3155 //FIXME: we only support address on first sink with HAL version < 3.0
3156 address = audio_device_address_to_parameter(
3157 patch->sinks[0].ext.device.type,
3158 patch->sinks[0].ext.device.address);
3159 } else {
3160 address = (char *)calloc(1, 1);
3161 }
3162 AudioParameter param = AudioParameter(String8(address));
3163 free(address);
3164 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), (int)type);
3165 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3166 param.toString().string());
3167 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003168 }
Eric Laurente8726fe2015-06-26 09:39:24 -07003169 if (configChanged) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003170 mPrevOutDevice = type;
Eric Laurente8726fe2015-06-26 09:39:24 -07003171 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
3172 }
Eric Laurent1c333e22014-05-20 10:48:17 -07003173 return status;
3174}
3175
Eric Laurent054d9d32015-04-24 08:48:48 -07003176status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3177{
3178 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3179 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3180 if (mFastMixer != 0) {
3181 FastMixerStateQueue *sq = mFastMixer->sq();
3182 FastMixerState *state = sq->begin();
3183 if (!(state->mCommand & FastMixerState::IDLE)) {
3184 previousCommand = state->mCommand;
3185 state->mCommand = FastMixerState::HOT_IDLE;
3186 sq->end();
3187 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3188 } else {
3189 sq->end(false /*didModify*/);
3190 }
3191 }
3192
3193 status_t status = PlaybackThread::releaseAudioPatch_l(handle);
3194
3195 if (!(previousCommand & FastMixerState::IDLE)) {
3196 ALOG_ASSERT(mFastMixer != 0);
3197 FastMixerStateQueue *sq = mFastMixer->sq();
3198 FastMixerState *state = sq->begin();
3199 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3200 state->mCommand = previousCommand;
3201 sq->end();
3202 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3203 }
3204
3205 return status;
3206}
3207
Eric Laurent1c333e22014-05-20 10:48:17 -07003208status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3209{
3210 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003211
3212 mOutDevice = AUDIO_DEVICE_NONE;
3213
Eric Laurent1c333e22014-05-20 10:48:17 -07003214 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
3215 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
3216 status = hwDevice->release_audio_patch(hwDevice, handle);
3217 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003218 AudioParameter param;
3219 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
3220 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3221 param.toString().string());
Eric Laurent1c333e22014-05-20 10:48:17 -07003222 }
3223 return status;
3224}
3225
Eric Laurent83b88082014-06-20 18:31:16 -07003226void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3227{
3228 Mutex::Autolock _l(mLock);
3229 mTracks.add(track);
3230}
3231
3232void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3233{
3234 Mutex::Autolock _l(mLock);
3235 destroyTrack_l(track);
3236}
3237
3238void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
3239{
3240 ThreadBase::getAudioPortConfig(config);
3241 config->role = AUDIO_PORT_ROLE_SOURCE;
3242 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3243 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
3244}
3245
Eric Laurent81784c32012-11-19 14:55:58 -08003246// ----------------------------------------------------------------------------
3247
3248AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurent72e3f392015-05-20 14:43:50 -07003249 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
3250 : PlaybackThread(audioFlinger, output, id, device, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08003251 // mAudioMixer below
3252 // mFastMixer below
3253 mFastMixerFutex(0)
3254 // mOutputSink below
3255 // mPipeSink below
3256 // mNormalSink below
3257{
3258 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07003259 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, "
Eric Laurent81784c32012-11-19 14:55:58 -08003260 "mFrameCount=%d, mNormalFrameCount=%d",
3261 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3262 mNormalFrameCount);
3263 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3264
Andy Hungfbfc3952015-01-15 13:33:51 -08003265 if (type == DUPLICATING) {
3266 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3267 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3268 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3269 return;
3270 }
Eric Laurent81784c32012-11-19 14:55:58 -08003271 // create an NBAIO sink for the HAL output stream, and negotiate
3272 mOutputSink = new AudioStreamOutSink(output->stream);
3273 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003274 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Eric Laurent81784c32012-11-19 14:55:58 -08003275 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
3276 ALOG_ASSERT(index == 0);
3277
3278 // initialize fast mixer depending on configuration
3279 bool initFastMixer;
3280 switch (kUseFastMixer) {
3281 case FastMixer_Never:
3282 initFastMixer = false;
3283 break;
3284 case FastMixer_Always:
3285 initFastMixer = true;
3286 break;
3287 case FastMixer_Static:
3288 case FastMixer_Dynamic:
3289 initFastMixer = mFrameCount < mNormalFrameCount;
3290 break;
3291 }
3292 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003293 audio_format_t fastMixerFormat;
3294 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3295 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3296 } else {
3297 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3298 }
3299 if (mFormat != fastMixerFormat) {
3300 // change our Sink format to accept our intermediate precision
3301 mFormat = fastMixerFormat;
3302 free(mSinkBuffer);
3303 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3304 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3305 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3306 }
Eric Laurent81784c32012-11-19 14:55:58 -08003307
3308 // create a MonoPipe to connect our submix to FastMixer
3309 NBAIO_Format format = mOutputSink->format();
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003310 NBAIO_Format origformat = format;
Andy Hung1258c1a2014-05-23 21:22:17 -07003311 // adjust format to match that of the Fast Mixer
Glenn Kasten97b7b752014-09-28 13:04:24 -07003312 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003313 format.mFormat = fastMixerFormat;
3314 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3315
Eric Laurent81784c32012-11-19 14:55:58 -08003316 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3317 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3318 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3319 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3320 const NBAIO_Format offers[1] = {format};
3321 size_t numCounterOffers = 0;
3322 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
3323 ALOG_ASSERT(index == 0);
3324 monoPipe->setAvgFrames((mScreenState & 1) ?
3325 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3326 mPipeSink = monoPipe;
3327
Glenn Kasten46909e72013-02-26 09:20:22 -08003328#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08003329 if (mTeeSinkOutputEnabled) {
3330 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003331 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
3332 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08003333 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003334 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003335 ALOG_ASSERT(index == 0);
3336 mTeeSink = teeSink;
3337 PipeReader *teeSource = new PipeReader(*teeSink);
3338 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003339 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003340 ALOG_ASSERT(index == 0);
3341 mTeeSource = teeSource;
3342 }
Glenn Kasten46909e72013-02-26 09:20:22 -08003343#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003344
3345 // create fast mixer and configure it initially with just one fast track for our submix
3346 mFastMixer = new FastMixer();
3347 FastMixerStateQueue *sq = mFastMixer->sq();
3348#ifdef STATE_QUEUE_DUMP
3349 sq->setObserverDump(&mStateQueueObserverDump);
3350 sq->setMutatorDump(&mStateQueueMutatorDump);
3351#endif
3352 FastMixerState *state = sq->begin();
3353 FastTrack *fastTrack = &state->mFastTracks[0];
3354 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3355 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3356 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003357 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3358 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003359 fastTrack->mGeneration++;
3360 state->mFastTracksGen++;
3361 state->mTrackMask = 1;
3362 // fast mixer will use the HAL output sink
3363 state->mOutputSink = mOutputSink.get();
3364 state->mOutputSinkGen++;
3365 state->mFrameCount = mFrameCount;
3366 state->mCommand = FastMixerState::COLD_IDLE;
3367 // already done in constructor initialization list
3368 //mFastMixerFutex = 0;
3369 state->mColdFutexAddr = &mFastMixerFutex;
3370 state->mColdGen++;
3371 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08003372#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003373 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08003374#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08003375 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3376 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003377 sq->end();
3378 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3379
3380 // start the fast mixer
3381 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3382 pid_t tid = mFastMixer->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003383 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003384
3385#ifdef AUDIO_WATCHDOG
3386 // create and start the watchdog
3387 mAudioWatchdog = new AudioWatchdog();
3388 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3389 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3390 tid = mAudioWatchdog->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003391 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003392#endif
3393
Eric Laurent81784c32012-11-19 14:55:58 -08003394 }
3395
3396 switch (kUseFastMixer) {
3397 case FastMixer_Never:
3398 case FastMixer_Dynamic:
3399 mNormalSink = mOutputSink;
3400 break;
3401 case FastMixer_Always:
3402 mNormalSink = mPipeSink;
3403 break;
3404 case FastMixer_Static:
3405 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3406 break;
3407 }
3408}
3409
3410AudioFlinger::MixerThread::~MixerThread()
3411{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003412 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003413 FastMixerStateQueue *sq = mFastMixer->sq();
3414 FastMixerState *state = sq->begin();
3415 if (state->mCommand == FastMixerState::COLD_IDLE) {
3416 int32_t old = android_atomic_inc(&mFastMixerFutex);
3417 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003418 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003419 }
3420 }
3421 state->mCommand = FastMixerState::EXIT;
3422 sq->end();
3423 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3424 mFastMixer->join();
3425 // Though the fast mixer thread has exited, it's state queue is still valid.
3426 // We'll use that extract the final state which contains one remaining fast track
3427 // corresponding to our sub-mix.
3428 state = sq->begin();
3429 ALOG_ASSERT(state->mTrackMask == 1);
3430 FastTrack *fastTrack = &state->mFastTracks[0];
3431 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3432 delete fastTrack->mBufferProvider;
3433 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003434 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003435#ifdef AUDIO_WATCHDOG
3436 if (mAudioWatchdog != 0) {
3437 mAudioWatchdog->requestExit();
3438 mAudioWatchdog->requestExitAndWait();
3439 mAudioWatchdog.clear();
3440 }
3441#endif
3442 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003443 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003444 delete mAudioMixer;
3445}
3446
3447
3448uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3449{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003450 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003451 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3452 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3453 }
3454 return latency;
3455}
3456
3457
3458void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3459{
3460 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3461}
3462
Eric Laurentbfb1b832013-01-07 09:53:42 -08003463ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003464{
3465 // FIXME we should only do one push per cycle; confirm this is true
3466 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003467 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003468 FastMixerStateQueue *sq = mFastMixer->sq();
3469 FastMixerState *state = sq->begin();
3470 if (state->mCommand != FastMixerState::MIX_WRITE &&
3471 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3472 if (state->mCommand == FastMixerState::COLD_IDLE) {
3473 int32_t old = android_atomic_inc(&mFastMixerFutex);
3474 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003475 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003476 }
3477#ifdef AUDIO_WATCHDOG
3478 if (mAudioWatchdog != 0) {
3479 mAudioWatchdog->resume();
3480 }
3481#endif
3482 }
3483 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08003484#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003485 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08003486 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08003487#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003488 sq->end();
3489 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3490 if (kUseFastMixer == FastMixer_Dynamic) {
3491 mNormalSink = mPipeSink;
3492 }
3493 } else {
3494 sq->end(false /*didModify*/);
3495 }
3496 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003497 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003498}
3499
3500void AudioFlinger::MixerThread::threadLoop_standby()
3501{
3502 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003503 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003504 FastMixerStateQueue *sq = mFastMixer->sq();
3505 FastMixerState *state = sq->begin();
3506 if (!(state->mCommand & FastMixerState::IDLE)) {
3507 state->mCommand = FastMixerState::COLD_IDLE;
3508 state->mColdFutexAddr = &mFastMixerFutex;
3509 state->mColdGen++;
3510 mFastMixerFutex = 0;
3511 sq->end();
3512 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3513 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3514 if (kUseFastMixer == FastMixer_Dynamic) {
3515 mNormalSink = mOutputSink;
3516 }
3517#ifdef AUDIO_WATCHDOG
3518 if (mAudioWatchdog != 0) {
3519 mAudioWatchdog->pause();
3520 }
3521#endif
3522 } else {
3523 sq->end(false /*didModify*/);
3524 }
3525 }
3526 PlaybackThread::threadLoop_standby();
3527}
3528
Eric Laurentbfb1b832013-01-07 09:53:42 -08003529bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3530{
3531 return false;
3532}
3533
3534bool AudioFlinger::PlaybackThread::shouldStandby_l()
3535{
3536 return !mStandby;
3537}
3538
3539bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3540{
3541 Mutex::Autolock _l(mLock);
3542 return waitingAsyncCallback_l();
3543}
3544
Eric Laurent81784c32012-11-19 14:55:58 -08003545// shared by MIXER and DIRECT, overridden by DUPLICATING
3546void AudioFlinger::PlaybackThread::threadLoop_standby()
3547{
3548 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08003549 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003550 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003551 // discard any pending drain or write ack by incrementing sequence
3552 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3553 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003554 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003555 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3556 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003557 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003558 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003559}
3560
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003561void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3562{
3563 ALOGV("signal playback thread");
3564 broadcast_l();
3565}
3566
Eric Laurent81784c32012-11-19 14:55:58 -08003567void AudioFlinger::MixerThread::threadLoop_mix()
3568{
3569 // obtain the presentation timestamp of the next output buffer
3570 int64_t pts;
3571 status_t status = INVALID_OPERATION;
3572
3573 if (mNormalSink != 0) {
3574 status = mNormalSink->getNextWriteTimestamp(&pts);
3575 } else {
3576 status = mOutputSink->getNextWriteTimestamp(&pts);
3577 }
3578
3579 if (status != NO_ERROR) {
3580 pts = AudioBufferProvider::kInvalidPTS;
3581 }
3582
3583 // mix buffers...
3584 mAudioMixer->process(pts);
Andy Hung25c2dac2014-02-27 14:56:00 -08003585 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003586 // increase sleep time progressively when application underrun condition clears.
3587 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3588 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3589 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003590 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003591 sleepTimeShift--;
3592 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003593 mSleepTimeUs = 0;
3594 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08003595 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003596
Eric Laurent81784c32012-11-19 14:55:58 -08003597}
3598
3599void AudioFlinger::MixerThread::threadLoop_sleepTime()
3600{
3601 // If no tracks are ready, sleep once for the duration of an output
3602 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003603 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003604 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003605 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
3606 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
3607 mSleepTimeUs = kMinThreadSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003608 }
3609 // reduce sleep time in case of consecutive application underruns to avoid
3610 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3611 // duration we would end up writing less data than needed by the audio HAL if
3612 // the condition persists.
3613 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3614 sleepTimeShift++;
3615 }
3616 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003617 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003618 }
3619 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003620 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3621 // before effects processing or output.
3622 if (mMixerBufferValid) {
3623 memset(mMixerBuffer, 0, mMixerBufferSize);
3624 } else {
3625 memset(mSinkBuffer, 0, mSinkBufferSize);
3626 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003627 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003628 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3629 "anticipated start");
3630 }
3631 // TODO add standby time extension fct of effect tail
3632}
3633
3634// prepareTracks_l() must be called with ThreadBase::mLock held
3635AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3636 Vector< sp<Track> > *tracksToRemove)
3637{
3638
3639 mixer_state mixerStatus = MIXER_IDLE;
3640 // find out which tracks need to be processed
3641 size_t count = mActiveTracks.size();
3642 size_t mixedTracks = 0;
3643 size_t tracksWithEffect = 0;
3644 // counts only _active_ fast tracks
3645 size_t fastTracks = 0;
3646 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
3647
3648 float masterVolume = mMasterVolume;
3649 bool masterMute = mMasterMute;
3650
3651 if (masterMute) {
3652 masterVolume = 0;
3653 }
3654 // Delegate master volume control to effect in output mix effect chain if needed
3655 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3656 if (chain != 0) {
3657 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
3658 chain->setVolume_l(&v, &v);
3659 masterVolume = (float)((v + (1 << 23)) >> 24);
3660 chain.clear();
3661 }
3662
3663 // prepare a new state to push
3664 FastMixerStateQueue *sq = NULL;
3665 FastMixerState *state = NULL;
3666 bool didModify = false;
3667 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003668 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003669 sq = mFastMixer->sq();
3670 state = sq->begin();
3671 }
3672
Andy Hung69aed5f2014-02-25 17:24:40 -08003673 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08003674 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08003675
Eric Laurent81784c32012-11-19 14:55:58 -08003676 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003677 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003678 if (t == 0) {
3679 continue;
3680 }
3681
3682 // this const just means the local variable doesn't change
3683 Track* const track = t.get();
3684
3685 // process fast tracks
3686 if (track->isFastTrack()) {
3687
3688 // It's theoretically possible (though unlikely) for a fast track to be created
3689 // and then removed within the same normal mix cycle. This is not a problem, as
3690 // the track never becomes active so it's fast mixer slot is never touched.
3691 // The converse, of removing an (active) track and then creating a new track
3692 // at the identical fast mixer slot within the same normal mix cycle,
3693 // is impossible because the slot isn't marked available until the end of each cycle.
3694 int j = track->mFastIndex;
3695 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
3696 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
3697 FastTrack *fastTrack = &state->mFastTracks[j];
3698
3699 // Determine whether the track is currently in underrun condition,
3700 // and whether it had a recent underrun.
3701 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
3702 FastTrackUnderruns underruns = ftDump->mUnderruns;
3703 uint32_t recentFull = (underruns.mBitFields.mFull -
3704 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
3705 uint32_t recentPartial = (underruns.mBitFields.mPartial -
3706 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
3707 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
3708 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
3709 uint32_t recentUnderruns = recentPartial + recentEmpty;
3710 track->mObservedUnderruns = underruns;
3711 // don't count underruns that occur while stopping or pausing
3712 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07003713 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
3714 recentUnderruns > 0) {
3715 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
3716 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003717 }
3718
3719 // This is similar to the state machine for normal tracks,
3720 // with a few modifications for fast tracks.
3721 bool isActive = true;
3722 switch (track->mState) {
3723 case TrackBase::STOPPING_1:
3724 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08003725 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003726 track->mState = TrackBase::STOPPING_2;
3727 }
3728 break;
3729 case TrackBase::PAUSING:
3730 // ramp down is not yet implemented
3731 track->setPaused();
3732 break;
3733 case TrackBase::RESUMING:
3734 // ramp up is not yet implemented
3735 track->mState = TrackBase::ACTIVE;
3736 break;
3737 case TrackBase::ACTIVE:
3738 if (recentFull > 0 || recentPartial > 0) {
3739 // track has provided at least some frames recently: reset retry count
3740 track->mRetryCount = kMaxTrackRetries;
3741 }
3742 if (recentUnderruns == 0) {
3743 // no recent underruns: stay active
3744 break;
3745 }
3746 // there has recently been an underrun of some kind
3747 if (track->sharedBuffer() == 0) {
3748 // were any of the recent underruns "empty" (no frames available)?
3749 if (recentEmpty == 0) {
3750 // no, then ignore the partial underruns as they are allowed indefinitely
3751 break;
3752 }
3753 // there has recently been an "empty" underrun: decrement the retry counter
3754 if (--(track->mRetryCount) > 0) {
3755 break;
3756 }
3757 // indicate to client process that the track was disabled because of underrun;
3758 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003759 android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003760 // remove from active list, but state remains ACTIVE [confusing but true]
3761 isActive = false;
3762 break;
3763 }
3764 // fall through
3765 case TrackBase::STOPPING_2:
3766 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003767 case TrackBase::STOPPED:
3768 case TrackBase::FLUSHED: // flush() while active
3769 // Check for presentation complete if track is inactive
3770 // We have consumed all the buffers of this track.
3771 // This would be incomplete if we auto-paused on underrun
3772 {
3773 size_t audioHALFrames =
3774 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3775 size_t framesWritten = mBytesWritten / mFrameSize;
3776 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
3777 // track stays in active list until presentation is complete
3778 break;
3779 }
3780 }
3781 if (track->isStopping_2()) {
3782 track->mState = TrackBase::STOPPED;
3783 }
3784 if (track->isStopped()) {
3785 // Can't reset directly, as fast mixer is still polling this track
3786 // track->reset();
3787 // So instead mark this track as needing to be reset after push with ack
3788 resetMask |= 1 << i;
3789 }
3790 isActive = false;
3791 break;
3792 case TrackBase::IDLE:
3793 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08003794 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08003795 }
3796
3797 if (isActive) {
3798 // was it previously inactive?
3799 if (!(state->mTrackMask & (1 << j))) {
3800 ExtendedAudioBufferProvider *eabp = track;
3801 VolumeProvider *vp = track;
3802 fastTrack->mBufferProvider = eabp;
3803 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08003804 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003805 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08003806 fastTrack->mGeneration++;
3807 state->mTrackMask |= 1 << j;
3808 didModify = true;
3809 // no acknowledgement required for newly active tracks
3810 }
3811 // cache the combined master volume and stream type volume for fast mixer; this
3812 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08003813 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08003814 ++fastTracks;
3815 } else {
3816 // was it previously active?
3817 if (state->mTrackMask & (1 << j)) {
3818 fastTrack->mBufferProvider = NULL;
3819 fastTrack->mGeneration++;
3820 state->mTrackMask &= ~(1 << j);
3821 didModify = true;
3822 // If any fast tracks were removed, we must wait for acknowledgement
3823 // because we're about to decrement the last sp<> on those tracks.
3824 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3825 } else {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003826 LOG_ALWAYS_FATAL("fast track %d should have been active", j);
Eric Laurent81784c32012-11-19 14:55:58 -08003827 }
3828 tracksToRemove->add(track);
3829 // Avoids a misleading display in dumpsys
3830 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
3831 }
3832 continue;
3833 }
3834
3835 { // local variable scope to avoid goto warning
3836
3837 audio_track_cblk_t* cblk = track->cblk();
3838
3839 // The first time a track is added we wait
3840 // for all its buffers to be filled before processing it
3841 int name = track->name();
3842 // make sure that we have enough frames to mix one full buffer.
3843 // enforce this condition only once to enable draining the buffer in case the client
3844 // app does not call stop() and relies on underrun to stop:
3845 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
3846 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003847 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07003848 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07003849 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07003850
3851 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07003852 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07003853 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
3854 // add frames already consumed but not yet released by the resampler
3855 // because mAudioTrackServerProxy->framesReady() will include these frames
3856 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
3857
Eric Laurent81784c32012-11-19 14:55:58 -08003858 uint32_t minFrames = 1;
3859 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
3860 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003861 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08003862 }
Eric Laurent13e4c962013-12-20 17:36:01 -08003863
3864 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07003865 if (ATRACE_ENABLED()) {
3866 // I wish we had formatted trace names
3867 char traceName[16];
3868 strcpy(traceName, "nRdy");
3869 int name = track->name();
3870 if (AudioMixer::TRACK0 <= name &&
3871 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
3872 name -= AudioMixer::TRACK0;
3873 traceName[4] = (name / 10) + '0';
3874 traceName[5] = (name % 10) + '0';
3875 } else {
3876 traceName[4] = '?';
3877 traceName[5] = '?';
3878 }
3879 traceName[6] = '\0';
3880 ATRACE_INT(traceName, framesReady);
3881 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003882 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08003883 !track->isPaused() && !track->isTerminated())
3884 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003885 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003886
3887 mixedTracks++;
3888
Andy Hung69aed5f2014-02-25 17:24:40 -08003889 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
3890 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08003891 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08003892 if (track->mainBuffer() != mSinkBuffer &&
3893 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08003894 if (mEffectBufferEnabled) {
3895 mEffectBufferValid = true; // Later can set directly.
3896 }
Eric Laurent81784c32012-11-19 14:55:58 -08003897 chain = getEffectChain_l(track->sessionId());
3898 // Delegate volume control to effect in track effect chain if needed
3899 if (chain != 0) {
3900 tracksWithEffect++;
3901 } else {
3902 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
3903 "session %d",
3904 name, track->sessionId());
3905 }
3906 }
3907
3908
3909 int param = AudioMixer::VOLUME;
3910 if (track->mFillingUpStatus == Track::FS_FILLED) {
3911 // no ramp for the first volume setting
3912 track->mFillingUpStatus = Track::FS_ACTIVE;
3913 if (track->mState == TrackBase::RESUMING) {
3914 track->mState = TrackBase::ACTIVE;
3915 param = AudioMixer::RAMP_VOLUME;
3916 }
3917 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003918 // FIXME should not make a decision based on mServer
3919 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003920 // If the track is stopped before the first frame was mixed,
3921 // do not apply ramp
3922 param = AudioMixer::RAMP_VOLUME;
3923 }
3924
3925 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07003926 uint32_t vl, vr; // in U8.24 integer format
3927 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08003928 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07003929 vl = vr = 0;
3930 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08003931 if (track->isPausing()) {
3932 track->setPaused();
3933 }
3934 } else {
3935
3936 // read original volumes with volume control
3937 float typeVolume = mStreamTypes[track->streamType()].volume;
3938 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003939 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07003940 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07003941 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
3942 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08003943 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07003944 if (vlf > GAIN_FLOAT_UNITY) {
3945 ALOGV("Track left volume out of range: %.3g", vlf);
3946 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003947 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07003948 if (vrf > GAIN_FLOAT_UNITY) {
3949 ALOGV("Track right volume out of range: %.3g", vrf);
3950 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003951 }
3952 // now apply the master volume and stream type volume
Andy Hung6be49402014-05-30 10:42:03 -07003953 vlf *= v;
3954 vrf *= v;
Eric Laurent81784c32012-11-19 14:55:58 -08003955 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07003956 // then derive vl and vr as U8.24 versions for the effect chain
3957 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
3958 vl = (uint32_t) (scaleto8_24 * vlf);
3959 vr = (uint32_t) (scaleto8_24 * vrf);
3960 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08003961 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08003962 // send level comes from shared memory and so may be corrupt
3963 if (sendLevel > MAX_GAIN_INT) {
3964 ALOGV("Track send level out of range: %04X", sendLevel);
3965 sendLevel = MAX_GAIN_INT;
3966 }
Andy Hung6be49402014-05-30 10:42:03 -07003967 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
3968 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08003969 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003970
Eric Laurent81784c32012-11-19 14:55:58 -08003971 // Delegate volume control to effect in track effect chain if needed
3972 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3973 // Do not ramp volume if volume is controlled by effect
3974 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08003975 // Update remaining floating point volume levels
3976 vlf = (float)vl / (1 << 24);
3977 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08003978 track->mHasVolumeController = true;
3979 } else {
3980 // force no volume ramp when volume controller was just disabled or removed
3981 // from effect chain to avoid volume spike
3982 if (track->mHasVolumeController) {
3983 param = AudioMixer::VOLUME;
3984 }
3985 track->mHasVolumeController = false;
3986 }
3987
Eric Laurent81784c32012-11-19 14:55:58 -08003988 // XXX: these things DON'T need to be done each time
3989 mAudioMixer->setBufferProvider(name, track);
3990 mAudioMixer->enable(name);
3991
Andy Hung6be49402014-05-30 10:42:03 -07003992 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
3993 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
3994 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08003995 mAudioMixer->setParameter(
3996 name,
3997 AudioMixer::TRACK,
3998 AudioMixer::FORMAT, (void *)track->format());
3999 mAudioMixer->setParameter(
4000 name,
4001 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004002 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07004003 mAudioMixer->setParameter(
4004 name,
4005 AudioMixer::TRACK,
4006 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08004007 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07004008 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004009 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08004010 if (reqSampleRate == 0) {
4011 reqSampleRate = mSampleRate;
4012 } else if (reqSampleRate > maxSampleRate) {
4013 reqSampleRate = maxSampleRate;
4014 }
Eric Laurent81784c32012-11-19 14:55:58 -08004015 mAudioMixer->setParameter(
4016 name,
4017 AudioMixer::RESAMPLE,
4018 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004019 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004020
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004021 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004022 mAudioMixer->setParameter(
4023 name,
4024 AudioMixer::TIMESTRETCH,
4025 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004026 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004027
Andy Hung69aed5f2014-02-25 17:24:40 -08004028 /*
4029 * Select the appropriate output buffer for the track.
4030 *
Andy Hung98ef9782014-03-04 14:46:50 -08004031 * Tracks with effects go into their own effects chain buffer
4032 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08004033 *
4034 * Other tracks can use mMixerBuffer for higher precision
4035 * channel accumulation. If this buffer is enabled
4036 * (mMixerBufferEnabled true), then selected tracks will accumulate
4037 * into it.
4038 *
4039 */
4040 if (mMixerBufferEnabled
4041 && (track->mainBuffer() == mSinkBuffer
4042 || track->mainBuffer() == mMixerBuffer)) {
4043 mAudioMixer->setParameter(
4044 name,
4045 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004046 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08004047 mAudioMixer->setParameter(
4048 name,
4049 AudioMixer::TRACK,
4050 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
4051 // TODO: override track->mainBuffer()?
4052 mMixerBufferValid = true;
4053 } else {
4054 mAudioMixer->setParameter(
4055 name,
4056 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004057 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08004058 mAudioMixer->setParameter(
4059 name,
4060 AudioMixer::TRACK,
4061 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
4062 }
Eric Laurent81784c32012-11-19 14:55:58 -08004063 mAudioMixer->setParameter(
4064 name,
4065 AudioMixer::TRACK,
4066 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
4067
4068 // reset retry count
4069 track->mRetryCount = kMaxTrackRetries;
4070
4071 // If one track is ready, set the mixer ready if:
4072 // - the mixer was not ready during previous round OR
4073 // - no other track is not ready
4074 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
4075 mixerStatus != MIXER_TRACKS_ENABLED) {
4076 mixerStatus = MIXER_TRACKS_READY;
4077 }
4078 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004079 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hung08fb1742015-05-31 23:22:10 -07004080 ALOGV("track(%p) underrun, framesReady(%zu) < framesDesired(%zd)",
4081 track, framesReady, desiredFrames);
Glenn Kasten82aaf942013-07-17 16:05:07 -07004082 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004083 }
Eric Laurent81784c32012-11-19 14:55:58 -08004084 // clear effect chain input buffer if an active track underruns to avoid sending
4085 // previous audio buffer again to effects
4086 chain = getEffectChain_l(track->sessionId());
4087 if (chain != 0) {
4088 chain->clearInputBuffer();
4089 }
4090
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004091 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004092 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
4093 track->isStopped() || track->isPaused()) {
4094 // We have consumed all the buffers of this track.
4095 // Remove it from the list of active tracks.
4096 // TODO: use actual buffer filling status instead of latency when available from
4097 // audio HAL
4098 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
4099 size_t framesWritten = mBytesWritten / mFrameSize;
4100 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
4101 if (track->isStopped()) {
4102 track->reset();
4103 }
4104 tracksToRemove->add(track);
4105 }
4106 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08004107 // No buffers for this track. Give it a few chances to
4108 // fill a buffer, then remove it from active list.
4109 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004110 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004111 tracksToRemove->add(track);
4112 // indicate to client process that the track was disabled because of underrun;
4113 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07004114 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08004115 // If one track is not ready, mark the mixer also not ready if:
4116 // - the mixer was ready during previous round OR
4117 // - no other track is ready
4118 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
4119 mixerStatus != MIXER_TRACKS_READY) {
4120 mixerStatus = MIXER_TRACKS_ENABLED;
4121 }
4122 }
4123 mAudioMixer->disable(name);
4124 }
4125
4126 } // local variable scope to avoid goto warning
4127track_is_ready: ;
4128
4129 }
4130
4131 // Push the new FastMixer state if necessary
4132 bool pauseAudioWatchdog = false;
4133 if (didModify) {
4134 state->mFastTracksGen++;
4135 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4136 if (kUseFastMixer == FastMixer_Dynamic &&
4137 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4138 state->mCommand = FastMixerState::COLD_IDLE;
4139 state->mColdFutexAddr = &mFastMixerFutex;
4140 state->mColdGen++;
4141 mFastMixerFutex = 0;
4142 if (kUseFastMixer == FastMixer_Dynamic) {
4143 mNormalSink = mOutputSink;
4144 }
4145 // If we go into cold idle, need to wait for acknowledgement
4146 // so that fast mixer stops doing I/O.
4147 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4148 pauseAudioWatchdog = true;
4149 }
Eric Laurent81784c32012-11-19 14:55:58 -08004150 }
4151 if (sq != NULL) {
4152 sq->end(didModify);
4153 sq->push(block);
4154 }
4155#ifdef AUDIO_WATCHDOG
4156 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4157 mAudioWatchdog->pause();
4158 }
4159#endif
4160
4161 // Now perform the deferred reset on fast tracks that have stopped
4162 while (resetMask != 0) {
4163 size_t i = __builtin_ctz(resetMask);
4164 ALOG_ASSERT(i < count);
4165 resetMask &= ~(1 << i);
4166 sp<Track> t = mActiveTracks[i].promote();
4167 if (t == 0) {
4168 continue;
4169 }
4170 Track* track = t.get();
4171 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
4172 track->reset();
4173 }
4174
4175 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004176 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004177
Eric Laurent97d547d2014-09-02 14:45:53 -07004178 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
4179 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07004180 }
4181
4182 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07004183 // as long as there are effects we should clear the effects buffer, to avoid
4184 // passing a non-clean buffer to the effect chain
4185 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07004186 }
Andy Hung69aed5f2014-02-25 17:24:40 -08004187 // sink or mix buffer must be cleared if all tracks are connected to an
4188 // effect chain as in this case the mixer will not write to the sink or mix buffer
4189 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08004190 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4191 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08004192 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08004193 if (mMixerBufferValid) {
4194 memset(mMixerBuffer, 0, mMixerBufferSize);
4195 // TODO: In testing, mSinkBuffer below need not be cleared because
4196 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
4197 // after mixing.
4198 //
4199 // To enforce this guarantee:
4200 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4201 // (mixedTracks == 0 && fastTracks > 0))
4202 // must imply MIXER_TRACKS_READY.
4203 // Later, we may clear buffers regardless, and skip much of this logic.
4204 }
Andy Hung98ef9782014-03-04 14:46:50 -08004205 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07004206 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004207 }
4208
4209 // if any fast tracks, then status is ready
4210 mMixerStatusIgnoringFastTracks = mixerStatus;
4211 if (fastTracks > 0) {
4212 mixerStatus = MIXER_TRACKS_READY;
4213 }
4214 return mixerStatus;
4215}
4216
4217// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07004218int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
4219 audio_format_t format, int sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08004220{
Andy Hunge8a1ced2014-05-09 15:02:21 -07004221 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08004222}
4223
4224// deleteTrackName_l() must be called with ThreadBase::mLock held
4225void AudioFlinger::MixerThread::deleteTrackName_l(int name)
4226{
4227 ALOGV("remove track (%d) and delete from mixer", name);
4228 mAudioMixer->deleteTrackName(name);
4229}
4230
Eric Laurent10351942014-05-08 18:49:52 -07004231// checkForNewParameter_l() must be called with ThreadBase::mLock held
4232bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
4233 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004234{
Eric Laurent81784c32012-11-19 14:55:58 -08004235 bool reconfig = false;
4236
Eric Laurent10351942014-05-08 18:49:52 -07004237 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004238
Eric Laurent10351942014-05-08 18:49:52 -07004239 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
4240 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004241 if (mFastMixer != 0) {
Eric Laurent10351942014-05-08 18:49:52 -07004242 FastMixerStateQueue *sq = mFastMixer->sq();
4243 FastMixerState *state = sq->begin();
4244 if (!(state->mCommand & FastMixerState::IDLE)) {
4245 previousCommand = state->mCommand;
4246 state->mCommand = FastMixerState::HOT_IDLE;
4247 sq->end();
4248 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
4249 } else {
4250 sq->end(false /*didModify*/);
Eric Laurent81784c32012-11-19 14:55:58 -08004251 }
Eric Laurent10351942014-05-08 18:49:52 -07004252 }
Eric Laurent81784c32012-11-19 14:55:58 -08004253
Eric Laurent10351942014-05-08 18:49:52 -07004254 AudioParameter param = AudioParameter(keyValuePair);
4255 int value;
4256 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4257 reconfig = true;
4258 }
4259 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004260 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004261 status = BAD_VALUE;
4262 } else {
4263 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08004264 reconfig = true;
4265 }
Eric Laurent10351942014-05-08 18:49:52 -07004266 }
4267 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004268 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004269 status = BAD_VALUE;
4270 } else {
4271 // no need to save value, since it's constant
4272 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004273 }
Eric Laurent10351942014-05-08 18:49:52 -07004274 }
4275 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4276 // do not accept frame count changes if tracks are open as the track buffer
4277 // size depends on frame count and correct behavior would not be guaranteed
4278 // if frame count is changed after track creation
4279 if (!mTracks.isEmpty()) {
4280 status = INVALID_OPERATION;
4281 } else {
4282 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004283 }
Eric Laurent10351942014-05-08 18:49:52 -07004284 }
4285 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004286#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07004287 // when changing the audio output device, call addBatteryData to notify
4288 // the change
4289 if (mOutDevice != value) {
4290 uint32_t params = 0;
4291 // check whether speaker is on
4292 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
4293 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08004294 }
Eric Laurent10351942014-05-08 18:49:52 -07004295
4296 audio_devices_t deviceWithoutSpeaker
4297 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
4298 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07004299 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07004300 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4301 }
4302
4303 if (params != 0) {
4304 addBatteryData(params);
4305 }
4306 }
Eric Laurent81784c32012-11-19 14:55:58 -08004307#endif
4308
Eric Laurent10351942014-05-08 18:49:52 -07004309 // forward device change to effects that have requested to be
4310 // aware of attached audio device.
4311 if (value != AUDIO_DEVICE_NONE) {
4312 mOutDevice = value;
4313 for (size_t i = 0; i < mEffectChains.size(); i++) {
4314 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08004315 }
4316 }
Eric Laurent10351942014-05-08 18:49:52 -07004317 }
Eric Laurent81784c32012-11-19 14:55:58 -08004318
Eric Laurent10351942014-05-08 18:49:52 -07004319 if (status == NO_ERROR) {
4320 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4321 keyValuePair.string());
4322 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004323 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004324 mStandby = true;
4325 mBytesWritten = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004326 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Eric Laurent10351942014-05-08 18:49:52 -07004327 keyValuePair.string());
Eric Laurent81784c32012-11-19 14:55:58 -08004328 }
Eric Laurent10351942014-05-08 18:49:52 -07004329 if (status == NO_ERROR && reconfig) {
4330 readOutputParameters_l();
4331 delete mAudioMixer;
4332 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4333 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07004334 int name = getTrackName_l(mTracks[i]->mChannelMask,
4335 mTracks[i]->mFormat, mTracks[i]->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07004336 if (name < 0) {
4337 break;
4338 }
4339 mTracks[i]->mName = name;
4340 }
Eric Laurent73e26b62015-04-27 16:55:58 -07004341 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004342 }
Eric Laurent81784c32012-11-19 14:55:58 -08004343 }
4344
4345 if (!(previousCommand & FastMixerState::IDLE)) {
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004346 ALOG_ASSERT(mFastMixer != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08004347 FastMixerStateQueue *sq = mFastMixer->sq();
4348 FastMixerState *state = sq->begin();
4349 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
4350 state->mCommand = previousCommand;
4351 sq->end();
4352 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4353 }
4354
4355 return reconfig;
4356}
4357
4358
4359void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
4360{
4361 const size_t SIZE = 256;
4362 char buffer[SIZE];
4363 String8 result;
4364
4365 PlaybackThread::dumpInternals(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07004366 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Elliott Hughes87cebad2014-05-22 10:14:43 -07004367 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Eric Laurent81784c32012-11-19 14:55:58 -08004368
4369 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten4182c4e2013-07-15 14:45:07 -07004370 const FastMixerDumpState copy(mFastMixerDumpState);
Eric Laurent81784c32012-11-19 14:55:58 -08004371 copy.dump(fd);
4372
4373#ifdef STATE_QUEUE_DUMP
4374 // Similar for state queue
4375 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4376 observerCopy.dump(fd);
4377 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4378 mutatorCopy.dump(fd);
4379#endif
4380
Glenn Kasten46909e72013-02-26 09:20:22 -08004381#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08004382 // Write the tee output to a .wav file
4383 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08004384#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004385
4386#ifdef AUDIO_WATCHDOG
4387 if (mAudioWatchdog != 0) {
4388 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4389 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4390 wdCopy.dump(fd);
4391 }
4392#endif
4393}
4394
4395uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4396{
4397 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4398}
4399
4400uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4401{
4402 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4403}
4404
4405void AudioFlinger::MixerThread::cacheParameters_l()
4406{
4407 PlaybackThread::cacheParameters_l();
4408
4409 // FIXME: Relaxed timing because of a certain device that can't meet latency
4410 // Should be reduced to 2x after the vendor fixes the driver issue
4411 // increase threshold again due to low power audio mode. The way this warning
4412 // threshold is calculated and its usefulness should be reconsidered anyway.
4413 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4414}
4415
4416// ----------------------------------------------------------------------------
4417
4418AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07004419 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device, bool systemReady)
4420 : PlaybackThread(audioFlinger, output, id, device, DIRECT, systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08004421 // mLeftVolFloat, mRightVolFloat
4422{
4423}
4424
Eric Laurentbfb1b832013-01-07 09:53:42 -08004425AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4426 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07004427 ThreadBase::type_t type, bool systemReady)
4428 : PlaybackThread(audioFlinger, output, id, device, type, systemReady)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004429 // mLeftVolFloat, mRightVolFloat
4430{
4431}
4432
Eric Laurent81784c32012-11-19 14:55:58 -08004433AudioFlinger::DirectOutputThread::~DirectOutputThread()
4434{
4435}
4436
Eric Laurentbfb1b832013-01-07 09:53:42 -08004437void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
4438{
4439 audio_track_cblk_t* cblk = track->cblk();
4440 float left, right;
4441
4442 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4443 left = right = 0;
4444 } else {
4445 float typeVolume = mStreamTypes[track->streamType()].volume;
4446 float v = mMasterVolume * typeVolume;
4447 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004448 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4449 left = float_from_gain(gain_minifloat_unpack_left(vlr));
4450 if (left > GAIN_FLOAT_UNITY) {
4451 left = GAIN_FLOAT_UNITY;
4452 }
4453 left *= v;
4454 right = float_from_gain(gain_minifloat_unpack_right(vlr));
4455 if (right > GAIN_FLOAT_UNITY) {
4456 right = GAIN_FLOAT_UNITY;
4457 }
4458 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004459 }
4460
4461 if (lastTrack) {
4462 if (left != mLeftVolFloat || right != mRightVolFloat) {
4463 mLeftVolFloat = left;
4464 mRightVolFloat = right;
4465
4466 // Convert volumes from float to 8.24
4467 uint32_t vl = (uint32_t)(left * (1 << 24));
4468 uint32_t vr = (uint32_t)(right * (1 << 24));
4469
4470 // Delegate volume control to effect in track effect chain if needed
4471 // only one effect chain can be present on DirectOutputThread, so if
4472 // there is one, the track is connected to it
4473 if (!mEffectChains.isEmpty()) {
4474 mEffectChains[0]->setVolume_l(&vl, &vr);
4475 left = (float)vl / (1 << 24);
4476 right = (float)vr / (1 << 24);
4477 }
4478 if (mOutput->stream->set_volume) {
4479 mOutput->stream->set_volume(mOutput->stream, left, right);
4480 }
4481 }
4482 }
4483}
4484
Phil Burk43b4dcc2015-06-09 16:53:44 -07004485void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
4486{
4487 sp<Track> previousTrack = mPreviousTrack.promote();
4488 sp<Track> latestTrack = mLatestActiveTrack.promote();
4489
Eric Laurent0f0631e2015-07-06 18:01:25 -07004490 if (previousTrack != 0 && latestTrack != 0) {
4491 if (mType == DIRECT) {
4492 if (previousTrack.get() != latestTrack.get()) {
4493 mFlushPending = true;
4494 }
4495 } else /* mType == OFFLOAD */ {
4496 if (previousTrack->sessionId() != latestTrack->sessionId()) {
4497 mFlushPending = true;
4498 }
4499 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004500 }
4501 PlaybackThread::onAddNewTrack_l();
4502}
Eric Laurentbfb1b832013-01-07 09:53:42 -08004503
Eric Laurent81784c32012-11-19 14:55:58 -08004504AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4505 Vector< sp<Track> > *tracksToRemove
4506)
4507{
Eric Laurentd595b7c2013-04-03 17:27:56 -07004508 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08004509 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004510 bool doHwPause = false;
4511 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004512
4513 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07004514 for (size_t i = 0; i < count; i++) {
4515 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08004516 // The track died recently
4517 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004518 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08004519 }
4520
Phil Burk43b4dcc2015-06-09 16:53:44 -07004521 if (t->isInvalid()) {
4522 ALOGW("An invalidated track shouldn't be in active list");
4523 tracksToRemove->add(t);
4524 continue;
4525 }
4526
Eric Laurent81784c32012-11-19 14:55:58 -08004527 Track* const track = t.get();
4528 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07004529 // Only consider last track started for volume and mixer state control.
4530 // In theory an older track could underrun and restart after the new one starts
4531 // but as we only care about the transition phase between two tracks on a
4532 // direct output, it is not a problem to ignore the underrun case.
4533 sp<Track> l = mLatestActiveTrack.promote();
4534 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08004535
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004536 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004537 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004538 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004539 doHwPause = true;
4540 mHwPaused = true;
4541 }
4542 tracksToRemove->add(track);
4543 } else if (track->isFlushPending()) {
4544 track->flushAck();
4545 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004546 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004547 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004548 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004549 track->resumeAck();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004550 if (last && mHwPaused) {
4551 doHwResume = true;
4552 mHwPaused = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004553 }
4554 }
4555
Eric Laurent81784c32012-11-19 14:55:58 -08004556 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08004557 // for all its buffers to be filled before processing it.
4558 // Allow draining the buffer in case the client
4559 // app does not call stop() and relies on underrun to stop:
4560 // hence the test on (track->mRetryCount > 1).
4561 // If retryCount<=1 then track is about to underrun and be removed.
Eric Laurent81784c32012-11-19 14:55:58 -08004562 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08004563 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
4564 && (track->mRetryCount > 1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004565 minFrames = mNormalFrameCount;
4566 } else {
4567 minFrames = 1;
4568 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004569
Eric Laurentab5cdba2014-06-09 17:22:27 -07004570 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4571 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08004572 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004573 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08004574
4575 if (track->mFillingUpStatus == Track::FS_FILLED) {
4576 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004577 // make sure processVolume_l() will apply new volume even if 0
4578 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004579 if (!mHwSupportsPause) {
4580 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08004581 }
4582 }
4583
4584 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004585 processVolume_l(track, last);
4586 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004587 sp<Track> previousTrack = mPreviousTrack.promote();
4588 if (previousTrack != 0) {
4589 if (track != previousTrack.get()) {
4590 // Flush any data still being written from last track
4591 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07004592 // Invalidate previous track to force a seek when resuming.
4593 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004594 }
4595 }
4596 mPreviousTrack = track;
4597
Eric Laurentd595b7c2013-04-03 17:27:56 -07004598 // reset retry count
4599 track->mRetryCount = kMaxTrackRetriesDirect;
4600 mActiveTrack = t;
4601 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07004602 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004603 doHwResume = true;
4604 mHwPaused = false;
4605 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004606 }
Eric Laurent81784c32012-11-19 14:55:58 -08004607 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004608 // clear effect chain input buffer if the last active track started underruns
4609 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07004610 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004611 mEffectChains[0]->clearInputBuffer();
4612 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004613 if (track->isStopping_1()) {
4614 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07004615 if (last && mHwPaused) {
4616 doHwResume = true;
4617 mHwPaused = false;
4618 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004619 }
4620 if ((track->sharedBuffer() != 0) || track->isStopped() ||
4621 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004622 // We have consumed all the buffers of this track.
4623 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07004624 size_t audioHALFrames;
4625 if (audio_is_linear_pcm(mFormat)) {
4626 audioHALFrames = (latency_l() * mSampleRate) / 1000;
4627 } else {
4628 audioHALFrames = 0;
4629 }
4630
Eric Laurent81784c32012-11-19 14:55:58 -08004631 size_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07004632 if (mStandby || !last ||
4633 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004634 if (track->isStopping_2()) {
4635 track->mState = TrackBase::STOPPED;
4636 }
Eric Laurent81784c32012-11-19 14:55:58 -08004637 if (track->isStopped()) {
4638 track->reset();
4639 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004640 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08004641 }
4642 } else {
4643 // No buffers for this track. Give it a few chances to
4644 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07004645 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08004646 if (--(track->mRetryCount) <= 0) {
4647 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07004648 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004649 // indicate to client process that the track was disabled because of underrun;
4650 // it will then automatically call start() when data is available
4651 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004652 } else if (last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004653 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07004654 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004655 doHwPause = true;
4656 mHwPaused = true;
4657 }
Eric Laurent81784c32012-11-19 14:55:58 -08004658 }
4659 }
4660 }
4661 }
4662
Eric Laurentd1f69b02014-12-15 14:33:13 -08004663 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07004664 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004665 for (size_t i = 0; i < mTracks.size(); i++) {
4666 if (mTracks[i]->isFlushPending()) {
4667 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004668 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004669 }
4670 }
4671 }
4672
4673 // make sure the pause/flush/resume sequence is executed in the right order.
4674 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4675 // before flush and then resume HW. This can happen in case of pause/flush/resume
4676 // if resume is received before pause is executed.
4677 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07004678 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004679 mOutput->stream->pause(mOutput->stream);
4680 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004681 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004682 flushHw_l();
4683 }
4684 if (mHwSupportsPause && !mStandby && doHwResume) {
4685 mOutput->stream->resume(mOutput->stream);
4686 }
Eric Laurent81784c32012-11-19 14:55:58 -08004687 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004688 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004689
4690 return mixerStatus;
4691}
4692
4693void AudioFlinger::DirectOutputThread::threadLoop_mix()
4694{
Eric Laurent81784c32012-11-19 14:55:58 -08004695 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08004696 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004697 // output audio to hardware
4698 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07004699 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004700 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08004701 status_t status = mActiveTrack->getNextBuffer(&buffer);
4702 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08004703 memset(curBuf, 0, frameCount * mFrameSize);
4704 break;
4705 }
4706 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
4707 frameCount -= buffer.frameCount;
4708 curBuf += buffer.frameCount * mFrameSize;
4709 mActiveTrack->releaseBuffer(&buffer);
4710 }
Andy Hung2098f272014-02-27 14:00:06 -08004711 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004712 mSleepTimeUs = 0;
4713 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08004714 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004715}
4716
4717void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
4718{
Eric Laurentd1f69b02014-12-15 14:33:13 -08004719 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004720 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004721 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004722 return;
4723 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004724 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004725 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004726 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004727 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004728 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004729 }
4730 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08004731 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004732 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004733 }
4734}
4735
Eric Laurentd1f69b02014-12-15 14:33:13 -08004736void AudioFlinger::DirectOutputThread::threadLoop_exit()
4737{
4738 {
4739 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08004740 for (size_t i = 0; i < mTracks.size(); i++) {
4741 if (mTracks[i]->isFlushPending()) {
4742 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004743 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004744 }
4745 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004746 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004747 flushHw_l();
4748 }
4749 }
4750 PlaybackThread::threadLoop_exit();
4751}
4752
4753// must be called with thread mutex locked
4754bool AudioFlinger::DirectOutputThread::shouldStandby_l()
4755{
4756 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07004757 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004758
4759 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4760 // after a timeout and we will enter standby then.
4761 if (mTracks.size() > 0) {
4762 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07004763 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
4764 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004765 }
4766
Eric Laurent5cff4032015-05-26 13:49:58 -07004767 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08004768}
4769
Eric Laurent81784c32012-11-19 14:55:58 -08004770// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004771int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Andy Hunge8a1ced2014-05-09 15:02:21 -07004772 audio_format_t format __unused, int sessionId __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004773{
4774 return 0;
4775}
4776
4777// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004778void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004779{
4780}
4781
Eric Laurent10351942014-05-08 18:49:52 -07004782// checkForNewParameter_l() must be called with ThreadBase::mLock held
4783bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
4784 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004785{
4786 bool reconfig = false;
4787
Eric Laurent10351942014-05-08 18:49:52 -07004788 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004789
Eric Laurent10351942014-05-08 18:49:52 -07004790 AudioParameter param = AudioParameter(keyValuePair);
4791 int value;
4792 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4793 // forward device change to effects that have requested to be
4794 // aware of attached audio device.
4795 if (value != AUDIO_DEVICE_NONE) {
4796 mOutDevice = value;
4797 for (size_t i = 0; i < mEffectChains.size(); i++) {
4798 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07004799 }
4800 }
Eric Laurent81784c32012-11-19 14:55:58 -08004801 }
Eric Laurent10351942014-05-08 18:49:52 -07004802 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4803 // do not accept frame count changes if tracks are open as the track buffer
4804 // size depends on frame count and correct behavior would not be garantied
4805 // if frame count is changed after track creation
4806 if (!mTracks.isEmpty()) {
4807 status = INVALID_OPERATION;
4808 } else {
4809 reconfig = true;
4810 }
4811 }
4812 if (status == NO_ERROR) {
4813 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4814 keyValuePair.string());
4815 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004816 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004817 mStandby = true;
4818 mBytesWritten = 0;
4819 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4820 keyValuePair.string());
4821 }
4822 if (status == NO_ERROR && reconfig) {
4823 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07004824 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004825 }
4826 }
4827
Eric Laurent81784c32012-11-19 14:55:58 -08004828 return reconfig;
4829}
4830
4831uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
4832{
4833 uint32_t time;
4834 if (audio_is_linear_pcm(mFormat)) {
4835 time = PlaybackThread::activeSleepTimeUs();
4836 } else {
4837 time = 10000;
4838 }
4839 return time;
4840}
4841
4842uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
4843{
4844 uint32_t time;
4845 if (audio_is_linear_pcm(mFormat)) {
4846 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
4847 } else {
4848 time = 10000;
4849 }
4850 return time;
4851}
4852
4853uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
4854{
4855 uint32_t time;
4856 if (audio_is_linear_pcm(mFormat)) {
4857 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
4858 } else {
4859 time = 10000;
4860 }
4861 return time;
4862}
4863
4864void AudioFlinger::DirectOutputThread::cacheParameters_l()
4865{
4866 PlaybackThread::cacheParameters_l();
4867
4868 // use shorter standby delay as on normal output to release
4869 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07004870 // no delay on outputs with HW A/V sync
4871 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004872 mStandbyDelayNs = 0;
Eric Laurent5cff4032015-05-26 13:49:58 -07004873 } else if ((mType == OFFLOAD) && !audio_is_linear_pcm(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004874 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07004875 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004876 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07004877 }
Eric Laurent81784c32012-11-19 14:55:58 -08004878}
4879
Eric Laurente659ef42014-09-29 13:06:46 -07004880void AudioFlinger::DirectOutputThread::flushHw_l()
4881{
Phil Burk062e67a2015-02-11 13:40:50 -08004882 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08004883 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07004884 mFlushPending = false;
Eric Laurente659ef42014-09-29 13:06:46 -07004885}
4886
Eric Laurent81784c32012-11-19 14:55:58 -08004887// ----------------------------------------------------------------------------
4888
Eric Laurentbfb1b832013-01-07 09:53:42 -08004889AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07004890 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004891 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07004892 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07004893 mWriteAckSequence(0),
4894 mDrainSequence(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004895{
4896}
4897
4898AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
4899{
4900}
4901
4902void AudioFlinger::AsyncCallbackThread::onFirstRef()
4903{
4904 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
4905}
4906
4907bool AudioFlinger::AsyncCallbackThread::threadLoop()
4908{
4909 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004910 uint32_t writeAckSequence;
4911 uint32_t drainSequence;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004912
4913 {
4914 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08004915 while (!((mWriteAckSequence & 1) ||
4916 (mDrainSequence & 1) ||
4917 exitPending())) {
4918 mWaitWorkCV.wait(mLock);
4919 }
4920
Eric Laurentbfb1b832013-01-07 09:53:42 -08004921 if (exitPending()) {
4922 break;
4923 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004924 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
4925 mWriteAckSequence, mDrainSequence);
4926 writeAckSequence = mWriteAckSequence;
4927 mWriteAckSequence &= ~1;
4928 drainSequence = mDrainSequence;
4929 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004930 }
4931 {
Eric Laurent4de95592013-09-26 15:28:21 -07004932 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
4933 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004934 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004935 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004936 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004937 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004938 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004939 }
4940 }
4941 }
4942 }
4943 return false;
4944}
4945
4946void AudioFlinger::AsyncCallbackThread::exit()
4947{
4948 ALOGV("AsyncCallbackThread::exit");
4949 Mutex::Autolock _l(mLock);
4950 requestExit();
4951 mWaitWorkCV.broadcast();
4952}
4953
Eric Laurent3b4529e2013-09-05 18:09:19 -07004954void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004955{
4956 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004957 // bit 0 is cleared
4958 mWriteAckSequence = sequence << 1;
4959}
4960
4961void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
4962{
4963 Mutex::Autolock _l(mLock);
4964 // ignore unexpected callbacks
4965 if (mWriteAckSequence & 2) {
4966 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004967 mWaitWorkCV.signal();
4968 }
4969}
4970
Eric Laurent3b4529e2013-09-05 18:09:19 -07004971void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004972{
4973 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004974 // bit 0 is cleared
4975 mDrainSequence = sequence << 1;
4976}
4977
4978void AudioFlinger::AsyncCallbackThread::resetDraining()
4979{
4980 Mutex::Autolock _l(mLock);
4981 // ignore unexpected callbacks
4982 if (mDrainSequence & 2) {
4983 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004984 mWaitWorkCV.signal();
4985 }
4986}
4987
4988
4989// ----------------------------------------------------------------------------
4990AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07004991 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady)
4992 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady),
Eric Laurentd7e59222013-11-15 12:02:28 -08004993 mPausedBytesRemaining(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004994{
Eric Laurentfd477972013-10-25 18:10:40 -07004995 //FIXME: mStandby should be set to true by ThreadBase constructor
4996 mStandby = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004997}
4998
Eric Laurentbfb1b832013-01-07 09:53:42 -08004999void AudioFlinger::OffloadThread::threadLoop_exit()
5000{
5001 if (mFlushPending || mHwPaused) {
5002 // If a flush is pending or track was paused, just discard buffered data
5003 flushHw_l();
5004 } else {
5005 mMixerStatus = MIXER_DRAIN_ALL;
5006 threadLoop_drain();
5007 }
Uday Gupta56604aa2014-05-13 11:19:17 -07005008 if (mUseAsyncWrite) {
5009 ALOG_ASSERT(mCallbackThread != 0);
5010 mCallbackThread->exit();
5011 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005012 PlaybackThread::threadLoop_exit();
5013}
5014
5015AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
5016 Vector< sp<Track> > *tracksToRemove
5017)
5018{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005019 size_t count = mActiveTracks.size();
5020
5021 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07005022 bool doHwPause = false;
5023 bool doHwResume = false;
5024
Eric Laurentede6c3b2013-09-19 14:37:46 -07005025 ALOGV("OffloadThread::prepareTracks_l active tracks %d", count);
5026
Eric Laurentbfb1b832013-01-07 09:53:42 -08005027 // find out which tracks need to be processed
5028 for (size_t i = 0; i < count; i++) {
5029 sp<Track> t = mActiveTracks[i].promote();
5030 // The track died recently
5031 if (t == 0) {
5032 continue;
5033 }
5034 Track* const track = t.get();
5035 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07005036 // Only consider last track started for volume and mixer state control.
5037 // In theory an older track could underrun and restart after the new one starts
5038 // but as we only care about the transition phase between two tracks on a
5039 // direct output, it is not a problem to ignore the underrun case.
5040 sp<Track> l = mLatestActiveTrack.promote();
5041 bool last = l.get() == track;
5042
Haynes Mathew George7844f672014-01-15 12:32:55 -08005043 if (track->isInvalid()) {
5044 ALOGW("An invalidated track shouldn't be in active list");
5045 tracksToRemove->add(track);
5046 continue;
5047 }
5048
5049 if (track->mState == TrackBase::IDLE) {
5050 ALOGW("An idle track shouldn't be in active list");
5051 continue;
5052 }
5053
Eric Laurentbfb1b832013-01-07 09:53:42 -08005054 if (track->isPausing()) {
5055 track->setPaused();
5056 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07005057 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07005058 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005059 mHwPaused = true;
5060 }
5061 // If we were part way through writing the mixbuffer to
5062 // the HAL we must save this until we resume
5063 // BUG - this will be wrong if a different track is made active,
5064 // in that case we want to discard the pending data in the
5065 // mixbuffer and tell the client to present it again when the
5066 // track is resumed
5067 mPausedWriteLength = mCurrentWriteLength;
5068 mPausedBytesRemaining = mBytesRemaining;
5069 mBytesRemaining = 0; // stop writing
5070 }
5071 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08005072 } else if (track->isFlushPending()) {
5073 track->flushAck();
5074 if (last) {
5075 mFlushPending = true;
5076 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005077 } else if (track->isResumePending()){
5078 track->resumeAck();
5079 if (last) {
5080 if (mPausedBytesRemaining) {
5081 // Need to continue write that was interrupted
5082 mCurrentWriteLength = mPausedWriteLength;
5083 mBytesRemaining = mPausedBytesRemaining;
5084 mPausedBytesRemaining = 0;
5085 }
5086 if (mHwPaused) {
5087 doHwResume = true;
5088 mHwPaused = false;
5089 // threadLoop_mix() will handle the case that we need to
5090 // resume an interrupted write
5091 }
5092 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005093 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005094
5095 // Do not handle new data in this iteration even if track->framesReady()
5096 mixerStatus = MIXER_TRACKS_ENABLED;
5097 }
5098 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07005099 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005100 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005101 if (track->mFillingUpStatus == Track::FS_FILLED) {
5102 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07005103 // make sure processVolume_l() will apply new volume even if 0
5104 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005105 }
5106
5107 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08005108 sp<Track> previousTrack = mPreviousTrack.promote();
5109 if (previousTrack != 0) {
5110 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08005111 // Flush any data still being written from last track
5112 mBytesRemaining = 0;
5113 if (mPausedBytesRemaining) {
5114 // Last track was paused so we also need to flush saved
5115 // mixbuffer state and invalidate track so that it will
5116 // re-submit that unwritten data when it is next resumed
5117 mPausedBytesRemaining = 0;
5118 // Invalidate is a bit drastic - would be more efficient
5119 // to have a flag to tell client that some of the
5120 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08005121 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005122 }
5123 // flush data already sent to the DSP if changing audio session as audio
5124 // comes from a different source. Also invalidate previous track to force a
5125 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08005126 if (previousTrack->sessionId() != track->sessionId()) {
5127 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005128 }
5129 }
5130 }
5131 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005132 // reset retry count
5133 track->mRetryCount = kMaxTrackRetriesOffload;
5134 mActiveTrack = t;
5135 mixerStatus = MIXER_TRACKS_READY;
5136 }
5137 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005138 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005139 if (track->isStopping_1()) {
5140 // Hardware buffer can hold a large amount of audio so we must
5141 // wait for all current track's data to drain before we say
5142 // that the track is stopped.
5143 if (mBytesRemaining == 0) {
5144 // Only start draining when all data in mixbuffer
5145 // has been written
5146 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
5147 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005148 // do not drain if no data was ever sent to HAL (mStandby == true)
5149 if (last && !mStandby) {
Eric Laurent1b9f9b12013-11-12 19:10:17 -08005150 // do not modify drain sequence if we are already draining. This happens
5151 // when resuming from pause after drain.
5152 if ((mDrainSequence & 1) == 0) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005153 mSleepTimeUs = 0;
5154 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent1b9f9b12013-11-12 19:10:17 -08005155 mixerStatus = MIXER_DRAIN_TRACK;
5156 mDrainSequence += 2;
5157 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005158 if (mHwPaused) {
5159 // It is possible to move from PAUSED to STOPPING_1 without
5160 // a resume so we must ensure hardware is running
Eric Laurent1b9f9b12013-11-12 19:10:17 -08005161 doHwResume = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005162 mHwPaused = false;
5163 }
5164 }
5165 }
5166 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005167 // Drain has completed or we are in standby, signal presentation complete
5168 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005169 track->mState = TrackBase::STOPPED;
5170 size_t audioHALFrames =
5171 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
5172 size_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08005173 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005174 track->presentationComplete(framesWritten, audioHALFrames);
5175 track->reset();
5176 tracksToRemove->add(track);
5177 }
5178 } else {
5179 // No buffers for this track. Give it a few chances to
5180 // fill a buffer, then remove it from active list.
5181 if (--(track->mRetryCount) <= 0) {
5182 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
5183 track->name());
5184 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08005185 // indicate to client process that the track was disabled because of underrun;
5186 // it will then automatically call start() when data is available
5187 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005188 } else if (last){
5189 mixerStatus = MIXER_TRACKS_ENABLED;
5190 }
5191 }
5192 }
5193 // compute volume for this track
5194 processVolume_l(track, last);
5195 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005196
Eric Laurentea0fade2013-10-04 16:23:48 -07005197 // make sure the pause/flush/resume sequence is executed in the right order.
5198 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5199 // before flush and then resume HW. This can happen in case of pause/flush/resume
5200 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07005201 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurent972a1732013-09-04 09:42:59 -07005202 mOutput->stream->pause(mOutput->stream);
5203 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005204 if (mFlushPending) {
5205 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005206 }
Eric Laurentfd477972013-10-25 18:10:40 -07005207 if (!mStandby && doHwResume) {
Eric Laurent972a1732013-09-04 09:42:59 -07005208 mOutput->stream->resume(mOutput->stream);
5209 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005210
Eric Laurentbfb1b832013-01-07 09:53:42 -08005211 // remove all the tracks that need to be...
5212 removeTracks_l(*tracksToRemove);
5213
5214 return mixerStatus;
5215}
5216
Eric Laurentbfb1b832013-01-07 09:53:42 -08005217// must be called with thread mutex locked
5218bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
5219{
Eric Laurent3b4529e2013-09-05 18:09:19 -07005220 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
5221 mWriteAckSequence, mDrainSequence);
5222 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005223 return true;
5224 }
5225 return false;
5226}
5227
Eric Laurentbfb1b832013-01-07 09:53:42 -08005228bool AudioFlinger::OffloadThread::waitingAsyncCallback()
5229{
5230 Mutex::Autolock _l(mLock);
5231 return waitingAsyncCallback_l();
5232}
5233
5234void AudioFlinger::OffloadThread::flushHw_l()
5235{
Eric Laurente659ef42014-09-29 13:06:46 -07005236 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005237 // Flush anything still waiting in the mixbuffer
5238 mCurrentWriteLength = 0;
5239 mBytesRemaining = 0;
5240 mPausedWriteLength = 0;
5241 mPausedBytesRemaining = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08005242
Eric Laurentbfb1b832013-01-07 09:53:42 -08005243 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005244 // discard any pending drain or write ack by incrementing sequence
5245 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5246 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005247 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005248 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5249 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005250 }
5251}
5252
5253// ----------------------------------------------------------------------------
5254
Eric Laurent81784c32012-11-19 14:55:58 -08005255AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07005256 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08005257 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
Eric Laurent72e3f392015-05-20 14:43:50 -07005258 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08005259 mWaitTimeMs(UINT_MAX)
5260{
5261 addOutputTrack(mainThread);
5262}
5263
5264AudioFlinger::DuplicatingThread::~DuplicatingThread()
5265{
5266 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5267 mOutputTracks[i]->destroy();
5268 }
5269}
5270
5271void AudioFlinger::DuplicatingThread::threadLoop_mix()
5272{
5273 // mix buffers...
5274 if (outputsReady(outputTracks)) {
5275 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
5276 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08005277 if (mMixerBufferValid) {
5278 memset(mMixerBuffer, 0, mMixerBufferSize);
5279 } else {
5280 memset(mSinkBuffer, 0, mSinkBufferSize);
5281 }
Eric Laurent81784c32012-11-19 14:55:58 -08005282 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005283 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005284 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005285 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005286 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005287}
5288
5289void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
5290{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005291 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005292 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005293 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005294 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005295 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005296 }
5297 } else if (mBytesWritten != 0) {
5298 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5299 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005300 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005301 } else {
5302 // flush remaining overflow buffers in output tracks
5303 writeFrames = 0;
5304 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005305 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005306 }
5307}
5308
Eric Laurentbfb1b832013-01-07 09:53:42 -08005309ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005310{
5311 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08005312 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005313 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07005314 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08005315 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005316}
5317
5318void AudioFlinger::DuplicatingThread::threadLoop_standby()
5319{
5320 // DuplicatingThread implements standby by stopping all tracks
5321 for (size_t i = 0; i < outputTracks.size(); i++) {
5322 outputTracks[i]->stop();
5323 }
5324}
5325
5326void AudioFlinger::DuplicatingThread::saveOutputTracks()
5327{
5328 outputTracks = mOutputTracks;
5329}
5330
5331void AudioFlinger::DuplicatingThread::clearOutputTracks()
5332{
5333 outputTracks.clear();
5334}
5335
5336void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
5337{
5338 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08005339 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
5340 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
5341 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
5342 const size_t frameCount =
5343 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
5344 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
5345 // from different OutputTracks and their associated MixerThreads (e.g. one may
5346 // nearly empty and the other may be dropping data).
5347
5348 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08005349 this,
5350 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08005351 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08005352 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005353 frameCount,
5354 IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08005355 if (outputTrack->cblk() != NULL) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005356 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
Eric Laurent81784c32012-11-19 14:55:58 -08005357 mOutputTracks.add(outputTrack);
Andy Hungc25b84a2015-01-14 19:04:10 -08005358 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005359 updateWaitTime_l();
5360 }
5361}
5362
5363void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
5364{
5365 Mutex::Autolock _l(mLock);
5366 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5367 if (mOutputTracks[i]->thread() == thread) {
5368 mOutputTracks[i]->destroy();
5369 mOutputTracks.removeAt(i);
5370 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07005371 if (thread->getOutput() == mOutput) {
5372 mOutput = NULL;
5373 }
Eric Laurent81784c32012-11-19 14:55:58 -08005374 return;
5375 }
5376 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07005377 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005378}
5379
5380// caller must hold mLock
5381void AudioFlinger::DuplicatingThread::updateWaitTime_l()
5382{
5383 mWaitTimeMs = UINT_MAX;
5384 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5385 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
5386 if (strong != 0) {
5387 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
5388 if (waitTimeMs < mWaitTimeMs) {
5389 mWaitTimeMs = waitTimeMs;
5390 }
5391 }
5392 }
5393}
5394
5395
5396bool AudioFlinger::DuplicatingThread::outputsReady(
5397 const SortedVector< sp<OutputTrack> > &outputTracks)
5398{
5399 for (size_t i = 0; i < outputTracks.size(); i++) {
5400 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
5401 if (thread == 0) {
5402 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
5403 outputTracks[i].get());
5404 return false;
5405 }
5406 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5407 // see note at standby() declaration
5408 if (playbackThread->standby() && !playbackThread->isSuspended()) {
5409 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
5410 thread.get());
5411 return false;
5412 }
5413 }
5414 return true;
5415}
5416
5417uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
5418{
5419 return (mWaitTimeMs * 1000) / 2;
5420}
5421
5422void AudioFlinger::DuplicatingThread::cacheParameters_l()
5423{
5424 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
5425 updateWaitTime_l();
5426
5427 MixerThread::cacheParameters_l();
5428}
5429
5430// ----------------------------------------------------------------------------
5431// Record
5432// ----------------------------------------------------------------------------
5433
5434AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5435 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08005436 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08005437 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07005438 audio_devices_t inDevice,
5439 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08005440#ifdef TEE_SINK
5441 , const sp<NBAIO_Sink>& teeSink
5442#endif
5443 ) :
Eric Laurent72e3f392015-05-20 14:43:50 -07005444 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005445 mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005446 // mRsmpInFrames and mRsmpInFramesP2 are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005447 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08005448#ifdef TEE_SINK
5449 , mTeeSink(teeSink)
5450#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07005451 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
5452 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005453 // mFastCapture below
5454 , mFastCaptureFutex(0)
5455 // mInputSource
5456 // mPipeSink
5457 // mPipeSource
5458 , mPipeFramesP2(0)
5459 // mPipeMemory
5460 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005461 , mFastTrackAvail(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005462{
Glenn Kastend7dca052015-03-05 16:05:54 -08005463 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
5464 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08005465
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005466 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005467
5468 // create an NBAIO source for the HAL input stream, and negotiate
5469 mInputSource = new AudioStreamInSource(input->stream);
5470 size_t numCounterOffers = 0;
5471 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
5472 ssize_t index = mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
5473 ALOG_ASSERT(index == 0);
5474
5475 // initialize fast capture depending on configuration
5476 bool initFastCapture;
5477 switch (kUseFastCapture) {
5478 case FastCapture_Never:
5479 initFastCapture = false;
5480 break;
5481 case FastCapture_Always:
5482 initFastCapture = true;
5483 break;
5484 case FastCapture_Static:
5485 uint32_t primaryOutputSampleRate;
5486 {
5487 AutoMutex _l(audioFlinger->mHardwareLock);
5488 primaryOutputSampleRate = audioFlinger->mPrimaryOutputSampleRate;
5489 }
5490 initFastCapture =
5491 // either capture sample rate is same as (a reasonable) primary output sample rate
Andy Hungdb4c0312015-05-06 08:46:52 -07005492 ((isMusicRate(primaryOutputSampleRate) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005493 (mSampleRate == primaryOutputSampleRate)) ||
5494 // or primary output sample rate is unknown, and capture sample rate is reasonable
5495 ((primaryOutputSampleRate == 0) &&
Andy Hungdb4c0312015-05-06 08:46:52 -07005496 isMusicRate(mSampleRate))) &&
Glenn Kasten9f81de32014-07-27 15:02:23 -07005497 // and the buffer size is < 12 ms
5498 (mFrameCount * 1000) / mSampleRate < 12;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005499 break;
5500 // case FastCapture_Dynamic:
5501 }
5502
5503 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07005504 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005505 NBAIO_Format format = mInputSource->format();
Glenn Kasten49d00ad2014-07-21 11:22:03 -07005506 size_t pipeFramesP2 = roundup(mSampleRate / 25); // double-buffering of 20 ms each
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005507 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
5508 void *pipeBuffer;
5509 const sp<MemoryDealer> roHeap(readOnlyHeap());
5510 sp<IMemory> pipeMemory;
5511 if ((roHeap == 0) ||
5512 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
5513 (pipeBuffer = pipeMemory->pointer()) == NULL) {
5514 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
5515 goto failed;
5516 }
5517 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
5518 memset(pipeBuffer, 0, pipeSize);
5519 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
5520 const NBAIO_Format offers[1] = {format};
5521 size_t numCounterOffers = 0;
5522 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
5523 ALOG_ASSERT(index == 0);
5524 mPipeSink = pipe;
5525 PipeReader *pipeReader = new PipeReader(*pipe);
5526 numCounterOffers = 0;
5527 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
5528 ALOG_ASSERT(index == 0);
5529 mPipeSource = pipeReader;
5530 mPipeFramesP2 = pipeFramesP2;
5531 mPipeMemory = pipeMemory;
5532
5533 // create fast capture
5534 mFastCapture = new FastCapture();
5535 FastCaptureStateQueue *sq = mFastCapture->sq();
5536#ifdef STATE_QUEUE_DUMP
5537 // FIXME
5538#endif
5539 FastCaptureState *state = sq->begin();
5540 state->mCblk = NULL;
5541 state->mInputSource = mInputSource.get();
5542 state->mInputSourceGen++;
5543 state->mPipeSink = pipe;
5544 state->mPipeSinkGen++;
5545 state->mFrameCount = mFrameCount;
5546 state->mCommand = FastCaptureState::COLD_IDLE;
5547 // already done in constructor initialization list
5548 //mFastCaptureFutex = 0;
5549 state->mColdFutexAddr = &mFastCaptureFutex;
5550 state->mColdGen++;
5551 state->mDumpState = &mFastCaptureDumpState;
5552#ifdef TEE_SINK
5553 // FIXME
5554#endif
5555 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
5556 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
5557 sq->end();
5558 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5559
5560 // start the fast capture
5561 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
5562 pid_t tid = mFastCapture->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07005563 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005564#ifdef AUDIO_WATCHDOG
5565 // FIXME
5566#endif
5567
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005568 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005569 }
5570failed: ;
5571
5572 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08005573}
5574
Eric Laurent81784c32012-11-19 14:55:58 -08005575AudioFlinger::RecordThread::~RecordThread()
5576{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005577 if (mFastCapture != 0) {
5578 FastCaptureStateQueue *sq = mFastCapture->sq();
5579 FastCaptureState *state = sq->begin();
5580 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5581 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5582 if (old == -1) {
5583 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5584 }
5585 }
5586 state->mCommand = FastCaptureState::EXIT;
5587 sq->end();
5588 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5589 mFastCapture->join();
5590 mFastCapture.clear();
5591 }
5592 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07005593 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07005594 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08005595}
5596
5597void AudioFlinger::RecordThread::onFirstRef()
5598{
Glenn Kastend7dca052015-03-05 16:05:54 -08005599 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08005600}
5601
Eric Laurent81784c32012-11-19 14:55:58 -08005602bool AudioFlinger::RecordThread::threadLoop()
5603{
Eric Laurent81784c32012-11-19 14:55:58 -08005604 nsecs_t lastWarning = 0;
5605
5606 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08005607
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005608reacquire_wakelock:
5609 sp<RecordTrack> activeTrack;
Glenn Kasten2b806402013-11-20 16:37:38 -08005610 int activeTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005611 {
5612 Mutex::Autolock _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005613 size_t size = mActiveTracks.size();
5614 activeTracksGen = mActiveTracksGen;
5615 if (size > 0) {
5616 // FIXME an arbitrary choice
5617 activeTrack = mActiveTracks[0];
5618 acquireWakeLock_l(activeTrack->uid());
5619 if (size > 1) {
5620 SortedVector<int> tmp;
5621 for (size_t i = 0; i < size; i++) {
5622 tmp.add(mActiveTracks[i]->uid());
5623 }
5624 updateWakeLockUids_l(tmp);
5625 }
5626 } else {
5627 acquireWakeLock_l(-1);
5628 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005629 }
5630
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005631 // used to request a deferred sleep, to be executed later while mutex is unlocked
5632 uint32_t sleepUs = 0;
5633
5634 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005635 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005636 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07005637
Glenn Kasten5edadd42013-08-14 16:30:49 -07005638 // sleep with mutex unlocked
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005639 if (sleepUs > 0) {
Glenn Kastene7754022014-10-31 12:11:26 -07005640 ATRACE_BEGIN("sleep");
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005641 usleep(sleepUs);
Glenn Kastene7754022014-10-31 12:11:26 -07005642 ATRACE_END();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005643 sleepUs = 0;
Glenn Kasten5edadd42013-08-14 16:30:49 -07005644 }
5645
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005646 // activeTracks accumulates a copy of a subset of mActiveTracks
5647 Vector< sp<RecordTrack> > activeTracks;
5648
Glenn Kasten735f45f2014-08-18 15:51:59 -07005649 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005650 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07005651
Glenn Kasten735f45f2014-08-18 15:51:59 -07005652 // reference to a fast track which is about to be removed
5653 sp<RecordTrack> fastTrackToRemove;
5654
Eric Laurent81784c32012-11-19 14:55:58 -08005655 { // scope for mLock
5656 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08005657
Eric Laurent021cf962014-05-13 10:18:14 -07005658 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005659
Eric Laurent000a4192014-01-29 15:17:32 -08005660 // check exitPending here because checkForNewParameters_l() and
5661 // checkForNewParameters_l() can temporarily release mLock
5662 if (exitPending()) {
5663 break;
5664 }
5665
Glenn Kasten2b806402013-11-20 16:37:38 -08005666 // if no active track(s), then standby and release wakelock
5667 size_t size = mActiveTracks.size();
5668 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07005669 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005670 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08005671 releaseWakeLock_l();
5672 ALOGV("RecordThread: loop stopping");
5673 // go to sleep
5674 mWaitWorkCV.wait(mLock);
5675 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005676 goto reacquire_wakelock;
5677 }
5678
Glenn Kasten2b806402013-11-20 16:37:38 -08005679 if (mActiveTracksGen != activeTracksGen) {
5680 activeTracksGen = mActiveTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005681 SortedVector<int> tmp;
Glenn Kasten2b806402013-11-20 16:37:38 -08005682 for (size_t i = 0; i < size; i++) {
5683 tmp.add(mActiveTracks[i]->uid());
5684 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005685 updateWakeLockUids_l(tmp);
Eric Laurent81784c32012-11-19 14:55:58 -08005686 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005687
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005688 bool doBroadcast = false;
5689 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07005690
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005691 activeTrack = mActiveTracks[i];
5692 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07005693 if (activeTrack->isFastTrack()) {
5694 ALOG_ASSERT(fastTrackToRemove == 0);
5695 fastTrackToRemove = activeTrack;
5696 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005697 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08005698 mActiveTracks.remove(activeTrack);
5699 mActiveTracksGen++;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005700 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07005701 continue;
5702 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005703
5704 TrackBase::track_state activeTrackState = activeTrack->mState;
5705 switch (activeTrackState) {
5706
5707 case TrackBase::PAUSING:
5708 mActiveTracks.remove(activeTrack);
5709 mActiveTracksGen++;
5710 doBroadcast = true;
5711 size--;
5712 continue;
5713
5714 case TrackBase::STARTING_1:
5715 sleepUs = 10000;
5716 i++;
5717 continue;
5718
5719 case TrackBase::STARTING_2:
5720 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005721 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07005722 activeTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005723 break;
5724
5725 case TrackBase::ACTIVE:
5726 break;
5727
5728 case TrackBase::IDLE:
5729 i++;
5730 continue;
5731
5732 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08005733 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07005734 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005735
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005736 activeTracks.add(activeTrack);
5737 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07005738
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005739 if (activeTrack->isFastTrack()) {
5740 ALOG_ASSERT(!mFastTrackAvail);
5741 ALOG_ASSERT(fastTrack == 0);
5742 fastTrack = activeTrack;
5743 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005744 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005745 if (doBroadcast) {
5746 mStartStopCond.broadcast();
5747 }
5748
5749 // sleep if there are no active tracks to process
5750 if (activeTracks.size() == 0) {
5751 if (sleepUs == 0) {
5752 sleepUs = kRecordThreadSleepUs;
5753 }
5754 continue;
5755 }
5756 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07005757
Eric Laurent81784c32012-11-19 14:55:58 -08005758 lockEffectChains_l(effectChains);
5759 }
5760
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005761 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07005762
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005763 size_t size = effectChains.size();
5764 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005765 // thread mutex is not locked, but effect chain is locked
5766 effectChains[i]->process_l();
5767 }
5768
Glenn Kasten735f45f2014-08-18 15:51:59 -07005769 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005770 if (mFastCapture != 0) {
5771 FastCaptureStateQueue *sq = mFastCapture->sq();
5772 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07005773 bool didModify = false;
5774 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005775 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
5776 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
5777 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5778 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5779 if (old == -1) {
5780 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5781 }
5782 }
5783 state->mCommand = FastCaptureState::READ_WRITE;
5784#if 0 // FIXME
5785 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08005786 FastThreadDumpState::kSamplingNforLowRamDevice :
5787 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005788#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07005789 didModify = true;
5790 }
5791 audio_track_cblk_t *cblkOld = state->mCblk;
5792 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
5793 if (cblkNew != cblkOld) {
5794 state->mCblk = cblkNew;
5795 // block until acked if removing a fast track
5796 if (cblkOld != NULL) {
5797 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
5798 }
5799 didModify = true;
5800 }
5801 sq->end(didModify);
5802 if (didModify) {
5803 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005804#if 0
5805 if (kUseFastCapture == FastCapture_Dynamic) {
5806 mNormalSource = mPipeSource;
5807 }
5808#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005809 }
5810 }
5811
Glenn Kasten735f45f2014-08-18 15:51:59 -07005812 // now run the fast track destructor with thread mutex unlocked
5813 fastTrackToRemove.clear();
5814
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005815 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
5816 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
5817 // slow, then this RecordThread will overrun by not calling HAL read often enough.
5818 // If destination is non-contiguous, first read past the nominal end of buffer, then
5819 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005820
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005821 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005822 ssize_t framesRead;
5823
5824 // If an NBAIO source is present, use it to read the normal capture's data
5825 if (mPipeSource != 0) {
5826 size_t framesToRead = mBufferSize / mFrameSize;
Andy Hung57446612015-04-19 23:56:46 -07005827 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005828 framesToRead, AudioBufferProvider::kInvalidPTS);
5829 if (framesRead == 0) {
5830 // since pipe is non-blocking, simulate blocking input
5831 sleepUs = (framesToRead * 1000000LL) / mSampleRate;
5832 }
5833 // otherwise use the HAL / AudioStreamIn directly
5834 } else {
5835 ssize_t bytesRead = mInput->stream->read(mInput->stream,
Andy Hung57446612015-04-19 23:56:46 -07005836 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005837 if (bytesRead < 0) {
5838 framesRead = bytesRead;
5839 } else {
5840 framesRead = bytesRead / mFrameSize;
5841 }
5842 }
5843
5844 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
5845 ALOGE("read failed: framesRead=%d", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005846 // Force input into standby so that it tries to recover at next read attempt
5847 inputStandBy();
5848 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005849 }
5850 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005851 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005852 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005853 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005854
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005855 if (mTeeSink != 0) {
Andy Hung57446612015-04-19 23:56:46 -07005856 (void) mTeeSink->write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005857 }
5858 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005859 {
5860 size_t part1 = mRsmpInFramesP2 - rear;
5861 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07005862 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005863 (framesRead - part1) * mFrameSize);
5864 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005865 }
5866 rear = mRsmpInRear += framesRead;
5867
5868 size = activeTracks.size();
5869 // loop over each active track
5870 for (size_t i = 0; i < size; i++) {
5871 activeTrack = activeTracks[i];
5872
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005873 // skip fast tracks, as those are handled directly by FastCapture
5874 if (activeTrack->isFastTrack()) {
5875 continue;
5876 }
5877
Andy Hung73c02e42015-03-29 01:13:58 -07005878 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07005879 // TODO: Update the activeTrack buffer converter in case of reconfigure.
5880
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005881 enum {
5882 OVERRUN_UNKNOWN,
5883 OVERRUN_TRUE,
5884 OVERRUN_FALSE
5885 } overrun = OVERRUN_UNKNOWN;
5886
5887 // loop over getNextBuffer to handle circular sink
5888 for (;;) {
5889
5890 activeTrack->mSink.frameCount = ~0;
5891 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
5892 size_t framesOut = activeTrack->mSink.frameCount;
5893 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
5894
Andy Hung73c02e42015-03-29 01:13:58 -07005895 // check available frames and handle overrun conditions
5896 // if the record track isn't draining fast enough.
5897 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005898 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07005899 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
5900 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005901 overrun = OVERRUN_TRUE;
5902 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005903 if (framesOut == 0 || framesIn == 0) {
5904 break;
5905 }
5906
Andy Hung6770c6f2015-04-07 13:43:36 -07005907 // Don't allow framesOut to be larger than what is possible with resampling
5908 // from framesIn.
5909 // This isn't strictly necessary but helps limit buffer resizing in
5910 // RecordBufferConverter. TODO: remove when no longer needed.
5911 framesOut = min(framesOut,
5912 destinationFramesPossible(
5913 framesIn, mSampleRate, activeTrack->mSampleRate));
Andy Hung97a893e2015-03-29 01:03:07 -07005914 // process frames from the RecordThread buffer provider to the RecordTrack buffer
5915 framesOut = activeTrack->mRecordBufferConverter->convert(
5916 activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005917
5918 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
5919 overrun = OVERRUN_FALSE;
5920 }
5921
5922 if (activeTrack->mFramesToDrop == 0) {
5923 if (framesOut > 0) {
5924 activeTrack->mSink.frameCount = framesOut;
5925 activeTrack->releaseBuffer(&activeTrack->mSink);
5926 }
5927 } else {
5928 // FIXME could do a partial drop of framesOut
5929 if (activeTrack->mFramesToDrop > 0) {
5930 activeTrack->mFramesToDrop -= framesOut;
5931 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005932 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005933 }
5934 } else {
5935 activeTrack->mFramesToDrop += framesOut;
5936 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
5937 activeTrack->mSyncStartEvent->isCancelled()) {
5938 ALOGW("Synced record %s, session %d, trigger session %d",
5939 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
5940 activeTrack->sessionId(),
5941 (activeTrack->mSyncStartEvent != 0) ?
5942 activeTrack->mSyncStartEvent->triggerSession() : 0);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005943 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005944 }
5945 }
5946 }
5947
5948 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005949 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005950 }
5951 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005952
5953 switch (overrun) {
5954 case OVERRUN_TRUE:
5955 // client isn't retrieving buffers fast enough
5956 if (!activeTrack->setOverflow()) {
5957 nsecs_t now = systemTime();
5958 // FIXME should lastWarning per track?
5959 if ((now - lastWarning) > kWarningThrottleNs) {
5960 ALOGW("RecordThread: buffer overflow");
5961 lastWarning = now;
5962 }
5963 }
5964 break;
5965 case OVERRUN_FALSE:
5966 activeTrack->clearOverflow();
5967 break;
5968 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005969 break;
5970 }
5971
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005972 }
5973
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005974unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08005975 // enable changes in effect chain
5976 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005977 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08005978 }
5979
Glenn Kasten93e471f2013-08-19 08:40:07 -07005980 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08005981
5982 {
5983 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07005984 for (size_t i = 0; i < mTracks.size(); i++) {
5985 sp<RecordTrack> track = mTracks[i];
5986 track->invalidate();
5987 }
Glenn Kasten2b806402013-11-20 16:37:38 -08005988 mActiveTracks.clear();
5989 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08005990 mStartStopCond.broadcast();
5991 }
5992
5993 releaseWakeLock();
5994
5995 ALOGV("RecordThread %p exiting", this);
5996 return false;
5997}
5998
Glenn Kasten93e471f2013-08-19 08:40:07 -07005999void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08006000{
6001 if (!mStandby) {
6002 inputStandBy();
6003 mStandby = true;
6004 }
6005}
6006
6007void AudioFlinger::RecordThread::inputStandBy()
6008{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006009 // Idle the fast capture if it's currently running
6010 if (mFastCapture != 0) {
6011 FastCaptureStateQueue *sq = mFastCapture->sq();
6012 FastCaptureState *state = sq->begin();
6013 if (!(state->mCommand & FastCaptureState::IDLE)) {
6014 state->mCommand = FastCaptureState::COLD_IDLE;
6015 state->mColdFutexAddr = &mFastCaptureFutex;
6016 state->mColdGen++;
6017 mFastCaptureFutex = 0;
6018 sq->end();
6019 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
6020 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
6021#if 0
6022 if (kUseFastCapture == FastCapture_Dynamic) {
6023 // FIXME
6024 }
6025#endif
6026#ifdef AUDIO_WATCHDOG
6027 // FIXME
6028#endif
6029 } else {
6030 sq->end(false /*didModify*/);
6031 }
6032 }
Eric Laurent81784c32012-11-19 14:55:58 -08006033 mInput->stream->common.standby(&mInput->stream->common);
6034}
6035
Glenn Kasten05997e22014-03-13 15:08:33 -07006036// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07006037sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08006038 const sp<AudioFlinger::Client>& client,
6039 uint32_t sampleRate,
6040 audio_format_t format,
6041 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08006042 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08006043 int sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07006044 size_t *notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08006045 int uid,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07006046 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08006047 pid_t tid,
6048 status_t *status)
6049{
Glenn Kasten74935e42013-12-19 08:56:45 -08006050 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08006051 sp<RecordTrack> track;
6052 status_t lStatus;
6053
Glenn Kasten90e58b12013-07-31 16:16:02 -07006054 // client expresses a preference for FAST, but we get the final say
6055 if (*flags & IAudioFlinger::TRACK_FAST) {
6056 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07006057 // we formerly checked for a callback handler (non-0 tid),
6058 // but that is no longer required for TRANSFER_OBTAIN mode
6059 //
Glenn Kasten74105912014-07-03 12:28:53 -07006060 // frame count is not specified, or is exactly the pipe depth
6061 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006062 // PCM data
6063 audio_is_linear_pcm(format) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006064 // native format
6065 (format == mFormat) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006066 // native channel mask
6067 (channelMask == mChannelMask) &&
6068 // native hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07006069 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006070 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006071 hasFastCapture() &&
6072 // there are sufficient fast track slots available
6073 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07006074 ) {
Glenn Kasten74105912014-07-03 12:28:53 -07006075 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%u mFrameCount=%u",
Glenn Kasten90e58b12013-07-31 16:16:02 -07006076 frameCount, mFrameCount);
6077 } else {
Glenn Kasten74105912014-07-03 12:28:53 -07006078 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%u mFrameCount=%u mPipeFramesP2=%u "
6079 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006080 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Glenn Kasten74105912014-07-03 12:28:53 -07006081 frameCount, mFrameCount, mPipeFramesP2,
6082 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
6083 hasFastCapture(), tid, mFastTrackAvail);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006084 *flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kasten74105912014-07-03 12:28:53 -07006085 }
6086 }
6087
6088 // compute track buffer size in frames, and suggest the notification frame count
6089 if (*flags & IAudioFlinger::TRACK_FAST) {
6090 // fast track: frame count is exactly the pipe depth
6091 frameCount = mPipeFramesP2;
6092 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
6093 *notificationFrames = mFrameCount;
6094 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006095 // not fast track: max notification period is resampled equivalent of one HAL buffer time
6096 // or 20 ms if there is a fast capture
6097 // TODO This could be a roundupRatio inline, and const
6098 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
6099 * sampleRate + mSampleRate - 1) / mSampleRate;
6100 // minimum number of notification periods is at least kMinNotifications,
6101 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
6102 static const size_t kMinNotifications = 3;
6103 static const uint32_t kMinMs = 30;
6104 // TODO This could be a roundupRatio inline
6105 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
6106 // TODO This could be a roundupRatio inline
6107 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
6108 maxNotificationFrames;
6109 const size_t minFrameCount = maxNotificationFrames *
6110 max(kMinNotifications, minNotificationsByMs);
6111 frameCount = max(frameCount, minFrameCount);
6112 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
6113 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07006114 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07006115 }
Glenn Kasten74935e42013-12-19 08:56:45 -08006116 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07006117
Glenn Kasten15e57982013-09-24 11:52:37 -07006118 lStatus = initCheck();
6119 if (lStatus != NO_ERROR) {
6120 ALOGE("createRecordTrack_l() audio driver not initialized");
6121 goto Exit;
6122 }
Eric Laurent81784c32012-11-19 14:55:58 -08006123
6124 { // scope for mLock
6125 Mutex::Autolock _l(mLock);
6126
6127 track = new RecordTrack(this, client, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07006128 format, channelMask, frameCount, NULL, sessionId, uid,
6129 *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08006130
Glenn Kasten03003332013-08-06 15:40:54 -07006131 lStatus = track->initCheck();
6132 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07006133 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08006134 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08006135 goto Exit;
6136 }
6137 mTracks.add(track);
6138
6139 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6140 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6141 mAudioFlinger->btNrecIsOff();
6142 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6143 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006144
6145 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
6146 pid_t callingPid = IPCThreadState::self()->getCallingPid();
6147 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
6148 // so ask activity manager to do this on our behalf
6149 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
6150 }
Eric Laurent81784c32012-11-19 14:55:58 -08006151 }
Glenn Kasten05997e22014-03-13 15:08:33 -07006152
Eric Laurent81784c32012-11-19 14:55:58 -08006153 lStatus = NO_ERROR;
6154
6155Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07006156 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08006157 return track;
6158}
6159
6160status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
6161 AudioSystem::sync_event_t event,
6162 int triggerSession)
6163{
6164 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
6165 sp<ThreadBase> strongMe = this;
6166 status_t status = NO_ERROR;
6167
6168 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006169 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006170 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006171 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08006172 triggerSession,
6173 recordTrack->sessionId(),
6174 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006175 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08006176 // Sync event can be cancelled by the trigger session if the track is not in a
6177 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006178 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006179 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006180 } else {
6181 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006182 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006183 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08006184 }
6185 }
6186
6187 {
Glenn Kasten47c20702013-08-13 15:37:35 -07006188 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08006189 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006190 if (mActiveTracks.indexOf(recordTrack) >= 0) {
6191 if (recordTrack->mState == TrackBase::PAUSING) {
6192 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006193 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006194 } else {
6195 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08006196 }
6197 return status;
6198 }
6199
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006200 // TODO consider other ways of handling this, such as changing the state to :STARTING and
6201 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
6202 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006203 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08006204 mActiveTracks.add(recordTrack);
6205 mActiveTracksGen++;
Eric Laurent83b88082014-06-20 18:31:16 -07006206 status_t status = NO_ERROR;
6207 if (recordTrack->isExternalTrack()) {
6208 mLock.unlock();
Eric Laurent4dc68062014-07-28 17:26:49 -07006209 status = AudioSystem::startInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006210 mLock.lock();
6211 // FIXME should verify that recordTrack is still in mActiveTracks
6212 if (status != NO_ERROR) {
6213 mActiveTracks.remove(recordTrack);
6214 mActiveTracksGen++;
6215 recordTrack->clearSyncStartEvent();
6216 ALOGV("RecordThread::start error %d", status);
6217 return status;
6218 }
Eric Laurent81784c32012-11-19 14:55:58 -08006219 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006220 // Catch up with current buffer indices if thread is already running.
6221 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
6222 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
6223 // see previously buffered data before it called start(), but with greater risk of overrun.
6224
Andy Hung73c02e42015-03-29 01:13:58 -07006225 recordTrack->mResamplerBufferProvider->reset();
Andy Hung97a893e2015-03-29 01:03:07 -07006226 // clear any converter state as new data will be discontinuous
6227 recordTrack->mRecordBufferConverter->reset();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006228 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08006229 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08006230 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08006231 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006232 ALOGV("Record failed to start");
6233 status = BAD_VALUE;
6234 goto startError;
6235 }
Eric Laurent81784c32012-11-19 14:55:58 -08006236 return status;
6237 }
Glenn Kasten7c027242012-12-26 14:43:16 -08006238
Eric Laurent81784c32012-11-19 14:55:58 -08006239startError:
Eric Laurent83b88082014-06-20 18:31:16 -07006240 if (recordTrack->isExternalTrack()) {
Eric Laurent4dc68062014-07-28 17:26:49 -07006241 AudioSystem::stopInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006242 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006243 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006244 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08006245 return status;
6246}
6247
Eric Laurent81784c32012-11-19 14:55:58 -08006248void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6249{
6250 sp<SyncEvent> strongEvent = event.promote();
6251
6252 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08006253 sp<RefBase> ptr = strongEvent->cookie().promote();
6254 if (ptr != 0) {
6255 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
6256 recordTrack->handleSyncStartEvent(strongEvent);
6257 }
Eric Laurent81784c32012-11-19 14:55:58 -08006258 }
6259}
6260
Glenn Kastena8356f62013-07-25 14:37:52 -07006261bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08006262 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07006263 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006264 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08006265 return false;
6266 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006267 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08006268 recordTrack->mState = TrackBase::PAUSING;
6269 // do not wait for mStartStopCond if exiting
6270 if (exitPending()) {
6271 return true;
6272 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006273 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08006274 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006275 // if we have been restarted, recordTrack is in mActiveTracks here
6276 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006277 ALOGV("Record stopped OK");
6278 return true;
6279 }
6280 return false;
6281}
6282
Glenn Kasten0f11b512014-01-31 16:18:54 -08006283bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08006284{
6285 return false;
6286}
6287
Glenn Kasten0f11b512014-01-31 16:18:54 -08006288status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006289{
6290#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
6291 if (!isValidSyncEvent(event)) {
6292 return BAD_VALUE;
6293 }
6294
6295 int eventSession = event->triggerSession();
6296 status_t ret = NAME_NOT_FOUND;
6297
6298 Mutex::Autolock _l(mLock);
6299
6300 for (size_t i = 0; i < mTracks.size(); i++) {
6301 sp<RecordTrack> track = mTracks[i];
6302 if (eventSession == track->sessionId()) {
6303 (void) track->setSyncEvent(event);
6304 ret = NO_ERROR;
6305 }
6306 }
6307 return ret;
6308#else
6309 return BAD_VALUE;
6310#endif
6311}
6312
6313// destroyTrack_l() must be called with ThreadBase::mLock held
6314void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6315{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006316 track->terminate();
6317 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08006318 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08006319 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006320 removeTrack_l(track);
6321 }
6322}
6323
6324void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6325{
6326 mTracks.remove(track);
6327 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006328 if (track->isFastTrack()) {
6329 ALOG_ASSERT(!mFastTrackAvail);
6330 mFastTrackAvail = true;
6331 }
Eric Laurent81784c32012-11-19 14:55:58 -08006332}
6333
6334void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6335{
6336 dumpInternals(fd, args);
6337 dumpTracks(fd, args);
6338 dumpEffectChains(fd, args);
6339}
6340
6341void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6342{
Elliott Hughes87cebad2014-05-22 10:14:43 -07006343 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08006344
Glenn Kasten44182c22015-03-05 17:12:23 -08006345 dumpBase(fd, args);
6346
6347 if (mActiveTracks.size() == 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006348 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006349 }
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006350 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006351 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08006352
6353 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
6354 const FastCaptureDumpState copy(mFastCaptureDumpState);
6355 copy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006356}
6357
Glenn Kasten0f11b512014-01-31 16:18:54 -08006358void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006359{
6360 const size_t SIZE = 256;
6361 char buffer[SIZE];
6362 String8 result;
6363
Marco Nelissenb2208842014-02-07 14:00:50 -08006364 size_t numtracks = mTracks.size();
6365 size_t numactive = mActiveTracks.size();
6366 size_t numactiveseen = 0;
Elliott Hughes87cebad2014-05-22 10:14:43 -07006367 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08006368 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006369 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08006370 RecordTrack::appendDumpHeader(result);
6371 for (size_t i = 0; i < numtracks ; ++i) {
6372 sp<RecordTrack> track = mTracks[i];
6373 if (track != 0) {
6374 bool active = mActiveTracks.indexOf(track) >= 0;
6375 if (active) {
6376 numactiveseen++;
6377 }
6378 track->dump(buffer, SIZE, active);
6379 result.append(buffer);
6380 }
Eric Laurent81784c32012-11-19 14:55:58 -08006381 }
Marco Nelissenb2208842014-02-07 14:00:50 -08006382 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006383 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006384 }
6385
Marco Nelissenb2208842014-02-07 14:00:50 -08006386 if (numactiveseen != numactive) {
6387 snprintf(buffer, SIZE, " The following tracks are in the active list but"
6388 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006389 result.append(buffer);
6390 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08006391 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08006392 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08006393 if (mTracks.indexOf(track) < 0) {
6394 track->dump(buffer, SIZE, true);
6395 result.append(buffer);
6396 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006397 }
Eric Laurent81784c32012-11-19 14:55:58 -08006398
6399 }
6400 write(fd, result.string(), result.size());
6401}
6402
Andy Hung73c02e42015-03-29 01:13:58 -07006403
6404void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
6405{
6406 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6407 RecordThread *recordThread = (RecordThread *) threadBase.get();
6408 mRsmpInFront = recordThread->mRsmpInRear;
6409 mRsmpInUnrel = 0;
6410}
6411
6412void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
6413 size_t *framesAvailable, bool *hasOverrun)
6414{
6415 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6416 RecordThread *recordThread = (RecordThread *) threadBase.get();
6417 const int32_t rear = recordThread->mRsmpInRear;
6418 const int32_t front = mRsmpInFront;
6419 const ssize_t filled = rear - front;
6420
6421 size_t framesIn;
6422 bool overrun = false;
6423 if (filled < 0) {
6424 // should not happen, but treat like a massive overrun and re-sync
6425 framesIn = 0;
6426 mRsmpInFront = rear;
6427 overrun = true;
6428 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
6429 framesIn = (size_t) filled;
6430 } else {
6431 // client is not keeping up with server, but give it latest data
6432 framesIn = recordThread->mRsmpInFrames;
6433 mRsmpInFront = /* front = */ rear - framesIn;
6434 overrun = true;
6435 }
6436 if (framesAvailable != NULL) {
6437 *framesAvailable = framesIn;
6438 }
6439 if (hasOverrun != NULL) {
6440 *hasOverrun = overrun;
6441 }
6442}
6443
Eric Laurent81784c32012-11-19 14:55:58 -08006444// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006445status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
6446 AudioBufferProvider::Buffer* buffer, int64_t pts __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006447{
Andy Hung73c02e42015-03-29 01:13:58 -07006448 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006449 if (threadBase == 0) {
6450 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006451 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006452 return NOT_ENOUGH_DATA;
6453 }
6454 RecordThread *recordThread = (RecordThread *) threadBase.get();
6455 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07006456 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07006457 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006458 // FIXME should not be P2 (don't want to increase latency)
6459 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006460 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07006461 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006462 front &= recordThread->mRsmpInFramesP2 - 1;
6463 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07006464 if (part1 > (size_t) filled) {
6465 part1 = filled;
6466 }
6467 size_t ask = buffer->frameCount;
6468 ALOG_ASSERT(ask > 0);
6469 if (part1 > ask) {
6470 part1 = ask;
6471 }
6472 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07006473 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07006474 buffer->raw = NULL;
6475 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07006476 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07006477 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08006478 }
6479
Andy Hung57446612015-04-19 23:56:46 -07006480 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07006481 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07006482 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08006483 return NO_ERROR;
6484}
6485
6486// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006487void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
6488 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006489{
Glenn Kasten85948432013-08-19 12:09:05 -07006490 size_t stepCount = buffer->frameCount;
6491 if (stepCount == 0) {
6492 return;
6493 }
Andy Hung73c02e42015-03-29 01:13:58 -07006494 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
6495 mRsmpInUnrel -= stepCount;
6496 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07006497 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006498 buffer->frameCount = 0;
6499}
6500
Andy Hung97a893e2015-03-29 01:03:07 -07006501AudioFlinger::RecordThread::RecordBufferConverter::RecordBufferConverter(
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 mSrcChannelMask(AUDIO_CHANNEL_INVALID), // updateParameters will set following vars
6507 // mSrcFormat
6508 // mSrcSampleRate
6509 // mDstChannelMask
6510 // mDstFormat
6511 // mDstSampleRate
6512 // mSrcChannelCount
6513 // mDstChannelCount
6514 // mDstFrameSize
6515 mBuf(NULL), mBufFrames(0), mBufFrameSize(0),
Andy Hungd330ee42015-04-20 13:23:41 -07006516 mResampler(NULL),
6517 mIsLegacyDownmix(false),
6518 mIsLegacyUpmix(false),
6519 mRequiresFloat(false),
6520 mInputConverterProvider(NULL)
Andy Hung97a893e2015-03-29 01:03:07 -07006521{
6522 (void)updateParameters(srcChannelMask, srcFormat, srcSampleRate,
6523 dstChannelMask, dstFormat, dstSampleRate);
6524}
6525
6526AudioFlinger::RecordThread::RecordBufferConverter::~RecordBufferConverter() {
6527 free(mBuf);
6528 delete mResampler;
Andy Hungd330ee42015-04-20 13:23:41 -07006529 delete mInputConverterProvider;
Andy Hung97a893e2015-03-29 01:03:07 -07006530}
6531
6532size_t AudioFlinger::RecordThread::RecordBufferConverter::convert(void *dst,
6533 AudioBufferProvider *provider, size_t frames)
6534{
Andy Hungd330ee42015-04-20 13:23:41 -07006535 if (mInputConverterProvider != NULL) {
6536 mInputConverterProvider->setBufferProvider(provider);
6537 provider = mInputConverterProvider;
6538 }
6539
6540 if (mResampler == NULL) {
Andy Hung97a893e2015-03-29 01:03:07 -07006541 ALOGVV("NO RESAMPLING sampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6542 mSrcSampleRate, mSrcFormat, mDstFormat);
6543
6544 AudioBufferProvider::Buffer buffer;
6545 for (size_t i = frames; i > 0; ) {
6546 buffer.frameCount = i;
6547 status_t status = provider->getNextBuffer(&buffer, 0);
6548 if (status != OK || buffer.frameCount == 0) {
6549 frames -= i; // cannot fill request.
6550 break;
6551 }
Andy Hungd330ee42015-04-20 13:23:41 -07006552 // format convert to destination buffer
6553 convertNoResampler(dst, buffer.raw, buffer.frameCount);
Andy Hung97a893e2015-03-29 01:03:07 -07006554
6555 dst = (int8_t*)dst + buffer.frameCount * mDstFrameSize;
6556 i -= buffer.frameCount;
6557 provider->releaseBuffer(&buffer);
6558 }
6559 } else {
6560 ALOGVV("RESAMPLING mSrcSampleRate:%u mDstSampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6561 mSrcSampleRate, mDstSampleRate, mSrcFormat, mDstFormat);
6562
Andy Hungd330ee42015-04-20 13:23:41 -07006563 // reallocate buffer if needed
6564 if (mBufFrameSize != 0 && mBufFrames < frames) {
6565 free(mBuf);
6566 mBufFrames = frames;
6567 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
6568 }
Andy Hung97a893e2015-03-29 01:03:07 -07006569 // resampler accumulates, but we only have one source track
Andy Hungd330ee42015-04-20 13:23:41 -07006570 memset(mBuf, 0, frames * mBufFrameSize);
6571 frames = mResampler->resample((int32_t*)mBuf, frames, provider);
6572 // format convert to destination buffer
6573 convertResampler(dst, mBuf, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006574 }
6575 return frames;
6576}
6577
6578status_t AudioFlinger::RecordThread::RecordBufferConverter::updateParameters(
6579 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6580 uint32_t srcSampleRate,
6581 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6582 uint32_t dstSampleRate)
6583{
6584 // quick evaluation if there is any change.
6585 if (mSrcFormat == srcFormat
6586 && mSrcChannelMask == srcChannelMask
6587 && mSrcSampleRate == srcSampleRate
6588 && mDstFormat == dstFormat
6589 && mDstChannelMask == dstChannelMask
6590 && mDstSampleRate == dstSampleRate) {
6591 return NO_ERROR;
6592 }
6593
Andy Hungdb4c0312015-05-06 08:46:52 -07006594 ALOGV("RecordBufferConverter updateParameters srcMask:%#x dstMask:%#x"
6595 " srcFormat:%#x dstFormat:%#x srcRate:%u dstRate:%u",
6596 srcChannelMask, dstChannelMask, srcFormat, dstFormat, srcSampleRate, dstSampleRate);
Andy Hung97a893e2015-03-29 01:03:07 -07006597 const bool valid =
6598 audio_is_input_channel(srcChannelMask)
6599 && audio_is_input_channel(dstChannelMask)
6600 && audio_is_valid_format(srcFormat) && audio_is_linear_pcm(srcFormat)
6601 && audio_is_valid_format(dstFormat) && audio_is_linear_pcm(dstFormat)
6602 && (srcSampleRate <= dstSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX)
6603 ; // no upsampling checks for now
6604 if (!valid) {
6605 return BAD_VALUE;
6606 }
6607
6608 mSrcFormat = srcFormat;
6609 mSrcChannelMask = srcChannelMask;
6610 mSrcSampleRate = srcSampleRate;
6611 mDstFormat = dstFormat;
6612 mDstChannelMask = dstChannelMask;
6613 mDstSampleRate = dstSampleRate;
6614
6615 // compute derived parameters
6616 mSrcChannelCount = audio_channel_count_from_in_mask(srcChannelMask);
6617 mDstChannelCount = audio_channel_count_from_in_mask(dstChannelMask);
6618 mDstFrameSize = mDstChannelCount * audio_bytes_per_sample(mDstFormat);
6619
Andy Hungd330ee42015-04-20 13:23:41 -07006620 // do we need to resample?
6621 delete mResampler;
6622 mResampler = NULL;
6623 if (mSrcSampleRate != mDstSampleRate) {
6624 mResampler = AudioResampler::create(AUDIO_FORMAT_PCM_FLOAT,
6625 mSrcChannelCount, mDstSampleRate);
6626 mResampler->setSampleRate(mSrcSampleRate);
6627 mResampler->setVolume(AudioMixer::UNITY_GAIN_FLOAT, AudioMixer::UNITY_GAIN_FLOAT);
6628 }
6629
6630 // are we running legacy channel conversion modes?
6631 mIsLegacyDownmix = (mSrcChannelMask == AUDIO_CHANNEL_IN_STEREO
6632 || mSrcChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK)
6633 && mDstChannelMask == AUDIO_CHANNEL_IN_MONO;
6634 mIsLegacyUpmix = mSrcChannelMask == AUDIO_CHANNEL_IN_MONO
6635 && (mDstChannelMask == AUDIO_CHANNEL_IN_STEREO
6636 || mDstChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK);
6637
6638 // do we need to process in float?
6639 mRequiresFloat = mResampler != NULL || mIsLegacyDownmix || mIsLegacyUpmix;
6640
6641 // do we need a staging buffer to convert for destination (we can still optimize this)?
6642 // we use mBufFrameSize > 0 to indicate both frame size as well as buffer necessity
6643 if (mResampler != NULL) {
6644 mBufFrameSize = max(mSrcChannelCount, FCC_2)
6645 * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
6646 } else if ((mIsLegacyUpmix || mIsLegacyDownmix) && mDstFormat != AUDIO_FORMAT_PCM_FLOAT) {
6647 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
6648 } else if (mSrcChannelMask != mDstChannelMask && mDstFormat != mSrcFormat) {
Andy Hung97a893e2015-03-29 01:03:07 -07006649 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(mSrcFormat);
6650 } else {
6651 mBufFrameSize = 0;
6652 }
6653 mBufFrames = 0; // force the buffer to be resized.
6654
Andy Hungd330ee42015-04-20 13:23:41 -07006655 // do we need an input converter buffer provider to give us float?
6656 delete mInputConverterProvider;
6657 mInputConverterProvider = NULL;
6658 if (mRequiresFloat && mSrcFormat != AUDIO_FORMAT_PCM_FLOAT) {
6659 mInputConverterProvider = new ReformatBufferProvider(
6660 audio_channel_count_from_in_mask(mSrcChannelMask),
6661 mSrcFormat,
6662 AUDIO_FORMAT_PCM_FLOAT,
6663 256 /* provider buffer frame count */);
6664 }
6665
6666 // do we need a remixer to do channel mask conversion
6667 if (!mIsLegacyDownmix && !mIsLegacyUpmix && mSrcChannelMask != mDstChannelMask) {
6668 (void) memcpy_by_index_array_initialization_from_channel_mask(
6669 mIdxAry, ARRAY_SIZE(mIdxAry), mDstChannelMask, mSrcChannelMask);
Andy Hung97a893e2015-03-29 01:03:07 -07006670 }
6671 return NO_ERROR;
6672}
6673
Andy Hungd330ee42015-04-20 13:23:41 -07006674void AudioFlinger::RecordThread::RecordBufferConverter::convertNoResampler(
6675 void *dst, const void *src, size_t frames)
Andy Hung97a893e2015-03-29 01:03:07 -07006676{
Andy Hungd330ee42015-04-20 13:23:41 -07006677 // src is native type unless there is legacy upmix or downmix, whereupon it is float.
Andy Hung97a893e2015-03-29 01:03:07 -07006678 if (mBufFrameSize != 0 && mBufFrames < frames) {
6679 free(mBuf);
6680 mBufFrames = frames;
6681 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
6682 }
Andy Hungd330ee42015-04-20 13:23:41 -07006683 // do we need to do legacy upmix and downmix?
6684 if (mIsLegacyUpmix || mIsLegacyDownmix) {
Andy Hung97a893e2015-03-29 01:03:07 -07006685 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07006686 if (mIsLegacyUpmix) {
6687 upmix_to_stereo_float_from_mono_float((float *)dstBuf,
6688 (const float *)src, frames);
6689 } else /*mIsLegacyDownmix */ {
6690 downmix_to_mono_float_from_stereo_float((float *)dstBuf,
6691 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006692 }
Andy Hungd330ee42015-04-20 13:23:41 -07006693 if (mBuf != NULL) {
6694 memcpy_by_audio_format(dst, mDstFormat, mBuf, AUDIO_FORMAT_PCM_FLOAT,
6695 frames * mDstChannelCount);
6696 }
6697 return;
6698 }
6699 // do we need to do channel mask conversion?
6700 if (mSrcChannelMask != mDstChannelMask) {
Andy Hung97a893e2015-03-29 01:03:07 -07006701 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07006702 memcpy_by_index_array(dstBuf, mDstChannelCount,
6703 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mSrcFormat), frames);
6704 if (dstBuf == dst) {
6705 return; // format is the same
6706 }
6707 }
6708 // convert to destination buffer
6709 const void *convertBuf = mBuf != NULL ? mBuf : src;
6710 memcpy_by_audio_format(dst, mDstFormat, convertBuf, mSrcFormat,
6711 frames * mDstChannelCount);
6712}
6713
6714void AudioFlinger::RecordThread::RecordBufferConverter::convertResampler(
6715 void *dst, /*not-a-const*/ void *src, size_t frames)
6716{
6717 // src buffer format is ALWAYS float when entering this routine
6718 if (mIsLegacyUpmix) {
6719 ; // mono to stereo already handled by resampler
6720 } else if (mIsLegacyDownmix
6721 || (mSrcChannelMask == mDstChannelMask && mSrcChannelCount == 1)) {
6722 // the resampler outputs stereo for mono input channel (a feature?)
6723 // must convert to mono
6724 downmix_to_mono_float_from_stereo_float((float *)src,
6725 (const float *)src, frames);
6726 } else if (mSrcChannelMask != mDstChannelMask) {
6727 // convert to mono channel again for channel mask conversion (could be skipped
6728 // with further optimization).
Andy Hung97a893e2015-03-29 01:03:07 -07006729 if (mSrcChannelCount == 1) {
Andy Hungd330ee42015-04-20 13:23:41 -07006730 downmix_to_mono_float_from_stereo_float((float *)src,
6731 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006732 }
Andy Hungd330ee42015-04-20 13:23:41 -07006733 // convert to destination format (in place, OK as float is larger than other types)
6734 if (mDstFormat != AUDIO_FORMAT_PCM_FLOAT) {
6735 memcpy_by_audio_format(src, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
6736 frames * mSrcChannelCount);
6737 }
6738 // channel convert and save to dst
6739 memcpy_by_index_array(dst, mDstChannelCount,
6740 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mDstFormat), frames);
6741 return;
Andy Hung97a893e2015-03-29 01:03:07 -07006742 }
Andy Hungd330ee42015-04-20 13:23:41 -07006743 // convert to destination format and save to dst
6744 memcpy_by_audio_format(dst, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
6745 frames * mDstChannelCount);
Andy Hung97a893e2015-03-29 01:03:07 -07006746}
6747
Eric Laurent10351942014-05-08 18:49:52 -07006748bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
6749 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006750{
6751 bool reconfig = false;
6752
Eric Laurent10351942014-05-08 18:49:52 -07006753 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006754
Eric Laurent10351942014-05-08 18:49:52 -07006755 audio_format_t reqFormat = mFormat;
6756 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07006757 // TODO this may change if we want to support capture from HDMI PCM multi channel (e.g on TVs).
Eric Laurent10351942014-05-08 18:49:52 -07006758 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
6759
6760 AudioParameter param = AudioParameter(keyValuePair);
6761 int value;
6762 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
6763 // channel count change can be requested. Do we mandate the first client defines the
6764 // HAL sampling rate and channel count or do we allow changes on the fly?
6765 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6766 samplingRate = value;
6767 reconfig = true;
6768 }
6769 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07006770 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07006771 status = BAD_VALUE;
6772 } else {
6773 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08006774 reconfig = true;
6775 }
Eric Laurent10351942014-05-08 18:49:52 -07006776 }
6777 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
6778 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07006779 if (!audio_is_input_channel(mask) ||
6780 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07006781 status = BAD_VALUE;
6782 } else {
6783 channelMask = mask;
6784 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006785 }
Eric Laurent10351942014-05-08 18:49:52 -07006786 }
6787 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6788 // do not accept frame count changes if tracks are open as the track buffer
6789 // size depends on frame count and correct behavior would not be guaranteed
6790 // if frame count is changed after track creation
6791 if (mActiveTracks.size() > 0) {
6792 status = INVALID_OPERATION;
6793 } else {
6794 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006795 }
Eric Laurent10351942014-05-08 18:49:52 -07006796 }
6797 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6798 // forward device change to effects that have requested to be
6799 // aware of attached audio device.
6800 for (size_t i = 0; i < mEffectChains.size(); i++) {
6801 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08006802 }
Eric Laurent81784c32012-11-19 14:55:58 -08006803
Eric Laurent10351942014-05-08 18:49:52 -07006804 // store input device and output device but do not forward output device to audio HAL.
6805 // Note that status is ignored by the caller for output device
6806 // (see AudioFlinger::setParameters()
6807 if (audio_is_output_devices(value)) {
6808 mOutDevice = value;
6809 status = BAD_VALUE;
6810 } else {
6811 mInDevice = value;
Eric Laurente8726fe2015-06-26 09:39:24 -07006812 if (value != AUDIO_DEVICE_NONE) {
6813 mPrevInDevice = value;
6814 }
Eric Laurent10351942014-05-08 18:49:52 -07006815 // disable AEC and NS if the device is a BT SCO headset supporting those
6816 // pre processings
6817 if (mTracks.size() > 0) {
6818 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6819 mAudioFlinger->btNrecIsOff();
6820 for (size_t i = 0; i < mTracks.size(); i++) {
6821 sp<RecordTrack> track = mTracks[i];
6822 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
6823 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08006824 }
6825 }
6826 }
Eric Laurent10351942014-05-08 18:49:52 -07006827 }
6828 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
6829 mAudioSource != (audio_source_t)value) {
6830 // forward device change to effects that have requested to be
6831 // aware of attached audio device.
6832 for (size_t i = 0; i < mEffectChains.size(); i++) {
6833 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08006834 }
Eric Laurent10351942014-05-08 18:49:52 -07006835 mAudioSource = (audio_source_t)value;
6836 }
Glenn Kastene198c362013-08-13 09:13:36 -07006837
Eric Laurent10351942014-05-08 18:49:52 -07006838 if (status == NO_ERROR) {
6839 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6840 keyValuePair.string());
6841 if (status == INVALID_OPERATION) {
6842 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006843 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6844 keyValuePair.string());
Eric Laurent10351942014-05-08 18:49:52 -07006845 }
6846 if (reconfig) {
6847 if (status == BAD_VALUE &&
Andy Hung97a893e2015-03-29 01:03:07 -07006848 audio_is_linear_pcm(mInput->stream->common.get_format(&mInput->stream->common)) &&
6849 audio_is_linear_pcm(reqFormat) &&
Eric Laurent10351942014-05-08 18:49:52 -07006850 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
Andy Hung97a893e2015-03-29 01:03:07 -07006851 <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate)) &&
Andy Hunge5412692014-05-16 11:25:07 -07006852 audio_channel_count_from_in_mask(
Andy Hungd1abb8f2015-05-05 23:42:34 -07006853 mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07006854 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006855 }
Eric Laurent10351942014-05-08 18:49:52 -07006856 if (status == NO_ERROR) {
6857 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07006858 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08006859 }
6860 }
Eric Laurent81784c32012-11-19 14:55:58 -08006861 }
Eric Laurent10351942014-05-08 18:49:52 -07006862
Eric Laurent81784c32012-11-19 14:55:58 -08006863 return reconfig;
6864}
6865
6866String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6867{
Eric Laurent81784c32012-11-19 14:55:58 -08006868 Mutex::Autolock _l(mLock);
6869 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07006870 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08006871 }
6872
Glenn Kastend8ea6992013-07-16 14:17:15 -07006873 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
6874 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08006875 free(s);
6876 return out_s8;
6877}
6878
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07006879void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07006880 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
6881
6882 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08006883
6884 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07006885 case AUDIO_INPUT_OPENED:
6886 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07006887 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07006888 desc->mChannelMask = mChannelMask;
6889 desc->mSamplingRate = mSampleRate;
6890 desc->mFormat = mFormat;
6891 desc->mFrameCount = mFrameCount;
6892 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006893 break;
6894
Eric Laurent73e26b62015-04-27 16:55:58 -07006895 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08006896 default:
6897 break;
6898 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07006899 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08006900}
6901
Glenn Kastendeca2ae2014-02-07 10:25:56 -08006902void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006903{
Eric Laurent81784c32012-11-19 14:55:58 -08006904 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
6905 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Andy Hunge5412692014-05-16 11:25:07 -07006906 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Andy Hungd330ee42015-04-20 13:23:41 -07006907 if (mChannelCount > FCC_8) {
6908 ALOGE("HAL channel count %d > %d", mChannelCount, FCC_8);
6909 }
Andy Hung463be252014-07-10 16:56:07 -07006910 mHALFormat = mInput->stream->common.get_format(&mInput->stream->common);
6911 mFormat = mHALFormat;
Andy Hungd330ee42015-04-20 13:23:41 -07006912 if (!audio_is_linear_pcm(mFormat)) {
6913 ALOGE("HAL format %#x is not linear pcm", mFormat);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07006914 }
Eric Laurent665470b2014-07-03 16:37:08 -07006915 mFrameSize = audio_stream_in_frame_size(mInput->stream);
Glenn Kasten548efc92012-11-29 08:48:51 -08006916 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
6917 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006918 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08006919 // 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 -07006920 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08006921 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006922 // A larger value should allow more old data to be read after a track calls start(),
6923 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07006924 //
6925 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08006926 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07006927 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07006928 free(mRsmpInBuffer);
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006929
6930 // TODO optimize audio capture buffer sizes ...
6931 // Here we calculate the size of the sliding buffer used as a source
6932 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
6933 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
6934 // be better to have it derived from the pipe depth in the long term.
6935 // The current value is higher than necessary. However it should not add to latency.
6936
Glenn Kasten85948432013-08-19 12:09:05 -07006937 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Andy Hung57446612015-04-19 23:56:46 -07006938 (void)posix_memalign(&mRsmpInBuffer, 32, (mRsmpInFramesP2 + mFrameCount - 1) * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006939
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006940 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
6941 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08006942}
6943
Glenn Kasten5f972c02014-01-13 09:59:31 -08006944uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08006945{
6946 Mutex::Autolock _l(mLock);
6947 if (initCheck() != NO_ERROR) {
6948 return 0;
6949 }
6950
6951 return mInput->stream->get_input_frames_lost(mInput->stream);
6952}
6953
6954uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
6955{
6956 Mutex::Autolock _l(mLock);
6957 uint32_t result = 0;
6958 if (getEffectChain_l(sessionId) != 0) {
6959 result = EFFECT_SESSION;
6960 }
6961
6962 for (size_t i = 0; i < mTracks.size(); ++i) {
6963 if (sessionId == mTracks[i]->sessionId()) {
6964 result |= TRACK_SESSION;
6965 break;
6966 }
6967 }
6968
6969 return result;
6970}
6971
6972KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
6973{
6974 KeyedVector<int, bool> ids;
6975 Mutex::Autolock _l(mLock);
6976 for (size_t j = 0; j < mTracks.size(); ++j) {
6977 sp<RecordThread::RecordTrack> track = mTracks[j];
6978 int sessionId = track->sessionId();
6979 if (ids.indexOfKey(sessionId) < 0) {
6980 ids.add(sessionId, true);
6981 }
6982 }
6983 return ids;
6984}
6985
6986AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
6987{
6988 Mutex::Autolock _l(mLock);
6989 AudioStreamIn *input = mInput;
6990 mInput = NULL;
6991 return input;
6992}
6993
6994// this method must always be called either with ThreadBase mLock held or inside the thread loop
6995audio_stream_t* AudioFlinger::RecordThread::stream() const
6996{
6997 if (mInput == NULL) {
6998 return NULL;
6999 }
7000 return &mInput->stream->common;
7001}
7002
7003status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7004{
7005 // only one chain per input thread
7006 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07007007 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08007008 return INVALID_OPERATION;
7009 }
7010 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07007011 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08007012 chain->setInBuffer(NULL);
7013 chain->setOutBuffer(NULL);
7014
7015 checkSuspendOnAddEffectChain_l(chain);
7016
Eric Laurent1b928682014-10-02 19:41:47 -07007017 // make sure enabled pre processing effects state is communicated to the HAL as we
7018 // just moved them to a new input stream.
7019 chain->syncHalEffectsState();
7020
Eric Laurent81784c32012-11-19 14:55:58 -08007021 mEffectChains.add(chain);
7022
7023 return NO_ERROR;
7024}
7025
7026size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7027{
7028 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
7029 ALOGW_IF(mEffectChains.size() != 1,
7030 "removeEffectChain_l() %p invalid chain size %d on thread %p",
7031 chain.get(), mEffectChains.size(), this);
7032 if (mEffectChains.size() == 1) {
7033 mEffectChains.removeAt(0);
7034 }
7035 return 0;
7036}
7037
Eric Laurent1c333e22014-05-20 10:48:17 -07007038status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
7039 audio_patch_handle_t *handle)
7040{
7041 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007042
7043 // store new device and send to effects
7044 mInDevice = patch->sources[0].ext.device.type;
Eric Laurent296fb132015-05-01 11:38:42 -07007045 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07007046 for (size_t i = 0; i < mEffectChains.size(); i++) {
7047 mEffectChains[i]->setDevice_l(mInDevice);
7048 }
7049
7050 // disable AEC and NS if the device is a BT SCO headset supporting those
7051 // pre processings
7052 if (mTracks.size() > 0) {
7053 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7054 mAudioFlinger->btNrecIsOff();
7055 for (size_t i = 0; i < mTracks.size(); i++) {
7056 sp<RecordTrack> track = mTracks[i];
7057 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7058 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
7059 }
7060 }
7061
7062 // store new source and send to effects
7063 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7064 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07007065 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07007066 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07007067 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007068 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007069
Eric Laurent054d9d32015-04-24 08:48:48 -07007070 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007071 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
7072 status = hwDevice->create_audio_patch(hwDevice,
7073 patch->num_sources,
7074 patch->sources,
7075 patch->num_sinks,
7076 patch->sinks,
7077 handle);
7078 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007079 char *address;
7080 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
7081 address = audio_device_address_to_parameter(
7082 patch->sources[0].ext.device.type,
7083 patch->sources[0].ext.device.address);
7084 } else {
7085 address = (char *)calloc(1, 1);
7086 }
7087 AudioParameter param = AudioParameter(String8(address));
7088 free(address);
7089 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING),
7090 (int)patch->sources[0].ext.device.type);
7091 param.addInt(String8(AUDIO_PARAMETER_STREAM_INPUT_SOURCE),
7092 (int)patch->sinks[0].ext.mix.usecase.source);
7093 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7094 param.toString().string());
7095 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07007096 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007097
Eric Laurente8726fe2015-06-26 09:39:24 -07007098 if (mInDevice != mPrevInDevice) {
7099 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
7100 mPrevInDevice = mInDevice;
7101 }
Eric Laurent296fb132015-05-01 11:38:42 -07007102
Eric Laurent1c333e22014-05-20 10:48:17 -07007103 return status;
7104}
7105
7106status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
7107{
7108 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007109
7110 mInDevice = AUDIO_DEVICE_NONE;
7111
Eric Laurent1c333e22014-05-20 10:48:17 -07007112 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
7113 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
7114 status = hwDevice->release_audio_patch(hwDevice, handle);
7115 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007116 AudioParameter param;
7117 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
7118 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7119 param.toString().string());
Eric Laurent1c333e22014-05-20 10:48:17 -07007120 }
7121 return status;
7122}
7123
Eric Laurent83b88082014-06-20 18:31:16 -07007124void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
7125{
7126 Mutex::Autolock _l(mLock);
7127 mTracks.add(record);
7128}
7129
7130void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
7131{
7132 Mutex::Autolock _l(mLock);
7133 destroyTrack_l(record);
7134}
7135
7136void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
7137{
7138 ThreadBase::getAudioPortConfig(config);
7139 config->role = AUDIO_PORT_ROLE_SINK;
7140 config->ext.mix.hw_module = mInput->audioHwDev->handle();
7141 config->ext.mix.usecase.source = mAudioSource;
7142}
Eric Laurent1c333e22014-05-20 10:48:17 -07007143
Glenn Kasten63238ef2015-03-02 15:50:29 -08007144} // namespace android