blob: 489f2d4f6cee61d1db0c825e549d8e9192f2bf59 [file] [log] [blame]
Eric Laurent81784c32012-11-19 14:55:58 -08001/*
2**
3** Copyright 2012, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
Alex Ray371eb972012-11-30 11:11:54 -080021#define ATRACE_TAG ATRACE_TAG_AUDIO
Eric Laurent81784c32012-11-19 14:55:58 -080022
Glenn Kasten153b9fe2013-07-15 11:23:36 -070023#include "Configuration.h"
Eric Laurent81784c32012-11-19 14:55:58 -080024#include <math.h>
25#include <fcntl.h>
Glenn Kastenad8510a2015-02-17 16:24:07 -080026#include <linux/futex.h>
Eric Laurent81784c32012-11-19 14:55:58 -080027#include <sys/stat.h>
Glenn Kastenad8510a2015-02-17 16:24:07 -080028#include <sys/syscall.h>
Eric Laurent81784c32012-11-19 14:55:58 -080029#include <cutils/properties.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070030#include <media/AudioParameter.h>
Andy Hungcd044842014-08-07 11:04:34 -070031#include <media/AudioResamplerPublic.h>
Eric Laurent81784c32012-11-19 14:55:58 -080032#include <utils/Log.h>
Alex Ray371eb972012-11-30 11:11:54 -080033#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080034
35#include <private/media/AudioTrackShared.h>
36#include <hardware/audio.h>
37#include <audio_effects/effect_ns.h>
38#include <audio_effects/effect_aec.h>
39#include <audio_utils/primitives.h>
Andy Hung98ef9782014-03-04 14:46:50 -080040#include <audio_utils/format.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070041#include <audio_utils/minifloat.h>
Eric Laurent81784c32012-11-19 14:55:58 -080042
43// NBAIO implementations
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070044#include <media/nbaio/AudioStreamInSource.h>
Eric Laurent81784c32012-11-19 14:55:58 -080045#include <media/nbaio/AudioStreamOutSink.h>
46#include <media/nbaio/MonoPipe.h>
47#include <media/nbaio/MonoPipeReader.h>
48#include <media/nbaio/Pipe.h>
49#include <media/nbaio/PipeReader.h>
50#include <media/nbaio/SourceAudioBufferProvider.h>
51
52#include <powermanager/PowerManager.h>
53
54#include <common_time/cc_helper.h>
55#include <common_time/local_clock.h>
56
57#include "AudioFlinger.h"
58#include "AudioMixer.h"
Andy Hungd330ee42015-04-20 13:23:41 -070059#include "BufferProviders.h"
Eric Laurent81784c32012-11-19 14:55:58 -080060#include "FastMixer.h"
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070061#include "FastCapture.h"
Eric Laurent81784c32012-11-19 14:55:58 -080062#include "ServiceUtilities.h"
63#include "SchedulingPolicyService.h"
64
Eric Laurent81784c32012-11-19 14:55:58 -080065#ifdef ADD_BATTERY_DATA
66#include <media/IMediaPlayerService.h>
67#include <media/IMediaDeathNotifier.h>
68#endif
69
Eric Laurent81784c32012-11-19 14:55:58 -080070#ifdef DEBUG_CPU_USAGE
71#include <cpustats/CentralTendencyStatistics.h>
72#include <cpustats/ThreadCpuUsage.h>
73#endif
74
75// ----------------------------------------------------------------------------
76
77// Note: the following macro is used for extremely verbose logging message. In
78// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
79// 0; but one side effect of this is to turn all LOGV's as well. Some messages
80// are so verbose that we want to suppress them even when we have ALOG_ASSERT
81// turned on. Do not uncomment the #def below unless you really know what you
82// are doing and want to see all of the extremely verbose messages.
83//#define VERY_VERY_VERBOSE_LOGGING
84#ifdef VERY_VERY_VERBOSE_LOGGING
85#define ALOGVV ALOGV
86#else
87#define ALOGVV(a...) do { } while(0)
88#endif
89
Andy Hung6770c6f2015-04-07 13:43:36 -070090// TODO: Move these macro/inlines to a header file.
Glenn Kasten49d00ad2014-07-21 11:22:03 -070091#define max(a, b) ((a) > (b) ? (a) : (b))
Andy Hung6770c6f2015-04-07 13:43:36 -070092template <typename T>
93static inline T min(const T& a, const T& b)
94{
95 return a < b ? a : b;
96}
Glenn Kasten49d00ad2014-07-21 11:22:03 -070097
Andy Hungd330ee42015-04-20 13:23:41 -070098#ifndef ARRAY_SIZE
99#define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
100#endif
101
Eric Laurent81784c32012-11-19 14:55:58 -0800102namespace android {
103
104// retry counts for buffer fill timeout
105// 50 * ~20msecs = 1 second
106static const int8_t kMaxTrackRetries = 50;
107static const int8_t kMaxTrackStartupRetries = 50;
108// allow less retry attempts on direct output thread.
109// direct outputs can be a scarce resource in audio hardware and should
110// be released as quickly as possible.
111static const int8_t kMaxTrackRetriesDirect = 2;
112
113// don't warn about blocked writes or record buffer overflows more often than this
114static const nsecs_t kWarningThrottleNs = seconds(5);
115
116// RecordThread loop sleep time upon application overrun or audio HAL read error
117static const int kRecordThreadSleepUs = 5000;
118
Eric Laurent10351942014-05-08 18:49:52 -0700119// maximum time to wait in sendConfigEvent_l() for a status to be received
120static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800121
122// minimum sleep time for the mixer thread loop when tracks are active but in underrun
123static const uint32_t kMinThreadSleepTimeUs = 5000;
124// maximum divider applied to the active sleep time in the mixer thread loop
125static const uint32_t kMaxThreadSleepTimeShift = 2;
126
Andy Hung09a50072014-02-27 14:30:47 -0800127// minimum normal sink buffer size, expressed in milliseconds rather than frames
128static const uint32_t kMinNormalSinkBufferSizeMs = 20;
129// maximum normal sink buffer size
130static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800131
Eric Laurent972a1732013-09-04 09:42:59 -0700132// Offloaded output thread standby delay: allows track transition without going to standby
133static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
134
Eric Laurent81784c32012-11-19 14:55:58 -0800135// Whether to use fast mixer
136static const enum {
137 FastMixer_Never, // never initialize or use: for debugging only
138 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
139 // normal mixer multiplier is 1
140 FastMixer_Static, // initialize if needed, then use all the time if initialized,
141 // multiplier is calculated based on min & max normal mixer buffer size
142 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
143 // multiplier is calculated based on min & max normal mixer buffer size
144 // FIXME for FastMixer_Dynamic:
145 // Supporting this option will require fixing HALs that can't handle large writes.
146 // For example, one HAL implementation returns an error from a large write,
147 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
148 // We could either fix the HAL implementations, or provide a wrapper that breaks
149 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
150} kUseFastMixer = FastMixer_Static;
151
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700152// Whether to use fast capture
153static const enum {
154 FastCapture_Never, // never initialize or use: for debugging only
155 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
156 FastCapture_Static, // initialize if needed, then use all the time if initialized
157} kUseFastCapture = FastCapture_Static;
158
Eric Laurent81784c32012-11-19 14:55:58 -0800159// Priorities for requestPriority
160static const int kPriorityAudioApp = 2;
161static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700162static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800163
164// IAudioFlinger::createTrack() reports back to client the total size of shared memory area
165// for the track. The client then sub-divides this into smaller buffers for its use.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800166// Currently the client uses N-buffering by default, but doesn't tell us about the value of N.
167// So for now we just assume that client is double-buffered for fast tracks.
168// FIXME It would be better for client to tell AudioFlinger the value of N,
169// so AudioFlinger could allocate the right amount of memory.
Eric Laurent81784c32012-11-19 14:55:58 -0800170// See the client's minBufCount and mNotificationFramesAct calculations for details.
Glenn Kasten03490092014-05-27 12:30:54 -0700171
172// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800173static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800174
Glenn Kasten03490092014-05-27 12:30:54 -0700175// The minimum and maximum allowed values
176static const int kFastTrackMultiplierMin = 1;
177static const int kFastTrackMultiplierMax = 2;
178
179// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
180static int sFastTrackMultiplier = kFastTrackMultiplier;
181
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700182// See Thread::readOnlyHeap().
183// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
184// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
185// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Glenn Kasten9f81de32014-07-27 15:02:23 -0700186static const size_t kRecordThreadReadOnlyHeapSize = 0x2000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700187
Eric Laurent81784c32012-11-19 14:55:58 -0800188// ----------------------------------------------------------------------------
189
Glenn Kasten03490092014-05-27 12:30:54 -0700190static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
191
192static void sFastTrackMultiplierInit()
193{
194 char value[PROPERTY_VALUE_MAX];
195 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
196 char *endptr;
197 unsigned long ul = strtoul(value, &endptr, 0);
198 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
199 sFastTrackMultiplier = (int) ul;
200 }
201 }
202}
203
204// ----------------------------------------------------------------------------
205
Eric Laurent81784c32012-11-19 14:55:58 -0800206#ifdef ADD_BATTERY_DATA
207// To collect the amplifier usage
208static void addBatteryData(uint32_t params) {
209 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
210 if (service == NULL) {
211 // it already logged
212 return;
213 }
214
215 service->addBatteryData(params);
216}
217#endif
218
219
220// ----------------------------------------------------------------------------
221// CPU Stats
222// ----------------------------------------------------------------------------
223
224class CpuStats {
225public:
226 CpuStats();
227 void sample(const String8 &title);
228#ifdef DEBUG_CPU_USAGE
229private:
230 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
231 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
232
233 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
234
235 int mCpuNum; // thread's current CPU number
236 int mCpukHz; // frequency of thread's current CPU in kHz
237#endif
238};
239
240CpuStats::CpuStats()
241#ifdef DEBUG_CPU_USAGE
242 : mCpuNum(-1), mCpukHz(-1)
243#endif
244{
245}
246
Glenn Kasten0f11b512014-01-31 16:18:54 -0800247void CpuStats::sample(const String8 &title
248#ifndef DEBUG_CPU_USAGE
249 __unused
250#endif
251 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800252#ifdef DEBUG_CPU_USAGE
253 // get current thread's delta CPU time in wall clock ns
254 double wcNs;
255 bool valid = mCpuUsage.sampleAndEnable(wcNs);
256
257 // record sample for wall clock statistics
258 if (valid) {
259 mWcStats.sample(wcNs);
260 }
261
262 // get the current CPU number
263 int cpuNum = sched_getcpu();
264
265 // get the current CPU frequency in kHz
266 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
267
268 // check if either CPU number or frequency changed
269 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
270 mCpuNum = cpuNum;
271 mCpukHz = cpukHz;
272 // ignore sample for purposes of cycles
273 valid = false;
274 }
275
276 // if no change in CPU number or frequency, then record sample for cycle statistics
277 if (valid && mCpukHz > 0) {
278 double cycles = wcNs * cpukHz * 0.000001;
279 mHzStats.sample(cycles);
280 }
281
282 unsigned n = mWcStats.n();
283 // mCpuUsage.elapsed() is expensive, so don't call it every loop
284 if ((n & 127) == 1) {
285 long long elapsed = mCpuUsage.elapsed();
286 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
287 double perLoop = elapsed / (double) n;
288 double perLoop100 = perLoop * 0.01;
289 double perLoop1k = perLoop * 0.001;
290 double mean = mWcStats.mean();
291 double stddev = mWcStats.stddev();
292 double minimum = mWcStats.minimum();
293 double maximum = mWcStats.maximum();
294 double meanCycles = mHzStats.mean();
295 double stddevCycles = mHzStats.stddev();
296 double minCycles = mHzStats.minimum();
297 double maxCycles = mHzStats.maximum();
298 mCpuUsage.resetElapsed();
299 mWcStats.reset();
300 mHzStats.reset();
301 ALOGD("CPU usage for %s over past %.1f secs\n"
302 " (%u mixer loops at %.1f mean ms per loop):\n"
303 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
304 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
305 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
306 title.string(),
307 elapsed * .000000001, n, perLoop * .000001,
308 mean * .001,
309 stddev * .001,
310 minimum * .001,
311 maximum * .001,
312 mean / perLoop100,
313 stddev / perLoop100,
314 minimum / perLoop100,
315 maximum / perLoop100,
316 meanCycles / perLoop1k,
317 stddevCycles / perLoop1k,
318 minCycles / perLoop1k,
319 maxCycles / perLoop1k);
320
321 }
322 }
323#endif
324};
325
326// ----------------------------------------------------------------------------
327// ThreadBase
328// ----------------------------------------------------------------------------
329
Glenn Kasten97b7b752014-09-28 13:04:24 -0700330// static
331const char *AudioFlinger::ThreadBase::threadTypeToString(AudioFlinger::ThreadBase::type_t type)
332{
333 switch (type) {
334 case MIXER:
335 return "MIXER";
336 case DIRECT:
337 return "DIRECT";
338 case DUPLICATING:
339 return "DUPLICATING";
340 case RECORD:
341 return "RECORD";
342 case OFFLOAD:
343 return "OFFLOAD";
344 default:
345 return "unknown";
346 }
347}
348
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800349String8 devicesToString(audio_devices_t devices)
350{
351 static const struct mapping {
352 audio_devices_t mDevices;
353 const char * mString;
354 } mappingsOut[] = {
355 AUDIO_DEVICE_OUT_EARPIECE, "EARPIECE",
356 AUDIO_DEVICE_OUT_SPEAKER, "SPEAKER",
357 AUDIO_DEVICE_OUT_WIRED_HEADSET, "WIRED_HEADSET",
358 AUDIO_DEVICE_OUT_WIRED_HEADPHONE, "WIRED_HEADPHONE",
Glenn Kasten84d61ca2015-05-06 18:32:13 -0700359 AUDIO_DEVICE_OUT_BLUETOOTH_SCO, "BLUETOOTH_SCO",
360 AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET, "BLUETOOTH_SCO_HEADSET",
361 AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT, "BLUETOOTH_SCO_CARKIT",
362 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, "BLUETOOTH_A2DP",
363 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES, "BLUETOOTH_A2DP_HEADPHONES",
364 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER, "BLUETOOTH_A2DP_SPEAKER",
365 AUDIO_DEVICE_OUT_AUX_DIGITAL, "AUX_DIGITAL",
366 AUDIO_DEVICE_OUT_HDMI, "HDMI",
367 AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET, "ANLG_DOCK_HEADSET",
368 AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET, "DGTL_DOCK_HEADSET",
369 AUDIO_DEVICE_OUT_USB_ACCESSORY, "USB_ACCESSORY",
370 AUDIO_DEVICE_OUT_USB_DEVICE, "USB_DEVICE",
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800371 AUDIO_DEVICE_OUT_TELEPHONY_TX, "TELEPHONY_TX",
Glenn Kasten84d61ca2015-05-06 18:32:13 -0700372 AUDIO_DEVICE_OUT_LINE, "LINE",
373 AUDIO_DEVICE_OUT_HDMI_ARC, "HDMI_ARC",
374 AUDIO_DEVICE_OUT_SPDIF, "SPDIF",
375 AUDIO_DEVICE_OUT_FM, "FM",
376 AUDIO_DEVICE_OUT_AUX_LINE, "AUX_LINE",
377 AUDIO_DEVICE_OUT_SPEAKER_SAFE, "SPEAKER_SAFE",
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800378 AUDIO_DEVICE_NONE, "NONE", // must be last
379 }, mappingsIn[] = {
Glenn Kasten84d61ca2015-05-06 18:32:13 -0700380 AUDIO_DEVICE_IN_COMMUNICATION, "COMMUNICATION",
381 AUDIO_DEVICE_IN_AMBIENT, "AMBIENT",
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800382 AUDIO_DEVICE_IN_BUILTIN_MIC, "BUILTIN_MIC",
Glenn Kasten84d61ca2015-05-06 18:32:13 -0700383 AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET, "BLUETOOTH_SCO_HEADSET",
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800384 AUDIO_DEVICE_IN_WIRED_HEADSET, "WIRED_HEADSET",
Glenn Kasten84d61ca2015-05-06 18:32:13 -0700385 AUDIO_DEVICE_IN_AUX_DIGITAL, "AUX_DIGITAL",
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800386 AUDIO_DEVICE_IN_VOICE_CALL, "VOICE_CALL",
Glenn Kasten84d61ca2015-05-06 18:32:13 -0700387 AUDIO_DEVICE_IN_TELEPHONY_RX, "TELEPHONY_RX",
388 AUDIO_DEVICE_IN_BACK_MIC, "BACK_MIC",
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800389 AUDIO_DEVICE_IN_REMOTE_SUBMIX, "REMOTE_SUBMIX",
Glenn Kasten84d61ca2015-05-06 18:32:13 -0700390 AUDIO_DEVICE_IN_ANLG_DOCK_HEADSET, "ANLG_DOCK_HEADSET",
391 AUDIO_DEVICE_IN_DGTL_DOCK_HEADSET, "DGTL_DOCK_HEADSET",
392 AUDIO_DEVICE_IN_USB_ACCESSORY, "USB_ACCESSORY",
393 AUDIO_DEVICE_IN_USB_DEVICE, "USB_DEVICE",
394 AUDIO_DEVICE_IN_FM_TUNER, "FM_TUNER",
395 AUDIO_DEVICE_IN_TV_TUNER, "TV_TUNER",
396 AUDIO_DEVICE_IN_LINE, "LINE",
397 AUDIO_DEVICE_IN_SPDIF, "SPDIF",
398 AUDIO_DEVICE_IN_BLUETOOTH_A2DP, "BLUETOOTH_A2DP",
399 AUDIO_DEVICE_IN_LOOPBACK, "LOOPBACK",
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800400 AUDIO_DEVICE_NONE, "NONE", // must be last
401 };
402 String8 result;
403 audio_devices_t allDevices = AUDIO_DEVICE_NONE;
404 const mapping *entry;
405 if (devices & AUDIO_DEVICE_BIT_IN) {
406 devices &= ~AUDIO_DEVICE_BIT_IN;
407 entry = mappingsIn;
408 } else {
409 entry = mappingsOut;
410 }
411 for ( ; entry->mDevices != AUDIO_DEVICE_NONE; entry++) {
412 allDevices = (audio_devices_t) (allDevices | entry->mDevices);
413 if (devices & entry->mDevices) {
414 if (!result.isEmpty()) {
415 result.append("|");
416 }
417 result.append(entry->mString);
418 }
419 }
420 if (devices & ~allDevices) {
421 if (!result.isEmpty()) {
422 result.append("|");
423 }
424 result.appendFormat("0x%X", devices & ~allDevices);
425 }
426 if (result.isEmpty()) {
427 result.append(entry->mString);
428 }
429 return result;
430}
431
432String8 inputFlagsToString(audio_input_flags_t flags)
433{
434 static const struct mapping {
435 audio_input_flags_t mFlag;
436 const char * mString;
437 } mappings[] = {
438 AUDIO_INPUT_FLAG_FAST, "FAST",
439 AUDIO_INPUT_FLAG_HW_HOTWORD, "HW_HOTWORD",
440 AUDIO_INPUT_FLAG_NONE, "NONE", // must be last
441 };
442 String8 result;
443 audio_input_flags_t allFlags = AUDIO_INPUT_FLAG_NONE;
444 const mapping *entry;
445 for (entry = mappings; entry->mFlag != AUDIO_INPUT_FLAG_NONE; entry++) {
446 allFlags = (audio_input_flags_t) (allFlags | entry->mFlag);
447 if (flags & entry->mFlag) {
448 if (!result.isEmpty()) {
449 result.append("|");
450 }
451 result.append(entry->mString);
452 }
453 }
454 if (flags & ~allFlags) {
455 if (!result.isEmpty()) {
456 result.append("|");
457 }
458 result.appendFormat("0x%X", flags & ~allFlags);
459 }
460 if (result.isEmpty()) {
461 result.append(entry->mString);
462 }
463 return result;
464}
465
466String8 outputFlagsToString(audio_output_flags_t flags)
Glenn Kasten97b7b752014-09-28 13:04:24 -0700467{
468 static const struct mapping {
469 audio_output_flags_t mFlag;
470 const char * mString;
471 } mappings[] = {
472 AUDIO_OUTPUT_FLAG_DIRECT, "DIRECT",
473 AUDIO_OUTPUT_FLAG_PRIMARY, "PRIMARY",
474 AUDIO_OUTPUT_FLAG_FAST, "FAST",
475 AUDIO_OUTPUT_FLAG_DEEP_BUFFER, "DEEP_BUFFER",
Glenn Kastendfb0e112015-02-18 14:33:39 -0800476 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD, "COMPRESS_OFFLOAD",
Glenn Kasten97b7b752014-09-28 13:04:24 -0700477 AUDIO_OUTPUT_FLAG_NON_BLOCKING, "NON_BLOCKING",
478 AUDIO_OUTPUT_FLAG_HW_AV_SYNC, "HW_AV_SYNC",
479 AUDIO_OUTPUT_FLAG_NONE, "NONE", // must be last
480 };
481 String8 result;
482 audio_output_flags_t allFlags = AUDIO_OUTPUT_FLAG_NONE;
483 const mapping *entry;
484 for (entry = mappings; entry->mFlag != AUDIO_OUTPUT_FLAG_NONE; entry++) {
485 allFlags = (audio_output_flags_t) (allFlags | entry->mFlag);
486 if (flags & entry->mFlag) {
487 if (!result.isEmpty()) {
488 result.append("|");
489 }
490 result.append(entry->mString);
491 }
492 }
493 if (flags & ~allFlags) {
494 if (!result.isEmpty()) {
495 result.append("|");
496 }
497 result.appendFormat("0x%X", flags & ~allFlags);
498 }
499 if (result.isEmpty()) {
500 result.append(entry->mString);
501 }
502 return result;
503}
504
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800505const char *sourceToString(audio_source_t source)
506{
507 switch (source) {
508 case AUDIO_SOURCE_DEFAULT: return "default";
509 case AUDIO_SOURCE_MIC: return "mic";
510 case AUDIO_SOURCE_VOICE_UPLINK: return "voice uplink";
511 case AUDIO_SOURCE_VOICE_DOWNLINK: return "voice downlink";
512 case AUDIO_SOURCE_VOICE_CALL: return "voice call";
513 case AUDIO_SOURCE_CAMCORDER: return "camcorder";
514 case AUDIO_SOURCE_VOICE_RECOGNITION: return "voice recognition";
515 case AUDIO_SOURCE_VOICE_COMMUNICATION: return "voice communication";
516 case AUDIO_SOURCE_REMOTE_SUBMIX: return "remote submix";
517 case AUDIO_SOURCE_FM_TUNER: return "FM tuner";
518 case AUDIO_SOURCE_HOTWORD: return "hotword";
519 default: return "unknown";
520 }
521}
522
Eric Laurent81784c32012-11-19 14:55:58 -0800523AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -0700524 audio_devices_t outDevice, audio_devices_t inDevice, type_t type, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -0800525 : Thread(false /*canCallJava*/),
526 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700527 mAudioFlinger(audioFlinger),
Glenn Kasten70949c42013-08-06 07:40:12 -0700528 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800529 // are set by PlaybackThread::readOutputParameters_l() or
530 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700531 //FIXME: mStandby should be true here. Is this some kind of hack?
Eric Laurent81784c32012-11-19 14:55:58 -0800532 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
533 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
534 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700535 mDeathRecipient(new PMDeathRecipient(this)),
536 mSystemReady(systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -0800537{
Eric Laurent296fb132015-05-01 11:38:42 -0700538 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800539}
540
541AudioFlinger::ThreadBase::~ThreadBase()
542{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700543 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700544 mConfigEvents.clear();
545
Eric Laurent81784c32012-11-19 14:55:58 -0800546 // do not lock the mutex in destructor
547 releaseWakeLock_l();
548 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800549 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800550 binder->unlinkToDeath(mDeathRecipient);
551 }
552}
553
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700554status_t AudioFlinger::ThreadBase::readyToRun()
555{
556 status_t status = initCheck();
557 if (status == NO_ERROR) {
558 ALOGI("AudioFlinger's thread %p ready to run", this);
559 } else {
560 ALOGE("No working audio driver found.");
561 }
562 return status;
563}
564
Eric Laurent81784c32012-11-19 14:55:58 -0800565void AudioFlinger::ThreadBase::exit()
566{
567 ALOGV("ThreadBase::exit");
568 // do any cleanup required for exit to succeed
569 preExit();
570 {
571 // This lock prevents the following race in thread (uniprocessor for illustration):
572 // if (!exitPending()) {
573 // // context switch from here to exit()
574 // // exit() calls requestExit(), what exitPending() observes
575 // // exit() calls signal(), which is dropped since no waiters
576 // // context switch back from exit() to here
577 // mWaitWorkCV.wait(...);
578 // // now thread is hung
579 // }
580 AutoMutex lock(mLock);
581 requestExit();
582 mWaitWorkCV.broadcast();
583 }
584 // When Thread::requestExitAndWait is made virtual and this method is renamed to
585 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
586 requestExitAndWait();
587}
588
589status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
590{
591 status_t status;
592
593 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
594 Mutex::Autolock _l(mLock);
595
Eric Laurent10351942014-05-08 18:49:52 -0700596 return sendSetParameterConfigEvent_l(keyValuePairs);
597}
598
599// sendConfigEvent_l() must be called with ThreadBase::mLock held
600// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
601status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
602{
603 status_t status = NO_ERROR;
604
Eric Laurent72e3f392015-05-20 14:43:50 -0700605 if (event->mRequiresSystemReady && !mSystemReady) {
606 event->mWaitStatus = false;
607 mPendingConfigEvents.add(event);
608 return status;
609 }
Eric Laurent10351942014-05-08 18:49:52 -0700610 mConfigEvents.add(event);
611 ALOGV("sendConfigEvent_l() num events %d event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800612 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700613 mLock.unlock();
614 {
615 Mutex::Autolock _l(event->mLock);
616 while (event->mWaitStatus) {
617 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
618 event->mStatus = TIMED_OUT;
619 event->mWaitStatus = false;
620 }
621 }
622 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800623 }
Eric Laurent10351942014-05-08 18:49:52 -0700624 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800625 return status;
626}
627
Eric Laurent73e26b62015-04-27 16:55:58 -0700628void AudioFlinger::ThreadBase::sendIoConfigEvent(audio_io_config_event event)
Eric Laurent81784c32012-11-19 14:55:58 -0800629{
630 Mutex::Autolock _l(mLock);
Eric Laurent73e26b62015-04-27 16:55:58 -0700631 sendIoConfigEvent_l(event);
Eric Laurent81784c32012-11-19 14:55:58 -0800632}
633
634// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
Eric Laurent73e26b62015-04-27 16:55:58 -0700635void AudioFlinger::ThreadBase::sendIoConfigEvent_l(audio_io_config_event event)
Eric Laurent81784c32012-11-19 14:55:58 -0800636{
Eric Laurent73e26b62015-04-27 16:55:58 -0700637 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event);
Eric Laurent10351942014-05-08 18:49:52 -0700638 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800639}
640
Eric Laurent72e3f392015-05-20 14:43:50 -0700641void AudioFlinger::ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio)
642{
643 Mutex::Autolock _l(mLock);
644 sendPrioConfigEvent_l(pid, tid, prio);
645}
646
Eric Laurent81784c32012-11-19 14:55:58 -0800647// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
648void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
649{
Eric Laurent10351942014-05-08 18:49:52 -0700650 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio);
651 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800652}
653
Eric Laurent10351942014-05-08 18:49:52 -0700654// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
655status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800656{
Eric Laurent10351942014-05-08 18:49:52 -0700657 sp<ConfigEvent> configEvent = (ConfigEvent *)new SetParameterConfigEvent(keyValuePair);
658 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700659}
660
Eric Laurent1c333e22014-05-20 10:48:17 -0700661status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
662 const struct audio_patch *patch,
663 audio_patch_handle_t *handle)
664{
665 Mutex::Autolock _l(mLock);
666 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
667 status_t status = sendConfigEvent_l(configEvent);
668 if (status == NO_ERROR) {
669 CreateAudioPatchConfigEventData *data =
670 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
671 *handle = data->mHandle;
672 }
673 return status;
674}
675
676status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
677 const audio_patch_handle_t handle)
678{
679 Mutex::Autolock _l(mLock);
680 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
681 return sendConfigEvent_l(configEvent);
682}
683
684
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700685// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700686void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700687{
Eric Laurent10351942014-05-08 18:49:52 -0700688 bool configChanged = false;
689
Eric Laurent81784c32012-11-19 14:55:58 -0800690 while (!mConfigEvents.isEmpty()) {
Eric Laurent10351942014-05-08 18:49:52 -0700691 ALOGV("processConfigEvents_l() remaining events %d", mConfigEvents.size());
692 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800693 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700694 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700695 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700696 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
697 // FIXME Need to understand why this has to be done asynchronously
698 int err = requestPriority(data->mPid, data->mTid, data->mPrio,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700699 true /*asynchronous*/);
700 if (err != 0) {
701 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700702 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700703 }
704 } break;
705 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700706 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent73e26b62015-04-27 16:55:58 -0700707 ioConfigChanged(data->mEvent);
Eric Laurent10351942014-05-08 18:49:52 -0700708 } break;
709 case CFG_EVENT_SET_PARAMETER: {
710 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
711 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
712 configChanged = true;
Glenn Kastend5418eb2013-08-14 13:11:06 -0700713 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700714 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700715 case CFG_EVENT_CREATE_AUDIO_PATCH: {
716 CreateAudioPatchConfigEventData *data =
717 (CreateAudioPatchConfigEventData *)event->mData.get();
718 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
719 } break;
720 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
721 ReleaseAudioPatchConfigEventData *data =
722 (ReleaseAudioPatchConfigEventData *)event->mData.get();
723 event->mStatus = releaseAudioPatch_l(data->mHandle);
724 } break;
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700725 default:
Eric Laurent10351942014-05-08 18:49:52 -0700726 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700727 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800728 }
Eric Laurent10351942014-05-08 18:49:52 -0700729 {
730 Mutex::Autolock _l(event->mLock);
731 if (event->mWaitStatus) {
732 event->mWaitStatus = false;
733 event->mCond.signal();
734 }
735 }
736 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
737 }
738
739 if (configChanged) {
740 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800741 }
Eric Laurent81784c32012-11-19 14:55:58 -0800742}
743
Marco Nelissenb2208842014-02-07 14:00:50 -0800744String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
745 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700746 const audio_channel_representation_t representation =
747 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700748
749 switch (representation) {
750 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
751 if (output) {
752 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
753 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
754 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
755 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
756 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
757 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
758 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
759 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
760 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
761 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
762 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
763 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
764 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
765 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
766 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
767 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
768 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
769 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
770 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
771 } else {
772 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
773 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
774 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
775 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
776 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
777 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
778 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
779 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
780 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
781 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
782 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
783 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
784 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
785 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
786 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
787 }
788 const int len = s.length();
789 if (len > 2) {
790 char *str = s.lockBuffer(len); // needed?
791 s.unlockBuffer(len - 2); // remove trailing ", "
792 }
793 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800794 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700795 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
796 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
797 return s;
798 default:
799 s.appendFormat("unknown mask, representation:%d bits:%#x",
800 representation, audio_channel_mask_get_bits(mask));
801 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800802 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800803}
804
Glenn Kasten0f11b512014-01-31 16:18:54 -0800805void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800806{
807 const size_t SIZE = 256;
808 char buffer[SIZE];
809 String8 result;
810
811 bool locked = AudioFlinger::dumpTryLock(mLock);
812 if (!locked) {
Glenn Kasten97b7b752014-09-28 13:04:24 -0700813 dprintf(fd, "thread %p may be deadlocked\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -0800814 }
815
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800816 dprintf(fd, " Thread name: %s\n", mThreadName);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700817 dprintf(fd, " I/O handle: %d\n", mId);
818 dprintf(fd, " TID: %d\n", getTid());
819 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700820 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700821 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700822 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat));
Elliott Hughes87cebad2014-05-22 10:14:43 -0700823 dprintf(fd, " HAL buffer size: %u bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700824 dprintf(fd, " Channel count: %u\n", mChannelCount);
825 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800826 channelMaskToString(mChannelMask, mType != RECORD).string());
Glenn Kasten97b7b752014-09-28 13:04:24 -0700827 dprintf(fd, " Format: 0x%x (%s)\n", mFormat, formatToString(mFormat));
828 dprintf(fd, " Frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700829 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800830 size_t numConfig = mConfigEvents.size();
831 if (numConfig) {
832 for (size_t i = 0; i < numConfig; i++) {
833 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700834 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800835 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700836 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800837 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700838 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800839 }
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800840 dprintf(fd, " Output device: %#x (%s)\n", mOutDevice, devicesToString(mOutDevice).string());
841 dprintf(fd, " Input device: %#x (%s)\n", mInDevice, devicesToString(mInDevice).string());
842 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, sourceToString(mAudioSource));
Eric Laurent81784c32012-11-19 14:55:58 -0800843
844 if (locked) {
845 mLock.unlock();
846 }
847}
848
849void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
850{
851 const size_t SIZE = 256;
852 char buffer[SIZE];
853 String8 result;
854
Marco Nelissenb2208842014-02-07 14:00:50 -0800855 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000856 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800857 write(fd, buffer, strlen(buffer));
858
Marco Nelissenb2208842014-02-07 14:00:50 -0800859 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800860 sp<EffectChain> chain = mEffectChains[i];
861 if (chain != 0) {
862 chain->dump(fd, args);
863 }
864 }
865}
866
Marco Nelissene14a5d62013-10-03 08:51:24 -0700867void AudioFlinger::ThreadBase::acquireWakeLock(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800868{
869 Mutex::Autolock _l(mLock);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700870 acquireWakeLock_l(uid);
Eric Laurent81784c32012-11-19 14:55:58 -0800871}
872
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100873String16 AudioFlinger::ThreadBase::getWakeLockTag()
874{
875 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -0800876 case MIXER:
877 return String16("AudioMix");
878 case DIRECT:
879 return String16("AudioDirectOut");
880 case DUPLICATING:
881 return String16("AudioDup");
882 case RECORD:
883 return String16("AudioIn");
884 case OFFLOAD:
885 return String16("AudioOffload");
886 default:
887 ALOG_ASSERT(false);
888 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100889 }
890}
891
Marco Nelissene14a5d62013-10-03 08:51:24 -0700892void AudioFlinger::ThreadBase::acquireWakeLock_l(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800893{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800894 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800895 if (mPowerManager != 0) {
896 sp<IBinder> binder = new BBinder();
Marco Nelissene14a5d62013-10-03 08:51:24 -0700897 status_t status;
898 if (uid >= 0) {
Eric Laurent547789d2013-10-04 11:46:55 -0700899 status = mPowerManager->acquireWakeLockWithUid(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700900 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100901 getWakeLockTag(),
Marco Nelissene14a5d62013-10-03 08:51:24 -0700902 String16("media"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700903 uid,
904 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700905 } else {
Eric Laurent547789d2013-10-04 11:46:55 -0700906 status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700907 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100908 getWakeLockTag(),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700909 String16("media"),
910 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700911 }
Eric Laurent81784c32012-11-19 14:55:58 -0800912 if (status == NO_ERROR) {
913 mWakeLockToken = binder;
914 }
Glenn Kastend7dca052015-03-05 16:05:54 -0800915 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Eric Laurent81784c32012-11-19 14:55:58 -0800916 }
917}
918
919void AudioFlinger::ThreadBase::releaseWakeLock()
920{
921 Mutex::Autolock _l(mLock);
922 releaseWakeLock_l();
923}
924
925void AudioFlinger::ThreadBase::releaseWakeLock_l()
926{
927 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800928 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -0800929 if (mPowerManager != 0) {
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700930 mPowerManager->releaseWakeLock(mWakeLockToken, 0,
931 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800932 }
933 mWakeLockToken.clear();
934 }
935}
936
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800937void AudioFlinger::ThreadBase::updateWakeLockUids(const SortedVector<int> &uids) {
938 Mutex::Autolock _l(mLock);
939 updateWakeLockUids_l(uids);
940}
941
942void AudioFlinger::ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -0700943 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800944 // use checkService() to avoid blocking if power service is not up yet
945 sp<IBinder> binder =
946 defaultServiceManager()->checkService(String16("power"));
947 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800948 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800949 } else {
950 mPowerManager = interface_cast<IPowerManager>(binder);
951 binder->linkToDeath(mDeathRecipient);
952 }
953 }
954}
955
956void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<int> &uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800957 getPowerManager_l();
958 if (mWakeLockToken == NULL) {
959 ALOGE("no wake lock to update!");
960 return;
961 }
962 if (mPowerManager != 0) {
963 sp<IBinder> binder = new BBinder();
964 status_t status;
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700965 status = mPowerManager->updateWakeLockUids(mWakeLockToken, uids.size(), uids.array(),
966 true /* FIXME force oneway contrary to .aidl */);
Glenn Kastend7dca052015-03-05 16:05:54 -0800967 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800968 }
969}
970
Eric Laurent81784c32012-11-19 14:55:58 -0800971void AudioFlinger::ThreadBase::clearPowerManager()
972{
973 Mutex::Autolock _l(mLock);
974 releaseWakeLock_l();
975 mPowerManager.clear();
976}
977
Glenn Kasten0f11b512014-01-31 16:18:54 -0800978void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800979{
980 sp<ThreadBase> thread = mThread.promote();
981 if (thread != 0) {
982 thread->clearPowerManager();
983 }
984 ALOGW("power manager service died !!!");
985}
986
987void AudioFlinger::ThreadBase::setEffectSuspended(
988 const effect_uuid_t *type, bool suspend, int sessionId)
989{
990 Mutex::Autolock _l(mLock);
991 setEffectSuspended_l(type, suspend, sessionId);
992}
993
994void AudioFlinger::ThreadBase::setEffectSuspended_l(
995 const effect_uuid_t *type, bool suspend, int sessionId)
996{
997 sp<EffectChain> chain = getEffectChain_l(sessionId);
998 if (chain != 0) {
999 if (type != NULL) {
1000 chain->setEffectSuspended_l(type, suspend);
1001 } else {
1002 chain->setEffectSuspendedAll_l(suspend);
1003 }
1004 }
1005
1006 updateSuspendedSessions_l(type, suspend, sessionId);
1007}
1008
1009void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1010{
1011 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1012 if (index < 0) {
1013 return;
1014 }
1015
1016 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1017 mSuspendedSessions.valueAt(index);
1018
1019 for (size_t i = 0; i < sessionEffects.size(); i++) {
1020 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
1021 for (int j = 0; j < desc->mRefCount; j++) {
1022 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1023 chain->setEffectSuspendedAll_l(true);
1024 } else {
1025 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1026 desc->mType.timeLow);
1027 chain->setEffectSuspended_l(&desc->mType, true);
1028 }
1029 }
1030 }
1031}
1032
1033void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1034 bool suspend,
1035 int sessionId)
1036{
1037 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1038
1039 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1040
1041 if (suspend) {
1042 if (index >= 0) {
1043 sessionEffects = mSuspendedSessions.valueAt(index);
1044 } else {
1045 mSuspendedSessions.add(sessionId, sessionEffects);
1046 }
1047 } else {
1048 if (index < 0) {
1049 return;
1050 }
1051 sessionEffects = mSuspendedSessions.valueAt(index);
1052 }
1053
1054
1055 int key = EffectChain::kKeyForSuspendAll;
1056 if (type != NULL) {
1057 key = type->timeLow;
1058 }
1059 index = sessionEffects.indexOfKey(key);
1060
1061 sp<SuspendedSessionDesc> desc;
1062 if (suspend) {
1063 if (index >= 0) {
1064 desc = sessionEffects.valueAt(index);
1065 } else {
1066 desc = new SuspendedSessionDesc();
1067 if (type != NULL) {
1068 desc->mType = *type;
1069 }
1070 sessionEffects.add(key, desc);
1071 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1072 }
1073 desc->mRefCount++;
1074 } else {
1075 if (index < 0) {
1076 return;
1077 }
1078 desc = sessionEffects.valueAt(index);
1079 if (--desc->mRefCount == 0) {
1080 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1081 sessionEffects.removeItemsAt(index);
1082 if (sessionEffects.isEmpty()) {
1083 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1084 sessionId);
1085 mSuspendedSessions.removeItem(sessionId);
1086 }
1087 }
1088 }
1089 if (!sessionEffects.isEmpty()) {
1090 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1091 }
1092}
1093
1094void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1095 bool enabled,
1096 int sessionId)
1097{
1098 Mutex::Autolock _l(mLock);
1099 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1100}
1101
1102void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1103 bool enabled,
1104 int sessionId)
1105{
1106 if (mType != RECORD) {
1107 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1108 // another session. This gives the priority to well behaved effect control panels
1109 // and applications not using global effects.
1110 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1111 // global effects
1112 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
1113 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1114 }
1115 }
1116
1117 sp<EffectChain> chain = getEffectChain_l(sessionId);
1118 if (chain != 0) {
1119 chain->checkSuspendOnEffectEnabled(effect, enabled);
1120 }
1121}
1122
1123// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1124sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1125 const sp<AudioFlinger::Client>& client,
1126 const sp<IEffectClient>& effectClient,
1127 int32_t priority,
1128 int sessionId,
1129 effect_descriptor_t *desc,
1130 int *enabled,
Glenn Kasten9156ef32013-08-06 15:39:08 -07001131 status_t *status)
Eric Laurent81784c32012-11-19 14:55:58 -08001132{
1133 sp<EffectModule> effect;
1134 sp<EffectHandle> handle;
1135 status_t lStatus;
1136 sp<EffectChain> chain;
1137 bool chainCreated = false;
1138 bool effectCreated = false;
1139 bool effectRegistered = false;
1140
1141 lStatus = initCheck();
1142 if (lStatus != NO_ERROR) {
1143 ALOGW("createEffect_l() Audio driver not initialized.");
1144 goto Exit;
1145 }
1146
Andy Hung98ef9782014-03-04 14:46:50 -08001147 // Reject any effect on Direct output threads for now, since the format of
1148 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1149 if (mType == DIRECT) {
1150 ALOGW("createEffect_l() Cannot add effect %s on Direct output type thread %s",
Glenn Kastend7dca052015-03-05 16:05:54 -08001151 desc->name, mThreadName);
Andy Hung98ef9782014-03-04 14:46:50 -08001152 lStatus = BAD_VALUE;
1153 goto Exit;
1154 }
1155
Andy Hung389cfdb2014-08-07 17:49:53 -07001156 // Reject any effect on mixer or duplicating multichannel sinks.
Andy Hung9a592762014-07-21 21:56:01 -07001157 // TODO: fix both format and multichannel issues with effects.
Andy Hung389cfdb2014-08-07 17:49:53 -07001158 if ((mType == MIXER || mType == DUPLICATING) && mChannelCount != FCC_2) {
1159 ALOGW("createEffect_l() Cannot add effect %s for multichannel(%d) %s threads",
1160 desc->name, mChannelCount, mType == MIXER ? "MIXER" : "DUPLICATING");
Andy Hung9a592762014-07-21 21:56:01 -07001161 lStatus = BAD_VALUE;
1162 goto Exit;
1163 }
1164
Eric Laurent5baf2af2013-09-12 17:37:00 -07001165 // Allow global effects only on offloaded and mixer threads
1166 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1167 switch (mType) {
1168 case MIXER:
1169 case OFFLOAD:
1170 break;
1171 case DIRECT:
1172 case DUPLICATING:
1173 case RECORD:
1174 default:
Glenn Kastend7dca052015-03-05 16:05:54 -08001175 ALOGW("createEffect_l() Cannot add global effect %s on thread %s",
1176 desc->name, mThreadName);
Eric Laurent5baf2af2013-09-12 17:37:00 -07001177 lStatus = BAD_VALUE;
1178 goto Exit;
1179 }
Eric Laurent81784c32012-11-19 14:55:58 -08001180 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07001181
Eric Laurent81784c32012-11-19 14:55:58 -08001182 // Only Pre processor effects are allowed on input threads and only on input threads
1183 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
1184 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
1185 desc->name, desc->flags, mType);
1186 lStatus = BAD_VALUE;
1187 goto Exit;
1188 }
1189
1190 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1191
1192 { // scope for mLock
1193 Mutex::Autolock _l(mLock);
1194
1195 // check for existing effect chain with the requested audio session
1196 chain = getEffectChain_l(sessionId);
1197 if (chain == 0) {
1198 // create a new chain for this session
1199 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1200 chain = new EffectChain(this, sessionId);
1201 addEffectChain_l(chain);
1202 chain->setStrategy(getStrategyForSession_l(sessionId));
1203 chainCreated = true;
1204 } else {
1205 effect = chain->getEffectFromDesc_l(desc);
1206 }
1207
1208 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1209
1210 if (effect == 0) {
1211 int id = mAudioFlinger->nextUniqueId();
1212 // Check CPU and memory usage
1213 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
1214 if (lStatus != NO_ERROR) {
1215 goto Exit;
1216 }
1217 effectRegistered = true;
1218 // create a new effect module if none present in the chain
1219 effect = new EffectModule(this, chain, desc, id, sessionId);
1220 lStatus = effect->status();
1221 if (lStatus != NO_ERROR) {
1222 goto Exit;
1223 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07001224 effect->setOffloaded(mType == OFFLOAD, mId);
1225
Eric Laurent81784c32012-11-19 14:55:58 -08001226 lStatus = chain->addEffect_l(effect);
1227 if (lStatus != NO_ERROR) {
1228 goto Exit;
1229 }
1230 effectCreated = true;
1231
1232 effect->setDevice(mOutDevice);
1233 effect->setDevice(mInDevice);
1234 effect->setMode(mAudioFlinger->getMode());
1235 effect->setAudioSource(mAudioSource);
1236 }
1237 // create effect handle and connect it to effect module
1238 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001239 lStatus = handle->initCheck();
1240 if (lStatus == OK) {
1241 lStatus = effect->addHandle(handle.get());
1242 }
Eric Laurent81784c32012-11-19 14:55:58 -08001243 if (enabled != NULL) {
1244 *enabled = (int)effect->isEnabled();
1245 }
1246 }
1247
1248Exit:
1249 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1250 Mutex::Autolock _l(mLock);
1251 if (effectCreated) {
1252 chain->removeEffect_l(effect);
1253 }
1254 if (effectRegistered) {
1255 AudioSystem::unregisterEffect(effect->id());
1256 }
1257 if (chainCreated) {
1258 removeEffectChain_l(chain);
1259 }
1260 handle.clear();
1261 }
1262
Glenn Kasten9156ef32013-08-06 15:39:08 -07001263 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001264 return handle;
1265}
1266
1267sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
1268{
1269 Mutex::Autolock _l(mLock);
1270 return getEffect_l(sessionId, effectId);
1271}
1272
1273sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
1274{
1275 sp<EffectChain> chain = getEffectChain_l(sessionId);
1276 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1277}
1278
1279// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1280// PlaybackThread::mLock held
1281status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1282{
1283 // check for existing effect chain with the requested audio session
1284 int sessionId = effect->sessionId();
1285 sp<EffectChain> chain = getEffectChain_l(sessionId);
1286 bool chainCreated = false;
1287
Eric Laurent5baf2af2013-09-12 17:37:00 -07001288 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
1289 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
1290 this, effect->desc().name, effect->desc().flags);
1291
Eric Laurent81784c32012-11-19 14:55:58 -08001292 if (chain == 0) {
1293 // create a new chain for this session
1294 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1295 chain = new EffectChain(this, sessionId);
1296 addEffectChain_l(chain);
1297 chain->setStrategy(getStrategyForSession_l(sessionId));
1298 chainCreated = true;
1299 }
1300 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1301
1302 if (chain->getEffectFromId_l(effect->id()) != 0) {
1303 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1304 this, effect->desc().name, chain.get());
1305 return BAD_VALUE;
1306 }
1307
Eric Laurent5baf2af2013-09-12 17:37:00 -07001308 effect->setOffloaded(mType == OFFLOAD, mId);
1309
Eric Laurent81784c32012-11-19 14:55:58 -08001310 status_t status = chain->addEffect_l(effect);
1311 if (status != NO_ERROR) {
1312 if (chainCreated) {
1313 removeEffectChain_l(chain);
1314 }
1315 return status;
1316 }
1317
1318 effect->setDevice(mOutDevice);
1319 effect->setDevice(mInDevice);
1320 effect->setMode(mAudioFlinger->getMode());
1321 effect->setAudioSource(mAudioSource);
1322 return NO_ERROR;
1323}
1324
1325void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
1326
1327 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
1328 effect_descriptor_t desc = effect->desc();
1329 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1330 detachAuxEffect_l(effect->id());
1331 }
1332
1333 sp<EffectChain> chain = effect->chain().promote();
1334 if (chain != 0) {
1335 // remove effect chain if removing last effect
1336 if (chain->removeEffect_l(effect) == 0) {
1337 removeEffectChain_l(chain);
1338 }
1339 } else {
1340 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1341 }
1342}
1343
1344void AudioFlinger::ThreadBase::lockEffectChains_l(
1345 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1346{
1347 effectChains = mEffectChains;
1348 for (size_t i = 0; i < mEffectChains.size(); i++) {
1349 mEffectChains[i]->lock();
1350 }
1351}
1352
1353void AudioFlinger::ThreadBase::unlockEffectChains(
1354 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1355{
1356 for (size_t i = 0; i < effectChains.size(); i++) {
1357 effectChains[i]->unlock();
1358 }
1359}
1360
1361sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
1362{
1363 Mutex::Autolock _l(mLock);
1364 return getEffectChain_l(sessionId);
1365}
1366
1367sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const
1368{
1369 size_t size = mEffectChains.size();
1370 for (size_t i = 0; i < size; i++) {
1371 if (mEffectChains[i]->sessionId() == sessionId) {
1372 return mEffectChains[i];
1373 }
1374 }
1375 return 0;
1376}
1377
1378void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1379{
1380 Mutex::Autolock _l(mLock);
1381 size_t size = mEffectChains.size();
1382 for (size_t i = 0; i < size; i++) {
1383 mEffectChains[i]->setMode_l(mode);
1384 }
1385}
1386
Eric Laurent83b88082014-06-20 18:31:16 -07001387void AudioFlinger::ThreadBase::getAudioPortConfig(struct audio_port_config *config)
1388{
1389 config->type = AUDIO_PORT_TYPE_MIX;
1390 config->ext.mix.handle = mId;
1391 config->sample_rate = mSampleRate;
1392 config->format = mFormat;
1393 config->channel_mask = mChannelMask;
1394 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1395 AUDIO_PORT_CONFIG_FORMAT;
1396}
1397
Eric Laurent72e3f392015-05-20 14:43:50 -07001398void AudioFlinger::ThreadBase::systemReady()
1399{
1400 Mutex::Autolock _l(mLock);
1401 if (mSystemReady) {
1402 return;
1403 }
1404 mSystemReady = true;
1405
1406 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1407 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1408 }
1409 mPendingConfigEvents.clear();
1410}
1411
Eric Laurent83b88082014-06-20 18:31:16 -07001412
Eric Laurent81784c32012-11-19 14:55:58 -08001413// ----------------------------------------------------------------------------
1414// Playback
1415// ----------------------------------------------------------------------------
1416
1417AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1418 AudioStreamOut* output,
1419 audio_io_handle_t id,
1420 audio_devices_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07001421 type_t type,
1422 bool systemReady)
1423 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type, systemReady),
Andy Hung2098f272014-02-27 14:00:06 -08001424 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001425 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001426 mMixerBuffer(NULL),
1427 mMixerBufferSize(0),
1428 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1429 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001430 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001431 mEffectBuffer(NULL),
1432 mEffectBufferSize(0),
1433 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1434 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001435 mSuspended(0), mBytesWritten(0),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001436 mActiveTracksGeneration(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001437 // mStreamTypes[] initialized in constructor body
1438 mOutput(output),
1439 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
1440 mMixerStatus(MIXER_IDLE),
1441 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001442 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001443 mBytesRemaining(0),
1444 mCurrentWriteLength(0),
1445 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001446 mWriteAckSequence(0),
1447 mDrainSequence(0),
Eric Laurentede6c3b2013-09-19 14:37:46 -07001448 mSignalPending(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001449 mScreenState(AudioFlinger::mScreenState),
1450 // index 0 is reserved for normal mixer's submix
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001451 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1),
Eric Laurentd1f69b02014-12-15 14:33:13 -08001452 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001453 // mLatchD, mLatchQ,
1454 mLatchDValid(false), mLatchQValid(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001455{
Glenn Kastend7dca052015-03-05 16:05:54 -08001456 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1457 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001458
1459 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1460 // it would be safer to explicitly pass initial masterVolume/masterMute as
1461 // parameter.
1462 //
1463 // If the HAL we are using has support for master volume or master mute,
1464 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1465 // and the mute set to false).
1466 mMasterVolume = audioFlinger->masterVolume_l();
1467 mMasterMute = audioFlinger->masterMute_l();
1468 if (mOutput && mOutput->audioHwDev) {
1469 if (mOutput->audioHwDev->canSetMasterVolume()) {
1470 mMasterVolume = 1.0;
1471 }
1472
1473 if (mOutput->audioHwDev->canSetMasterMute()) {
1474 mMasterMute = false;
1475 }
1476 }
1477
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001478 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001479
Eric Laurent223fd5c2014-11-11 13:43:36 -08001480 // ++ operator does not compile
Glenn Kasten66e46352014-01-16 17:44:23 -08001481 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001482 stream = (audio_stream_type_t) (stream + 1)) {
1483 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1484 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1485 }
Eric Laurent81784c32012-11-19 14:55:58 -08001486}
1487
1488AudioFlinger::PlaybackThread::~PlaybackThread()
1489{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001490 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001491 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001492 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001493 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001494}
1495
1496void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1497{
1498 dumpInternals(fd, args);
1499 dumpTracks(fd, args);
1500 dumpEffectChains(fd, args);
1501}
1502
Glenn Kasten0f11b512014-01-31 16:18:54 -08001503void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001504{
1505 const size_t SIZE = 256;
1506 char buffer[SIZE];
1507 String8 result;
1508
Marco Nelissenb2208842014-02-07 14:00:50 -08001509 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001510 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1511 const stream_type_t *st = &mStreamTypes[i];
1512 if (i > 0) {
1513 result.appendFormat(", ");
1514 }
1515 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1516 if (st->mute) {
1517 result.append("M");
1518 }
1519 }
1520 result.append("\n");
1521 write(fd, result.string(), result.length());
1522 result.clear();
1523
Eric Laurent81784c32012-11-19 14:55:58 -08001524 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1525 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001526 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001527 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001528
1529 size_t numtracks = mTracks.size();
1530 size_t numactive = mActiveTracks.size();
Elliott Hughes87cebad2014-05-22 10:14:43 -07001531 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001532 size_t numactiveseen = 0;
1533 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07001534 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08001535 Track::appendDumpHeader(result);
1536 for (size_t i = 0; i < numtracks; ++i) {
1537 sp<Track> track = mTracks[i];
1538 if (track != 0) {
1539 bool active = mActiveTracks.indexOf(track) >= 0;
1540 if (active) {
1541 numactiveseen++;
1542 }
1543 track->dump(buffer, SIZE, active);
1544 result.append(buffer);
1545 }
1546 }
1547 } else {
1548 result.append("\n");
1549 }
1550 if (numactiveseen != numactive) {
1551 // some tracks in the active list were not in the tracks list
1552 snprintf(buffer, SIZE, " The following tracks are in the active list but"
1553 " not in the track list\n");
1554 result.append(buffer);
1555 Track::appendDumpHeader(result);
1556 for (size_t i = 0; i < numactive; ++i) {
1557 sp<Track> track = mActiveTracks[i].promote();
1558 if (track != 0 && mTracks.indexOf(track) < 0) {
1559 track->dump(buffer, SIZE, true);
1560 result.append(buffer);
1561 }
1562 }
1563 }
1564
1565 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001566}
1567
1568void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1569{
Glenn Kasten97b7b752014-09-28 13:04:24 -07001570 dprintf(fd, "\nOutput thread %p type %d (%s):\n", this, type(), threadTypeToString(type()));
Glenn Kasten44182c22015-03-05 17:12:23 -08001571
1572 dumpBase(fd, args);
1573
Elliott Hughes87cebad2014-05-22 10:14:43 -07001574 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
1575 dprintf(fd, " Last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1576 dprintf(fd, " Total writes: %d\n", mNumWrites);
1577 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1578 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1579 dprintf(fd, " Suspend count: %d\n", mSuspended);
1580 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1581 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1582 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1583 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001584 AudioStreamOut *output = mOutput;
1585 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
1586 String8 flagsAsString = outputFlagsToString(flags);
1587 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n", output, flags, flagsAsString.string());
Eric Laurent81784c32012-11-19 14:55:58 -08001588}
1589
1590// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001591
1592void AudioFlinger::PlaybackThread::onFirstRef()
1593{
Glenn Kastend7dca052015-03-05 16:05:54 -08001594 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001595}
1596
1597// ThreadBase virtuals
1598void AudioFlinger::PlaybackThread::preExit()
1599{
1600 ALOGV(" preExit()");
1601 // FIXME this is using hard-coded strings but in the future, this functionality will be
1602 // converted to use audio HAL extensions required to support tunneling
1603 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1604}
1605
1606// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1607sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1608 const sp<AudioFlinger::Client>& client,
1609 audio_stream_type_t streamType,
1610 uint32_t sampleRate,
1611 audio_format_t format,
1612 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001613 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001614 const sp<IMemory>& sharedBuffer,
1615 int sessionId,
1616 IAudioFlinger::track_flags_t *flags,
1617 pid_t tid,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001618 int uid,
Eric Laurent81784c32012-11-19 14:55:58 -08001619 status_t *status)
1620{
Glenn Kasten74935e42013-12-19 08:56:45 -08001621 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001622 sp<Track> track;
1623 status_t lStatus;
1624
1625 bool isTimed = (*flags & IAudioFlinger::TRACK_TIMED) != 0;
1626
1627 // client expresses a preference for FAST, but we get the final say
1628 if (*flags & IAudioFlinger::TRACK_FAST) {
1629 if (
1630 // not timed
1631 (!isTimed) &&
1632 // either of these use cases:
1633 (
1634 // use case 1: shared buffer with any frame count
1635 (
1636 (sharedBuffer != 0)
1637 ) ||
Glenn Kasten1dfe2f92015-03-09 12:03:14 -07001638 // use case 2: frame count is default or at least as large as HAL
Eric Laurent81784c32012-11-19 14:55:58 -08001639 (
Glenn Kasten1dfe2f92015-03-09 12:03:14 -07001640 // we formerly checked for a callback handler (non-0 tid),
1641 // but that is no longer required for TRANSFER_OBTAIN mode
Eric Laurent81784c32012-11-19 14:55:58 -08001642 ((frameCount == 0) ||
Glenn Kastenb5fed682013-12-03 09:06:43 -08001643 (frameCount >= mFrameCount))
Eric Laurent81784c32012-11-19 14:55:58 -08001644 )
1645 ) &&
1646 // PCM data
1647 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07001648 // TODO: extract as a data library function that checks that a computationally
1649 // expensive downmixer is not required: isFastOutputChannelConversion()
Andy Hung9a592762014-07-21 21:56:01 -07001650 (channelMask == mChannelMask ||
Andy Hung1f439e12015-05-19 12:57:41 -07001651 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
1652 (channelMask == AUDIO_CHANNEL_OUT_MONO
1653 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001654 // hardware sample rate
1655 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001656 // normal mixer has an associated fast mixer
1657 hasFastMixer() &&
1658 // there are sufficient fast track slots available
1659 (mFastTrackAvailMask != 0)
1660 // FIXME test that MixerThread for this fast track has a capable output HAL
1661 // FIXME add a permission test also?
1662 ) {
1663 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1664 if (frameCount == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001665 // read the fast track multiplier property the first time it is needed
1666 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1667 if (ok != 0) {
1668 ALOGE("%s pthread_once failed: %d", __func__, ok);
1669 }
1670 frameCount = mFrameCount * sFastTrackMultiplier;
Eric Laurent81784c32012-11-19 14:55:58 -08001671 }
1672 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
1673 frameCount, mFrameCount);
1674 } else {
1675 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
Andy Hung6146c082014-03-18 11:56:15 -07001676 "mFrameCount=%d format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
1677 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001678 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Andy Hung6146c082014-03-18 11:56:15 -07001679 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001680 audio_is_linear_pcm(format),
1681 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
1682 *flags &= ~IAudioFlinger::TRACK_FAST;
Andy Hung0e48d252015-01-26 11:43:15 -08001683 }
1684 }
1685 // For normal PCM streaming tracks, update minimum frame count.
1686 // For compatibility with AudioTrack calculation, buffer depth is forced
1687 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1688 // This is probably too conservative, but legacy application code may depend on it.
1689 // If you change this calculation, also review the start threshold which is related.
1690 if (!(*flags & IAudioFlinger::TRACK_FAST)
1691 && audio_is_linear_pcm(format) && sharedBuffer == 0) {
Andy Hung8edb8dc2015-03-26 19:13:55 -07001692 // this must match AudioTrack.cpp calculateMinFrameCount().
1693 // TODO: Move to a common library
Eric Laurent81784c32012-11-19 14:55:58 -08001694 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1695 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1696 if (minBufCount < 2) {
1697 minBufCount = 2;
1698 }
Andy Hung8edb8dc2015-03-26 19:13:55 -07001699 // For normal mixing tracks, if speed is > 1.0f (normal), AudioTrack
1700 // or the client should compute and pass in a larger buffer request.
Andy Hung0e48d252015-01-26 11:43:15 -08001701 size_t minFrameCount =
Andy Hung8edb8dc2015-03-26 19:13:55 -07001702 minBufCount * sourceFramesNeededWithTimestretch(
1703 sampleRate, mNormalFrameCount,
1704 mSampleRate, AUDIO_TIMESTRETCH_SPEED_NORMAL /*speed*/);
Andy Hung0e48d252015-01-26 11:43:15 -08001705 if (frameCount < minFrameCount) { // including frameCount == 0
Eric Laurent81784c32012-11-19 14:55:58 -08001706 frameCount = minFrameCount;
1707 }
Eric Laurent81784c32012-11-19 14:55:58 -08001708 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001709 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001710
Glenn Kastenc3df8382014-03-13 15:05:25 -07001711 switch (mType) {
1712
1713 case DIRECT:
Glenn Kasten993fa062014-05-02 11:14:34 -07001714 if (audio_is_linear_pcm(format)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001715 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001716 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1717 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001718 sampleRate, format, channelMask, mOutput, mFormat);
1719 lStatus = BAD_VALUE;
1720 goto Exit;
1721 }
1722 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001723 break;
1724
1725 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001726 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001727 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1728 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001729 sampleRate, format, channelMask, mOutput, mFormat);
1730 lStatus = BAD_VALUE;
1731 goto Exit;
1732 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001733 break;
1734
1735 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07001736 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001737 ALOGE("createTrack_l() Bad parameter: format %#x \""
1738 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001739 format, mOutput, mFormat);
1740 lStatus = BAD_VALUE;
1741 goto Exit;
1742 }
Andy Hungcd044842014-08-07 11:04:34 -07001743 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08001744 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1745 lStatus = BAD_VALUE;
1746 goto Exit;
1747 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001748 break;
1749
Eric Laurent81784c32012-11-19 14:55:58 -08001750 }
1751
1752 lStatus = initCheck();
1753 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07001754 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08001755 goto Exit;
1756 }
1757
1758 { // scope for mLock
1759 Mutex::Autolock _l(mLock);
1760
1761 // all tracks in same audio session must share the same routing strategy otherwise
1762 // conflicts will happen when tracks are moved from one output to another by audio policy
1763 // manager
1764 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1765 for (size_t i = 0; i < mTracks.size(); ++i) {
1766 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07001767 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001768 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1769 if (sessionId == t->sessionId() && strategy != actual) {
1770 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1771 strategy, actual);
1772 lStatus = BAD_VALUE;
1773 goto Exit;
1774 }
1775 }
1776 }
1777
1778 if (!isTimed) {
1779 track = new Track(this, client, streamType, sampleRate, format,
Eric Laurent83b88082014-06-20 18:31:16 -07001780 channelMask, frameCount, NULL, sharedBuffer,
1781 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08001782 } else {
1783 track = TimedTrack::create(this, client, streamType, sampleRate, format,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001784 channelMask, frameCount, sharedBuffer, sessionId, uid);
Eric Laurent81784c32012-11-19 14:55:58 -08001785 }
Glenn Kasten03003332013-08-06 15:40:54 -07001786
1787 // new Track always returns non-NULL,
1788 // but TimedTrack::create() is a factory that could fail by returning NULL
1789 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
1790 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08001791 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001792 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08001793 goto Exit;
1794 }
1795 mTracks.add(track);
1796
1797 sp<EffectChain> chain = getEffectChain_l(sessionId);
1798 if (chain != 0) {
1799 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1800 track->setMainBuffer(chain->inBuffer());
1801 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1802 chain->incTrackCnt();
1803 }
1804
1805 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1806 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1807 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1808 // so ask activity manager to do this on our behalf
1809 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1810 }
1811 }
1812
1813 lStatus = NO_ERROR;
1814
1815Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001816 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001817 return track;
1818}
1819
1820uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1821{
1822 return latency;
1823}
1824
1825uint32_t AudioFlinger::PlaybackThread::latency() const
1826{
1827 Mutex::Autolock _l(mLock);
1828 return latency_l();
1829}
1830uint32_t AudioFlinger::PlaybackThread::latency_l() const
1831{
1832 if (initCheck() == NO_ERROR) {
1833 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
1834 } else {
1835 return 0;
1836 }
1837}
1838
1839void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1840{
1841 Mutex::Autolock _l(mLock);
1842 // Don't apply master volume in SW if our HAL can do it for us.
1843 if (mOutput && mOutput->audioHwDev &&
1844 mOutput->audioHwDev->canSetMasterVolume()) {
1845 mMasterVolume = 1.0;
1846 } else {
1847 mMasterVolume = value;
1848 }
1849}
1850
1851void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1852{
1853 Mutex::Autolock _l(mLock);
1854 // Don't apply master mute in SW if our HAL can do it for us.
1855 if (mOutput && mOutput->audioHwDev &&
1856 mOutput->audioHwDev->canSetMasterMute()) {
1857 mMasterMute = false;
1858 } else {
1859 mMasterMute = muted;
1860 }
1861}
1862
1863void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
1864{
1865 Mutex::Autolock _l(mLock);
1866 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001867 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001868}
1869
1870void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
1871{
1872 Mutex::Autolock _l(mLock);
1873 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001874 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001875}
1876
1877float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
1878{
1879 Mutex::Autolock _l(mLock);
1880 return mStreamTypes[stream].volume;
1881}
1882
1883// addTrack_l() must be called with ThreadBase::mLock held
1884status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1885{
1886 status_t status = ALREADY_EXISTS;
1887
1888 // set retry count for buffer fill
1889 track->mRetryCount = kMaxTrackStartupRetries;
1890 if (mActiveTracks.indexOf(track) < 0) {
1891 // the track is newly added, make sure it fills up all its
1892 // buffers before playing. This is to ensure the client will
1893 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07001894 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001895 TrackBase::track_state state = track->mState;
1896 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08001897 status = AudioSystem::startOutput(mId, track->streamType(),
1898 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001899 mLock.lock();
1900 // abort track was stopped/paused while we released the lock
1901 if (state != track->mState) {
1902 if (status == NO_ERROR) {
1903 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08001904 AudioSystem::stopOutput(mId, track->streamType(),
1905 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001906 mLock.lock();
1907 }
1908 return INVALID_OPERATION;
1909 }
1910 // abort if start is rejected by audio policy manager
1911 if (status != NO_ERROR) {
1912 return PERMISSION_DENIED;
1913 }
1914#ifdef ADD_BATTERY_DATA
1915 // to track the speaker usage
1916 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
1917#endif
1918 }
1919
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001920 track->mFillingUpStatus = track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent81784c32012-11-19 14:55:58 -08001921 track->mResetDone = false;
1922 track->mPresentationCompleteFrames = 0;
1923 mActiveTracks.add(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001924 mWakeLockUids.add(track->uid());
1925 mActiveTracksGeneration++;
Eric Laurentfd477972013-10-25 18:10:40 -07001926 mLatestActiveTrack = track;
Eric Laurentd0107bc2013-06-11 14:38:48 -07001927 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1928 if (chain != 0) {
1929 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
1930 track->sessionId());
1931 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08001932 }
1933
1934 status = NO_ERROR;
1935 }
1936
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08001937 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001938 return status;
1939}
1940
Eric Laurentbfb1b832013-01-07 09:53:42 -08001941bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08001942{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001943 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08001944 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001945 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
1946 track->mState = TrackBase::STOPPED;
1947 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08001948 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07001949 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001950 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08001951 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001952
1953 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08001954}
1955
1956void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1957{
1958 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
1959 mTracks.remove(track);
1960 deleteTrackName_l(track->name());
1961 // redundant as track is about to be destroyed, for dumpsys only
1962 track->mName = -1;
1963 if (track->isFastTrack()) {
1964 int index = track->mFastIndex;
1965 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
1966 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1967 mFastTrackAvailMask |= 1 << index;
1968 // redundant as track is about to be destroyed, for dumpsys only
1969 track->mFastIndex = -1;
1970 }
1971 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1972 if (chain != 0) {
1973 chain->decTrackCnt();
1974 }
1975}
1976
Eric Laurentede6c3b2013-09-19 14:37:46 -07001977void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001978{
1979 // Thread could be blocked waiting for async
1980 // so signal it to handle state changes immediately
1981 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1982 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1983 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001984 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001985}
1986
Eric Laurent81784c32012-11-19 14:55:58 -08001987String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1988{
Eric Laurent81784c32012-11-19 14:55:58 -08001989 Mutex::Autolock _l(mLock);
1990 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07001991 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08001992 }
1993
Glenn Kastend8ea6992013-07-16 14:17:15 -07001994 char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
1995 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08001996 free(s);
1997 return out_s8;
1998}
1999
Eric Laurent73e26b62015-04-27 16:55:58 -07002000void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event) {
2001 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2002 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002003
Eric Laurent73e26b62015-04-27 16:55:58 -07002004 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002005
2006 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002007 case AUDIO_OUTPUT_OPENED:
2008 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002009 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002010 desc->mChannelMask = mChannelMask;
2011 desc->mSamplingRate = mSampleRate;
2012 desc->mFormat = mFormat;
2013 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002014 // AudioFlinger::frameCount(audio_io_handle_t)
Eric Laurent73e26b62015-04-27 16:55:58 -07002015 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002016 break;
2017
Eric Laurent73e26b62015-04-27 16:55:58 -07002018 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002019 default:
2020 break;
2021 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002022 mAudioFlinger->ioConfigChanged(event, desc);
Eric Laurent81784c32012-11-19 14:55:58 -08002023}
2024
Eric Laurentbfb1b832013-01-07 09:53:42 -08002025void AudioFlinger::PlaybackThread::writeCallback()
2026{
2027 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002028 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002029}
2030
2031void AudioFlinger::PlaybackThread::drainCallback()
2032{
2033 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002034 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002035}
2036
Eric Laurent3b4529e2013-09-05 18:09:19 -07002037void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002038{
2039 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002040 // reject out of sequence requests
2041 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2042 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002043 mWaitWorkCV.signal();
2044 }
2045}
2046
Eric Laurent3b4529e2013-09-05 18:09:19 -07002047void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002048{
2049 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002050 // reject out of sequence requests
2051 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
2052 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002053 mWaitWorkCV.signal();
2054 }
2055}
2056
2057// static
2058int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
Glenn Kasten0f11b512014-01-31 16:18:54 -08002059 void *param __unused,
Eric Laurentbfb1b832013-01-07 09:53:42 -08002060 void *cookie)
2061{
2062 AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
2063 ALOGV("asyncCallback() event %d", event);
2064 switch (event) {
2065 case STREAM_CBK_EVENT_WRITE_READY:
2066 me->writeCallback();
2067 break;
2068 case STREAM_CBK_EVENT_DRAIN_READY:
2069 me->drainCallback();
2070 break;
2071 default:
2072 ALOGW("asyncCallback() unknown event %d", event);
2073 break;
2074 }
2075 return 0;
2076}
2077
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002078void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002079{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002080 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Eric Laurent81784c32012-11-19 14:55:58 -08002081 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
2082 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002083 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002084 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002085 }
Andy Hung9a592762014-07-21 21:56:01 -07002086 if ((mType == MIXER || mType == DUPLICATING)
2087 && !isValidPcmSinkChannelMask(mChannelMask)) {
2088 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2089 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002090 }
Andy Hunge5412692014-05-16 11:25:07 -07002091 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Andy Hung463be252014-07-10 16:56:07 -07002092 mHALFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
2093 mFormat = mHALFormat;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002094 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002095 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002096 }
Andy Hung6146c082014-03-18 11:56:15 -07002097 if ((mType == MIXER || mType == DUPLICATING)
2098 && !isValidPcmSinkFormat(mFormat)) {
2099 LOG_FATAL("HAL format %#x not supported for mixed output",
2100 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002101 }
Phil Burk062e67a2015-02-11 13:40:50 -08002102 mFrameSize = mOutput->getFrameSize();
Glenn Kasten70949c42013-08-06 07:40:12 -07002103 mBufferSize = mOutput->stream->common.get_buffer_size(&mOutput->stream->common);
2104 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002105 if (mFrameCount & 15) {
2106 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
2107 mFrameCount);
2108 }
2109
Eric Laurentbfb1b832013-01-07 09:53:42 -08002110 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
2111 (mOutput->stream->set_callback != NULL)) {
2112 if (mOutput->stream->set_callback(mOutput->stream,
2113 AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
2114 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002115 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002116 }
2117 }
2118
Eric Laurentd1f69b02014-12-15 14:33:13 -08002119 mHwSupportsPause = false;
2120 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
2121 if (mOutput->stream->pause != NULL) {
2122 if (mOutput->stream->resume != NULL) {
2123 mHwSupportsPause = true;
2124 } else {
2125 ALOGW("direct output implements pause but not resume");
2126 }
2127 } else if (mOutput->stream->resume != NULL) {
2128 ALOGW("direct output implements resume but not pause");
2129 }
2130 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002131 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2132 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2133 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002134
Andy Hungfbfc3952015-01-15 13:33:51 -08002135 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2136 // For best precision, we use float instead of the associated output
2137 // device format (typically PCM 16 bit).
2138
2139 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2140 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2141 mBufferSize = mFrameSize * mFrameCount;
2142
2143 // TODO: We currently use the associated output device channel mask and sample rate.
2144 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2145 // (if a valid mask) to avoid premature downmix.
2146 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2147 // instead of the output device sample rate to avoid loss of high frequency information.
2148 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2149 }
2150
Andy Hung09a50072014-02-27 14:30:47 -08002151 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002152 double multiplier = 1.0;
2153 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2154 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002155 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2156 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Eric Laurent81784c32012-11-19 14:55:58 -08002157 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2158 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2159 maxNormalFrameCount = maxNormalFrameCount & ~15;
2160 if (maxNormalFrameCount < minNormalFrameCount) {
2161 maxNormalFrameCount = minNormalFrameCount;
2162 }
2163 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2164 if (multiplier <= 1.0) {
2165 multiplier = 1.0;
2166 } else if (multiplier <= 2.0) {
2167 if (2 * mFrameCount <= maxNormalFrameCount) {
2168 multiplier = 2.0;
2169 } else {
2170 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2171 }
2172 } else {
2173 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
Andy Hung09a50072014-02-27 14:30:47 -08002174 // 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 -08002175 // track, but we sometimes have to do this to satisfy the maximum frame count
2176 // constraint)
2177 // FIXME this rounding up should not be done if no HAL SRC
2178 uint32_t truncMult = (uint32_t) multiplier;
2179 if ((truncMult & 1)) {
2180 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
2181 ++truncMult;
2182 }
2183 }
2184 multiplier = (double) truncMult;
2185 }
2186 }
2187 mNormalFrameCount = multiplier * mFrameCount;
2188 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002189 if (mType == MIXER || mType == DUPLICATING) {
2190 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2191 }
Andy Hung09a50072014-02-27 14:30:47 -08002192 ALOGI("HAL output buffer size %u frames, normal sink buffer size %u frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002193 mNormalFrameCount);
2194
Andy Hung08fb1742015-05-31 23:22:10 -07002195 // Check if we want to throttle the processing to no more than 2x normal rate
2196 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
2197 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2198
Andy Hung010a1a12014-03-13 13:57:33 -07002199 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2200 // Originally this was int16_t[] array, need to remove legacy implications.
2201 free(mSinkBuffer);
2202 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002203 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2204 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2205 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002206 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002207
Andy Hung69aed5f2014-02-25 17:24:40 -08002208 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2209 // drives the output.
2210 free(mMixerBuffer);
2211 mMixerBuffer = NULL;
2212 if (mMixerBufferEnabled) {
2213 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2214 mMixerBufferSize = mNormalFrameCount * mChannelCount
2215 * audio_bytes_per_sample(mMixerBufferFormat);
2216 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2217 }
Andy Hung98ef9782014-03-04 14:46:50 -08002218 free(mEffectBuffer);
2219 mEffectBuffer = NULL;
2220 if (mEffectBufferEnabled) {
2221 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
2222 mEffectBufferSize = mNormalFrameCount * mChannelCount
2223 * audio_bytes_per_sample(mEffectBufferFormat);
2224 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2225 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002226
Eric Laurent81784c32012-11-19 14:55:58 -08002227 // force reconfiguration of effect chains and engines to take new buffer size and audio
2228 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002229 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002230 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2231 // matter.
2232 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2233 Vector< sp<EffectChain> > effectChains = mEffectChains;
2234 for (size_t i = 0; i < effectChains.size(); i ++) {
2235 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2236 }
2237}
2238
2239
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002240status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002241{
2242 if (halFrames == NULL || dspFrames == NULL) {
2243 return BAD_VALUE;
2244 }
2245 Mutex::Autolock _l(mLock);
2246 if (initCheck() != NO_ERROR) {
2247 return INVALID_OPERATION;
2248 }
2249 size_t framesWritten = mBytesWritten / mFrameSize;
2250 *halFrames = framesWritten;
2251
2252 if (isSuspended()) {
2253 // return an estimation of rendered frames when the output is suspended
2254 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
2255 *dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0;
2256 return NO_ERROR;
2257 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002258 status_t status;
2259 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002260 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002261 *dspFrames = (size_t)frames;
2262 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002263 }
2264}
2265
2266uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
2267{
2268 Mutex::Autolock _l(mLock);
2269 uint32_t result = 0;
2270 if (getEffectChain_l(sessionId) != 0) {
2271 result = EFFECT_SESSION;
2272 }
2273
2274 for (size_t i = 0; i < mTracks.size(); ++i) {
2275 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002276 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002277 result |= TRACK_SESSION;
2278 break;
2279 }
2280 }
2281
2282 return result;
2283}
2284
2285uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
2286{
2287 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2288 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2289 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2290 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2291 }
2292 for (size_t i = 0; i < mTracks.size(); i++) {
2293 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002294 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002295 return AudioSystem::getStrategyForStream(track->streamType());
2296 }
2297 }
2298 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2299}
2300
2301
Phil Burk062e67a2015-02-11 13:40:50 -08002302AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002303{
2304 Mutex::Autolock _l(mLock);
2305 return mOutput;
2306}
2307
Phil Burk062e67a2015-02-11 13:40:50 -08002308AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002309{
2310 Mutex::Autolock _l(mLock);
2311 AudioStreamOut *output = mOutput;
2312 mOutput = NULL;
2313 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2314 // must push a NULL and wait for ack
2315 mOutputSink.clear();
2316 mPipeSink.clear();
2317 mNormalSink.clear();
2318 return output;
2319}
2320
2321// this method must always be called either with ThreadBase mLock held or inside the thread loop
2322audio_stream_t* AudioFlinger::PlaybackThread::stream() const
2323{
2324 if (mOutput == NULL) {
2325 return NULL;
2326 }
2327 return &mOutput->stream->common;
2328}
2329
2330uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2331{
2332 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2333}
2334
2335status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2336{
2337 if (!isValidSyncEvent(event)) {
2338 return BAD_VALUE;
2339 }
2340
2341 Mutex::Autolock _l(mLock);
2342
2343 for (size_t i = 0; i < mTracks.size(); ++i) {
2344 sp<Track> track = mTracks[i];
2345 if (event->triggerSession() == track->sessionId()) {
2346 (void) track->setSyncEvent(event);
2347 return NO_ERROR;
2348 }
2349 }
2350
2351 return NAME_NOT_FOUND;
2352}
2353
2354bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2355{
2356 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2357}
2358
2359void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2360 const Vector< sp<Track> >& tracksToRemove)
2361{
2362 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002363 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002364 for (size_t i = 0 ; i < count ; i++) {
2365 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002366 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002367 AudioSystem::stopOutput(mId, track->streamType(),
2368 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002369#ifdef ADD_BATTERY_DATA
2370 // to track the speaker usage
2371 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2372#endif
2373 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002374 AudioSystem::releaseOutput(mId, track->streamType(),
2375 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002376 }
Eric Laurent81784c32012-11-19 14:55:58 -08002377 }
2378 }
2379 }
Eric Laurent81784c32012-11-19 14:55:58 -08002380}
2381
2382void AudioFlinger::PlaybackThread::checkSilentMode_l()
2383{
2384 if (!mMasterMute) {
2385 char value[PROPERTY_VALUE_MAX];
2386 if (property_get("ro.audio.silent", value, "0") > 0) {
2387 char *endptr;
2388 unsigned long ul = strtoul(value, &endptr, 0);
2389 if (*endptr == '\0' && ul != 0) {
2390 ALOGD("Silence is golden");
2391 // The setprop command will not allow a property to be changed after
2392 // the first time it is set, so we don't have to worry about un-muting.
2393 setMasterMute_l(true);
2394 }
2395 }
2396 }
2397}
2398
2399// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002400ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002401{
2402 // FIXME rewrite to reduce number of system calls
2403 mLastWriteTime = systemTime();
2404 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002405 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002406 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002407
2408 // If an NBAIO sink is present, use it to write the normal mixer's submix
2409 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002410
Andy Hung010a1a12014-03-13 13:57:33 -07002411 const size_t count = mBytesRemaining / mFrameSize;
2412
Simon Wilson2d590962012-11-29 15:18:50 -08002413 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002414 // update the setpoint when AudioFlinger::mScreenState changes
2415 uint32_t screenState = AudioFlinger::mScreenState;
2416 if (screenState != mScreenState) {
2417 mScreenState = screenState;
2418 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2419 if (pipe != NULL) {
2420 pipe->setAvgFrames((mScreenState & 1) ?
2421 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2422 }
2423 }
Andy Hung010a1a12014-03-13 13:57:33 -07002424 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002425 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002426 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002427 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002428 } else {
2429 bytesWritten = framesWritten;
2430 }
Glenn Kastenefaa7ab2014-08-20 08:48:54 -07002431 mLatchDValid = false;
Glenn Kasten767094d2013-08-23 13:51:43 -07002432 status_t status = mNormalSink->getTimestamp(mLatchD.mTimestamp);
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002433 if (status == NO_ERROR) {
2434 size_t totalFramesWritten = mNormalSink->framesWritten();
2435 if (totalFramesWritten >= mLatchD.mTimestamp.mPosition) {
2436 mLatchD.mUnpresentedFrames = totalFramesWritten - mLatchD.mTimestamp.mPosition;
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002437 // mLatchD.mFramesReleased is set immediately before D is clocked into Q
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002438 mLatchDValid = true;
2439 }
2440 }
Eric Laurent81784c32012-11-19 14:55:58 -08002441 // otherwise use the HAL / AudioStreamOut directly
2442 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002443 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002444
Eric Laurentbfb1b832013-01-07 09:53:42 -08002445 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002446 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2447 mWriteAckSequence += 2;
2448 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002449 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002450 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002451 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002452 // FIXME We should have an implementation of timestamps for direct output threads.
2453 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002454 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002455 if (mUseAsyncWrite &&
2456 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2457 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002458 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002459 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002460 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002461 }
Eric Laurent81784c32012-11-19 14:55:58 -08002462 }
2463
Eric Laurent81784c32012-11-19 14:55:58 -08002464 mNumWrites++;
2465 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002466 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002467 return bytesWritten;
2468}
2469
2470void AudioFlinger::PlaybackThread::threadLoop_drain()
2471{
2472 if (mOutput->stream->drain) {
2473 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2474 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002475 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2476 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002477 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002478 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002479 }
2480 mOutput->stream->drain(mOutput->stream,
2481 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
2482 : AUDIO_DRAIN_ALL);
2483 }
2484}
2485
2486void AudioFlinger::PlaybackThread::threadLoop_exit()
2487{
Eric Laurent275e8e92014-11-30 15:14:47 -08002488 {
2489 Mutex::Autolock _l(mLock);
2490 for (size_t i = 0; i < mTracks.size(); i++) {
2491 sp<Track> track = mTracks[i];
2492 track->invalidate();
2493 }
2494 }
Eric Laurent81784c32012-11-19 14:55:58 -08002495}
2496
2497/*
2498The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002499 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002500 - mActiveSleepTimeUs from activeSleepTimeUs()
2501 - mIdleSleepTimeUs from idleSleepTimeUs()
2502 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only)
Eric Laurent81784c32012-11-19 14:55:58 -08002503 - maxPeriod from frame count and sample rate (MIXER only)
2504
2505The parameters that affect these derived values are:
2506 - frame count
2507 - frame size
2508 - sample rate
2509 - device type: A2DP or not
2510 - device latency
2511 - format: PCM or not
2512 - active sleep time
2513 - idle sleep time
2514*/
2515
2516void AudioFlinger::PlaybackThread::cacheParameters_l()
2517{
Andy Hung25c2dac2014-02-27 14:56:00 -08002518 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002519 mActiveSleepTimeUs = activeSleepTimeUs();
2520 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent81784c32012-11-19 14:55:58 -08002521}
2522
2523void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2524{
Glenn Kasten7c027242012-12-26 14:43:16 -08002525 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurent81784c32012-11-19 14:55:58 -08002526 this, streamType, mTracks.size());
2527 Mutex::Autolock _l(mLock);
2528
2529 size_t size = mTracks.size();
2530 for (size_t i = 0; i < size; i++) {
2531 sp<Track> t = mTracks[i];
2532 if (t->streamType() == streamType) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002533 t->invalidate();
Eric Laurent81784c32012-11-19 14:55:58 -08002534 }
2535 }
2536}
2537
2538status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2539{
2540 int session = chain->sessionId();
Andy Hung010a1a12014-03-13 13:57:33 -07002541 int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled
2542 ? mEffectBuffer : mSinkBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002543 bool ownsBuffer = false;
2544
2545 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
2546 if (session > 0) {
2547 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002548 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002549 if (mType != DIRECT) {
2550 size_t numSamples = mNormalFrameCount * mChannelCount;
2551 buffer = new int16_t[numSamples];
2552 memset(buffer, 0, numSamples * sizeof(int16_t));
2553 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2554 ownsBuffer = true;
2555 }
2556
2557 // Attach all tracks with same session ID to this chain.
2558 for (size_t i = 0; i < mTracks.size(); ++i) {
2559 sp<Track> track = mTracks[i];
2560 if (session == track->sessionId()) {
2561 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2562 buffer);
2563 track->setMainBuffer(buffer);
2564 chain->incTrackCnt();
2565 }
2566 }
2567
2568 // indicate all active tracks in the chain
2569 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2570 sp<Track> track = mActiveTracks[i].promote();
2571 if (track == 0) {
2572 continue;
2573 }
2574 if (session == track->sessionId()) {
2575 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2576 chain->incActiveTrackCnt();
2577 }
2578 }
2579 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002580 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08002581 chain->setInBuffer(buffer, ownsBuffer);
Andy Hung010a1a12014-03-13 13:57:33 -07002582 chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled
2583 ? mEffectBuffer : mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002584 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
2585 // chains list in order to be processed last as it contains output stage effects
2586 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2587 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
2588 // after track specific effects and before output stage
2589 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
2590 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
2591 // Effect chain for other sessions are inserted at beginning of effect
2592 // chains list to be processed before output mix effects. Relative order between other
2593 // sessions is not important
2594 size_t size = mEffectChains.size();
2595 size_t i = 0;
2596 for (i = 0; i < size; i++) {
2597 if (mEffectChains[i]->sessionId() < session) {
2598 break;
2599 }
2600 }
2601 mEffectChains.insertAt(chain, i);
2602 checkSuspendOnAddEffectChain_l(chain);
2603
2604 return NO_ERROR;
2605}
2606
2607size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2608{
2609 int session = chain->sessionId();
2610
2611 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2612
2613 for (size_t i = 0; i < mEffectChains.size(); i++) {
2614 if (chain == mEffectChains[i]) {
2615 mEffectChains.removeAt(i);
2616 // detach all active tracks from the chain
2617 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2618 sp<Track> track = mActiveTracks[i].promote();
2619 if (track == 0) {
2620 continue;
2621 }
2622 if (session == track->sessionId()) {
2623 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2624 chain.get(), session);
2625 chain->decActiveTrackCnt();
2626 }
2627 }
2628
2629 // detach all tracks with same session ID from this chain
2630 for (size_t i = 0; i < mTracks.size(); ++i) {
2631 sp<Track> track = mTracks[i];
2632 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002633 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002634 chain->decTrackCnt();
2635 }
2636 }
2637 break;
2638 }
2639 }
2640 return mEffectChains.size();
2641}
2642
2643status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2644 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2645{
2646 Mutex::Autolock _l(mLock);
2647 return attachAuxEffect_l(track, EffectId);
2648}
2649
2650status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2651 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2652{
2653 status_t status = NO_ERROR;
2654
2655 if (EffectId == 0) {
2656 track->setAuxBuffer(0, NULL);
2657 } else {
2658 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2659 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2660 if (effect != 0) {
2661 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2662 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2663 } else {
2664 status = INVALID_OPERATION;
2665 }
2666 } else {
2667 status = BAD_VALUE;
2668 }
2669 }
2670 return status;
2671}
2672
2673void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2674{
2675 for (size_t i = 0; i < mTracks.size(); ++i) {
2676 sp<Track> track = mTracks[i];
2677 if (track->auxEffectId() == effectId) {
2678 attachAuxEffect_l(track, 0);
2679 }
2680 }
2681}
2682
2683bool AudioFlinger::PlaybackThread::threadLoop()
2684{
2685 Vector< sp<Track> > tracksToRemove;
2686
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002687 mStandbyTimeNs = systemTime();
Eric Laurent81784c32012-11-19 14:55:58 -08002688
2689 // MIXER
2690 nsecs_t lastWarning = 0;
2691
2692 // DUPLICATING
2693 // FIXME could this be made local to while loop?
2694 writeFrames = 0;
2695
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002696 int lastGeneration = 0;
2697
Eric Laurent81784c32012-11-19 14:55:58 -08002698 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002699 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08002700
2701 if (mType == MIXER) {
2702 sleepTimeShift = 0;
2703 }
2704
2705 CpuStats cpuStats;
2706 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2707
2708 acquireWakeLock();
2709
Glenn Kasten9e58b552013-01-18 15:09:48 -08002710 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2711 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2712 // and then that string will be logged at the next convenient opportunity.
2713 const char *logString = NULL;
2714
Eric Laurent664539d2013-09-23 18:24:31 -07002715 checkSilentMode_l();
2716
Eric Laurent81784c32012-11-19 14:55:58 -08002717 while (!exitPending())
2718 {
2719 cpuStats.sample(myName);
2720
2721 Vector< sp<EffectChain> > effectChains;
2722
Eric Laurent81784c32012-11-19 14:55:58 -08002723 { // scope for mLock
2724
2725 Mutex::Autolock _l(mLock);
2726
Eric Laurent021cf962014-05-13 10:18:14 -07002727 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07002728
Glenn Kasten9e58b552013-01-18 15:09:48 -08002729 if (logString != NULL) {
2730 mNBLogWriter->logTimestamp();
2731 mNBLogWriter->log(logString);
2732 logString = NULL;
2733 }
2734
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002735 // Gather the framesReleased counters for all active tracks,
2736 // and latch them atomically with the timestamp.
2737 // FIXME We're using raw pointers as indices. A unique track ID would be a better index.
2738 mLatchD.mFramesReleased.clear();
2739 size_t size = mActiveTracks.size();
2740 for (size_t i = 0; i < size; i++) {
2741 sp<Track> t = mActiveTracks[i].promote();
2742 if (t != 0) {
2743 mLatchD.mFramesReleased.add(t.get(),
2744 t->mAudioTrackServerProxy->framesReleased());
2745 }
2746 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002747 if (mLatchDValid) {
2748 mLatchQ = mLatchD;
2749 mLatchDValid = false;
2750 mLatchQValid = true;
2751 }
2752
Eric Laurent81784c32012-11-19 14:55:58 -08002753 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002754 if (mSignalPending) {
2755 // A signal was raised while we were unlocked
2756 mSignalPending = false;
2757 } else if (waitingAsyncCallback_l()) {
2758 if (exitPending()) {
2759 break;
2760 }
Marco Nelissen078538c2015-05-12 09:17:57 -07002761 bool released = false;
2762 // The following works around a bug in the offload driver. Ideally we would release
2763 // the wake lock every time, but that causes the last offload buffer(s) to be
2764 // dropped while the device is on battery, so we need to hold a wake lock during
2765 // the drain phase.
2766 if (mBytesRemaining && !(mDrainSequence & 1)) {
2767 releaseWakeLock_l();
2768 released = true;
2769 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002770 mWakeLockUids.clear();
2771 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002772 ALOGV("wait async completion");
2773 mWaitWorkCV.wait(mLock);
2774 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07002775 if (released) {
2776 acquireWakeLock_l();
2777 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002778 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
2779 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002780
2781 continue;
2782 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002783 if ((!mActiveTracks.size() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08002784 isSuspended()) {
2785 // put audio hardware into standby after short delay
2786 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002787
2788 threadLoop_standby();
2789
2790 mStandby = true;
2791 }
2792
2793 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2794 // we're about to wait, flush the binder command buffer
2795 IPCThreadState::self()->flushCommands();
2796
2797 clearOutputTracks();
2798
2799 if (exitPending()) {
2800 break;
2801 }
2802
2803 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002804 mWakeLockUids.clear();
2805 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002806 // wait until we have something to do...
2807 ALOGV("%s going to sleep", myName.string());
2808 mWaitWorkCV.wait(mLock);
2809 ALOGV("%s waking up", myName.string());
2810 acquireWakeLock_l();
2811
2812 mMixerStatus = MIXER_IDLE;
2813 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2814 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002815 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002816 checkSilentMode_l();
2817
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002818 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
2819 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08002820 if (mType == MIXER) {
2821 sleepTimeShift = 0;
2822 }
2823
2824 continue;
2825 }
2826 }
Eric Laurent81784c32012-11-19 14:55:58 -08002827 // mMixerStatusIgnoringFastTracks is also updated internally
2828 mMixerStatus = prepareTracks_l(&tracksToRemove);
2829
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002830 // compare with previously applied list
2831 if (lastGeneration != mActiveTracksGeneration) {
2832 // update wakelock
2833 updateWakeLockUids_l(mWakeLockUids);
2834 lastGeneration = mActiveTracksGeneration;
2835 }
2836
Eric Laurent81784c32012-11-19 14:55:58 -08002837 // prevent any changes in effect chain list and in each effect chain
2838 // during mixing and effect process as the audio buffers could be deleted
2839 // or modified if an effect is created or deleted
2840 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002841 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08002842
Eric Laurentbfb1b832013-01-07 09:53:42 -08002843 if (mBytesRemaining == 0) {
2844 mCurrentWriteLength = 0;
2845 if (mMixerStatus == MIXER_TRACKS_READY) {
2846 // threadLoop_mix() sets mCurrentWriteLength
2847 threadLoop_mix();
2848 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
2849 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002850 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08002851 // must be written to HAL
2852 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002853 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08002854 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002855 }
2856 }
Andy Hung98ef9782014-03-04 14:46:50 -08002857 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002858 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08002859 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
2860 // or mSinkBuffer (if there are no effects).
2861 //
2862 // This is done pre-effects computation; if effects change to
2863 // support higher precision, this needs to move.
2864 //
2865 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002866 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08002867 if (mMixerBufferValid) {
2868 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
2869 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
2870
2871 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
2872 mNormalFrameCount * mChannelCount);
2873 }
2874
Eric Laurentbfb1b832013-01-07 09:53:42 -08002875 mBytesRemaining = mCurrentWriteLength;
2876 if (isSuspended()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002877 mSleepTimeUs = suspendSleepTimeUs();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002878 // simulate write to HAL when suspended
Andy Hung25c2dac2014-02-27 14:56:00 -08002879 mBytesWritten += mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002880 mBytesRemaining = 0;
2881 }
Eric Laurent81784c32012-11-19 14:55:58 -08002882
Eric Laurentbfb1b832013-01-07 09:53:42 -08002883 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002884 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002885 for (size_t i = 0; i < effectChains.size(); i ++) {
2886 effectChains[i]->process_l();
2887 }
Eric Laurent81784c32012-11-19 14:55:58 -08002888 }
2889 }
Eric Laurent59fe0102013-09-27 18:48:26 -07002890 // Process effect chains for offloaded thread even if no audio
2891 // was read from audio track: process only updates effect state
2892 // and thus does have to be synchronized with audio writes but may have
2893 // to be called while waiting for async write callback
2894 if (mType == OFFLOAD) {
2895 for (size_t i = 0; i < effectChains.size(); i ++) {
2896 effectChains[i]->process_l();
2897 }
2898 }
Eric Laurent81784c32012-11-19 14:55:58 -08002899
Andy Hung98ef9782014-03-04 14:46:50 -08002900 // Only if the Effects buffer is enabled and there is data in the
2901 // Effects buffer (buffer valid), we need to
2902 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002903 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08002904 if (mEffectBufferValid) {
2905 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
2906 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
2907 mNormalFrameCount * mChannelCount);
2908 }
2909
Eric Laurent81784c32012-11-19 14:55:58 -08002910 // enable changes in effect chain
2911 unlockEffectChains(effectChains);
2912
Eric Laurentbfb1b832013-01-07 09:53:42 -08002913 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002914 // mSleepTimeUs == 0 means we must write to audio hardware
2915 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07002916 ssize_t ret = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002917 if (mBytesRemaining) {
Andy Hung08fb1742015-05-31 23:22:10 -07002918 ret = threadLoop_write();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002919 if (ret < 0) {
2920 mBytesRemaining = 0;
2921 } else {
2922 mBytesWritten += ret;
2923 mBytesRemaining -= ret;
2924 }
2925 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
2926 (mMixerStatus == MIXER_DRAIN_ALL)) {
2927 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08002928 }
Andy Hung08fb1742015-05-31 23:22:10 -07002929 if (mType == MIXER && !mStandby) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07002930 // write blocked detection
2931 nsecs_t now = systemTime();
2932 nsecs_t delta = now - mLastWriteTime;
Andy Hung08fb1742015-05-31 23:22:10 -07002933 if (delta > maxPeriod) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07002934 mNumDelayedWrites++;
2935 if ((now - lastWarning) > kWarningThrottleNs) {
2936 ATRACE_NAME("underrun");
2937 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2938 ns2ms(delta), mNumDelayedWrites, this);
2939 lastWarning = now;
2940 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002941 }
Andy Hung08fb1742015-05-31 23:22:10 -07002942
2943 if (mThreadThrottle
2944 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
2945 && ret > 0) { // we wrote something
2946 // Limit MixerThread data processing to no more than twice the
2947 // expected processing rate.
2948 //
2949 // This helps prevent underruns with NuPlayer and other applications
2950 // which may set up buffers that are close to the minimum size, or use
2951 // deep buffers, and rely on a double-buffering sleep strategy to fill.
2952 //
2953 // The throttle smooths out sudden large data drains from the device,
2954 // e.g. when it comes out of standby, which often causes problems with
2955 // (1) mixer threads without a fast mixer (which has its own warm-up)
2956 // (2) minimum buffer sized tracks (even if the track is full,
2957 // the app won't fill fast enough to handle the sudden draw).
2958
2959 const int32_t deltaMs = delta / 1000000;
2960 const int32_t throttleMs = mHalfBufferMs - deltaMs;
2961 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
2962 usleep(throttleMs * 1000);
2963 ALOGD("mixer(%p) throttle: ret(%zd) deltaMs(%d) requires sleep %d ms",
2964 this, ret, deltaMs, throttleMs);
2965 }
2966 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002967 }
Eric Laurent81784c32012-11-19 14:55:58 -08002968
Eric Laurentbfb1b832013-01-07 09:53:42 -08002969 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07002970 ATRACE_BEGIN("sleep");
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002971 usleep(mSleepTimeUs);
Glenn Kastene7754022014-10-31 12:11:26 -07002972 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002973 }
Eric Laurent81784c32012-11-19 14:55:58 -08002974 }
2975
2976 // Finally let go of removed track(s), without the lock held
2977 // since we can't guarantee the destructors won't acquire that
2978 // same lock. This will also mutate and push a new fast mixer state.
2979 threadLoop_removeTracks(tracksToRemove);
2980 tracksToRemove.clear();
2981
2982 // FIXME I don't understand the need for this here;
2983 // it was in the original code but maybe the
2984 // assignment in saveOutputTracks() makes this unnecessary?
2985 clearOutputTracks();
2986
2987 // Effect chains will be actually deleted here if they were removed from
2988 // mEffectChains list during mixing or effects processing
2989 effectChains.clear();
2990
2991 // FIXME Note that the above .clear() is no longer necessary since effectChains
2992 // is now local to this block, but will keep it for now (at least until merge done).
2993 }
2994
Eric Laurentbfb1b832013-01-07 09:53:42 -08002995 threadLoop_exit();
2996
Eric Laurentcf817a22014-08-04 20:36:31 -07002997 if (!mStandby) {
2998 threadLoop_standby();
2999 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003000 }
3001
3002 releaseWakeLock();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003003 mWakeLockUids.clear();
3004 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08003005
3006 ALOGV("Thread %p type %d exiting", this, mType);
3007 return false;
3008}
3009
Eric Laurentbfb1b832013-01-07 09:53:42 -08003010// removeTracks_l() must be called with ThreadBase::mLock held
3011void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3012{
3013 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07003014 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003015 for (size_t i=0 ; i<count ; i++) {
3016 const sp<Track>& track = tracksToRemove.itemAt(i);
3017 mActiveTracks.remove(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003018 mWakeLockUids.remove(track->uid());
3019 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003020 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
3021 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3022 if (chain != 0) {
3023 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
3024 track->sessionId());
3025 chain->decActiveTrackCnt();
3026 }
3027 if (track->isTerminated()) {
3028 removeTrack_l(track);
3029 }
3030 }
3031 }
3032
3033}
Eric Laurent81784c32012-11-19 14:55:58 -08003034
Eric Laurentaccc1472013-09-20 09:36:34 -07003035status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3036{
3037 if (mNormalSink != 0) {
3038 return mNormalSink->getTimestamp(timestamp);
3039 }
Andy Hung9a1c8892014-12-03 11:37:42 -08003040 if ((mType == OFFLOAD || mType == DIRECT)
3041 && mOutput != NULL && mOutput->stream->get_presentation_position) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003042 uint64_t position64;
Phil Burk062e67a2015-02-11 13:40:50 -08003043 int ret = mOutput->getPresentationPosition(&position64, &timestamp.mTime);
Eric Laurentaccc1472013-09-20 09:36:34 -07003044 if (ret == 0) {
3045 timestamp.mPosition = (uint32_t)position64;
3046 return NO_ERROR;
3047 }
3048 }
3049 return INVALID_OPERATION;
3050}
Eric Laurent1c333e22014-05-20 10:48:17 -07003051
Eric Laurent054d9d32015-04-24 08:48:48 -07003052status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
3053 audio_patch_handle_t *handle)
3054{
3055 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3056 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3057 if (mFastMixer != 0) {
3058 FastMixerStateQueue *sq = mFastMixer->sq();
3059 FastMixerState *state = sq->begin();
3060 if (!(state->mCommand & FastMixerState::IDLE)) {
3061 previousCommand = state->mCommand;
3062 state->mCommand = FastMixerState::HOT_IDLE;
3063 sq->end();
3064 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3065 } else {
3066 sq->end(false /*didModify*/);
3067 }
3068 }
3069 status_t status = PlaybackThread::createAudioPatch_l(patch, handle);
3070
3071 if (!(previousCommand & FastMixerState::IDLE)) {
3072 ALOG_ASSERT(mFastMixer != 0);
3073 FastMixerStateQueue *sq = mFastMixer->sq();
3074 FastMixerState *state = sq->begin();
3075 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3076 state->mCommand = previousCommand;
3077 sq->end();
3078 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3079 }
3080
3081 return status;
3082}
3083
Eric Laurent1c333e22014-05-20 10:48:17 -07003084status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3085 audio_patch_handle_t *handle)
3086{
3087 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003088
3089 // store new device and send to effects
3090 audio_devices_t type = AUDIO_DEVICE_NONE;
3091 for (unsigned int i = 0; i < patch->num_sinks; i++) {
3092 type |= patch->sinks[i].ext.device.type;
3093 }
3094
3095#ifdef ADD_BATTERY_DATA
3096 // when changing the audio output device, call addBatteryData to notify
3097 // the change
3098 if (mOutDevice != type) {
3099 uint32_t params = 0;
3100 // check whether speaker is on
3101 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3102 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003103 }
3104
Eric Laurent054d9d32015-04-24 08:48:48 -07003105 audio_devices_t deviceWithoutSpeaker
3106 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3107 // check if any other device (except speaker) is on
3108 if (type & deviceWithoutSpeaker) {
3109 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3110 }
3111
3112 if (params != 0) {
3113 addBatteryData(params);
3114 }
3115 }
3116#endif
3117
3118 for (size_t i = 0; i < mEffectChains.size(); i++) {
3119 mEffectChains[i]->setDevice_l(type);
3120 }
3121 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003122 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003123
3124 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003125 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
3126 status = hwDevice->create_audio_patch(hwDevice,
3127 patch->num_sources,
3128 patch->sources,
3129 patch->num_sinks,
3130 patch->sinks,
3131 handle);
3132 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003133 char *address;
3134 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3135 //FIXME: we only support address on first sink with HAL version < 3.0
3136 address = audio_device_address_to_parameter(
3137 patch->sinks[0].ext.device.type,
3138 patch->sinks[0].ext.device.address);
3139 } else {
3140 address = (char *)calloc(1, 1);
3141 }
3142 AudioParameter param = AudioParameter(String8(address));
3143 free(address);
3144 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), (int)type);
3145 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3146 param.toString().string());
3147 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003148 }
Eric Laurent296fb132015-05-01 11:38:42 -07003149 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent1c333e22014-05-20 10:48:17 -07003150 return status;
3151}
3152
Eric Laurent054d9d32015-04-24 08:48:48 -07003153status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3154{
3155 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3156 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3157 if (mFastMixer != 0) {
3158 FastMixerStateQueue *sq = mFastMixer->sq();
3159 FastMixerState *state = sq->begin();
3160 if (!(state->mCommand & FastMixerState::IDLE)) {
3161 previousCommand = state->mCommand;
3162 state->mCommand = FastMixerState::HOT_IDLE;
3163 sq->end();
3164 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3165 } else {
3166 sq->end(false /*didModify*/);
3167 }
3168 }
3169
3170 status_t status = PlaybackThread::releaseAudioPatch_l(handle);
3171
3172 if (!(previousCommand & FastMixerState::IDLE)) {
3173 ALOG_ASSERT(mFastMixer != 0);
3174 FastMixerStateQueue *sq = mFastMixer->sq();
3175 FastMixerState *state = sq->begin();
3176 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3177 state->mCommand = previousCommand;
3178 sq->end();
3179 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3180 }
3181
3182 return status;
3183}
3184
Eric Laurent1c333e22014-05-20 10:48:17 -07003185status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3186{
3187 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003188
3189 mOutDevice = AUDIO_DEVICE_NONE;
3190
Eric Laurent1c333e22014-05-20 10:48:17 -07003191 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
3192 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
3193 status = hwDevice->release_audio_patch(hwDevice, handle);
3194 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003195 AudioParameter param;
3196 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
3197 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3198 param.toString().string());
Eric Laurent1c333e22014-05-20 10:48:17 -07003199 }
3200 return status;
3201}
3202
Eric Laurent83b88082014-06-20 18:31:16 -07003203void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3204{
3205 Mutex::Autolock _l(mLock);
3206 mTracks.add(track);
3207}
3208
3209void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3210{
3211 Mutex::Autolock _l(mLock);
3212 destroyTrack_l(track);
3213}
3214
3215void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
3216{
3217 ThreadBase::getAudioPortConfig(config);
3218 config->role = AUDIO_PORT_ROLE_SOURCE;
3219 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3220 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
3221}
3222
Eric Laurent81784c32012-11-19 14:55:58 -08003223// ----------------------------------------------------------------------------
3224
3225AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurent72e3f392015-05-20 14:43:50 -07003226 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
3227 : PlaybackThread(audioFlinger, output, id, device, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08003228 // mAudioMixer below
3229 // mFastMixer below
3230 mFastMixerFutex(0)
3231 // mOutputSink below
3232 // mPipeSink below
3233 // mNormalSink below
3234{
3235 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07003236 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, "
Eric Laurent81784c32012-11-19 14:55:58 -08003237 "mFrameCount=%d, mNormalFrameCount=%d",
3238 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3239 mNormalFrameCount);
3240 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3241
Andy Hungfbfc3952015-01-15 13:33:51 -08003242 if (type == DUPLICATING) {
3243 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3244 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3245 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3246 return;
3247 }
Eric Laurent81784c32012-11-19 14:55:58 -08003248 // create an NBAIO sink for the HAL output stream, and negotiate
3249 mOutputSink = new AudioStreamOutSink(output->stream);
3250 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003251 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Eric Laurent81784c32012-11-19 14:55:58 -08003252 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
3253 ALOG_ASSERT(index == 0);
3254
3255 // initialize fast mixer depending on configuration
3256 bool initFastMixer;
3257 switch (kUseFastMixer) {
3258 case FastMixer_Never:
3259 initFastMixer = false;
3260 break;
3261 case FastMixer_Always:
3262 initFastMixer = true;
3263 break;
3264 case FastMixer_Static:
3265 case FastMixer_Dynamic:
3266 initFastMixer = mFrameCount < mNormalFrameCount;
3267 break;
3268 }
3269 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003270 audio_format_t fastMixerFormat;
3271 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3272 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3273 } else {
3274 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3275 }
3276 if (mFormat != fastMixerFormat) {
3277 // change our Sink format to accept our intermediate precision
3278 mFormat = fastMixerFormat;
3279 free(mSinkBuffer);
3280 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3281 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3282 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3283 }
Eric Laurent81784c32012-11-19 14:55:58 -08003284
3285 // create a MonoPipe to connect our submix to FastMixer
3286 NBAIO_Format format = mOutputSink->format();
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003287 NBAIO_Format origformat = format;
Andy Hung1258c1a2014-05-23 21:22:17 -07003288 // adjust format to match that of the Fast Mixer
Glenn Kasten97b7b752014-09-28 13:04:24 -07003289 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003290 format.mFormat = fastMixerFormat;
3291 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3292
Eric Laurent81784c32012-11-19 14:55:58 -08003293 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3294 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3295 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3296 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3297 const NBAIO_Format offers[1] = {format};
3298 size_t numCounterOffers = 0;
3299 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
3300 ALOG_ASSERT(index == 0);
3301 monoPipe->setAvgFrames((mScreenState & 1) ?
3302 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3303 mPipeSink = monoPipe;
3304
Glenn Kasten46909e72013-02-26 09:20:22 -08003305#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08003306 if (mTeeSinkOutputEnabled) {
3307 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003308 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
3309 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08003310 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003311 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003312 ALOG_ASSERT(index == 0);
3313 mTeeSink = teeSink;
3314 PipeReader *teeSource = new PipeReader(*teeSink);
3315 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003316 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003317 ALOG_ASSERT(index == 0);
3318 mTeeSource = teeSource;
3319 }
Glenn Kasten46909e72013-02-26 09:20:22 -08003320#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003321
3322 // create fast mixer and configure it initially with just one fast track for our submix
3323 mFastMixer = new FastMixer();
3324 FastMixerStateQueue *sq = mFastMixer->sq();
3325#ifdef STATE_QUEUE_DUMP
3326 sq->setObserverDump(&mStateQueueObserverDump);
3327 sq->setMutatorDump(&mStateQueueMutatorDump);
3328#endif
3329 FastMixerState *state = sq->begin();
3330 FastTrack *fastTrack = &state->mFastTracks[0];
3331 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3332 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3333 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003334 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3335 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003336 fastTrack->mGeneration++;
3337 state->mFastTracksGen++;
3338 state->mTrackMask = 1;
3339 // fast mixer will use the HAL output sink
3340 state->mOutputSink = mOutputSink.get();
3341 state->mOutputSinkGen++;
3342 state->mFrameCount = mFrameCount;
3343 state->mCommand = FastMixerState::COLD_IDLE;
3344 // already done in constructor initialization list
3345 //mFastMixerFutex = 0;
3346 state->mColdFutexAddr = &mFastMixerFutex;
3347 state->mColdGen++;
3348 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08003349#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003350 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08003351#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08003352 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3353 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003354 sq->end();
3355 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3356
3357 // start the fast mixer
3358 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3359 pid_t tid = mFastMixer->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003360 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003361
3362#ifdef AUDIO_WATCHDOG
3363 // create and start the watchdog
3364 mAudioWatchdog = new AudioWatchdog();
3365 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3366 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3367 tid = mAudioWatchdog->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003368 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003369#endif
3370
Eric Laurent81784c32012-11-19 14:55:58 -08003371 }
3372
3373 switch (kUseFastMixer) {
3374 case FastMixer_Never:
3375 case FastMixer_Dynamic:
3376 mNormalSink = mOutputSink;
3377 break;
3378 case FastMixer_Always:
3379 mNormalSink = mPipeSink;
3380 break;
3381 case FastMixer_Static:
3382 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3383 break;
3384 }
3385}
3386
3387AudioFlinger::MixerThread::~MixerThread()
3388{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003389 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003390 FastMixerStateQueue *sq = mFastMixer->sq();
3391 FastMixerState *state = sq->begin();
3392 if (state->mCommand == FastMixerState::COLD_IDLE) {
3393 int32_t old = android_atomic_inc(&mFastMixerFutex);
3394 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003395 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003396 }
3397 }
3398 state->mCommand = FastMixerState::EXIT;
3399 sq->end();
3400 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3401 mFastMixer->join();
3402 // Though the fast mixer thread has exited, it's state queue is still valid.
3403 // We'll use that extract the final state which contains one remaining fast track
3404 // corresponding to our sub-mix.
3405 state = sq->begin();
3406 ALOG_ASSERT(state->mTrackMask == 1);
3407 FastTrack *fastTrack = &state->mFastTracks[0];
3408 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3409 delete fastTrack->mBufferProvider;
3410 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003411 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003412#ifdef AUDIO_WATCHDOG
3413 if (mAudioWatchdog != 0) {
3414 mAudioWatchdog->requestExit();
3415 mAudioWatchdog->requestExitAndWait();
3416 mAudioWatchdog.clear();
3417 }
3418#endif
3419 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003420 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003421 delete mAudioMixer;
3422}
3423
3424
3425uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3426{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003427 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003428 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3429 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3430 }
3431 return latency;
3432}
3433
3434
3435void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3436{
3437 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3438}
3439
Eric Laurentbfb1b832013-01-07 09:53:42 -08003440ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003441{
3442 // FIXME we should only do one push per cycle; confirm this is true
3443 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003444 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003445 FastMixerStateQueue *sq = mFastMixer->sq();
3446 FastMixerState *state = sq->begin();
3447 if (state->mCommand != FastMixerState::MIX_WRITE &&
3448 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3449 if (state->mCommand == FastMixerState::COLD_IDLE) {
3450 int32_t old = android_atomic_inc(&mFastMixerFutex);
3451 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003452 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003453 }
3454#ifdef AUDIO_WATCHDOG
3455 if (mAudioWatchdog != 0) {
3456 mAudioWatchdog->resume();
3457 }
3458#endif
3459 }
3460 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08003461#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003462 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08003463 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08003464#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003465 sq->end();
3466 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3467 if (kUseFastMixer == FastMixer_Dynamic) {
3468 mNormalSink = mPipeSink;
3469 }
3470 } else {
3471 sq->end(false /*didModify*/);
3472 }
3473 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003474 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003475}
3476
3477void AudioFlinger::MixerThread::threadLoop_standby()
3478{
3479 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003480 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003481 FastMixerStateQueue *sq = mFastMixer->sq();
3482 FastMixerState *state = sq->begin();
3483 if (!(state->mCommand & FastMixerState::IDLE)) {
3484 state->mCommand = FastMixerState::COLD_IDLE;
3485 state->mColdFutexAddr = &mFastMixerFutex;
3486 state->mColdGen++;
3487 mFastMixerFutex = 0;
3488 sq->end();
3489 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3490 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3491 if (kUseFastMixer == FastMixer_Dynamic) {
3492 mNormalSink = mOutputSink;
3493 }
3494#ifdef AUDIO_WATCHDOG
3495 if (mAudioWatchdog != 0) {
3496 mAudioWatchdog->pause();
3497 }
3498#endif
3499 } else {
3500 sq->end(false /*didModify*/);
3501 }
3502 }
3503 PlaybackThread::threadLoop_standby();
3504}
3505
Eric Laurentbfb1b832013-01-07 09:53:42 -08003506bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3507{
3508 return false;
3509}
3510
3511bool AudioFlinger::PlaybackThread::shouldStandby_l()
3512{
3513 return !mStandby;
3514}
3515
3516bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3517{
3518 Mutex::Autolock _l(mLock);
3519 return waitingAsyncCallback_l();
3520}
3521
Eric Laurent81784c32012-11-19 14:55:58 -08003522// shared by MIXER and DIRECT, overridden by DUPLICATING
3523void AudioFlinger::PlaybackThread::threadLoop_standby()
3524{
3525 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08003526 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003527 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003528 // discard any pending drain or write ack by incrementing sequence
3529 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3530 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003531 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003532 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3533 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003534 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003535 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003536}
3537
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003538void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3539{
3540 ALOGV("signal playback thread");
3541 broadcast_l();
3542}
3543
Eric Laurent81784c32012-11-19 14:55:58 -08003544void AudioFlinger::MixerThread::threadLoop_mix()
3545{
3546 // obtain the presentation timestamp of the next output buffer
3547 int64_t pts;
3548 status_t status = INVALID_OPERATION;
3549
3550 if (mNormalSink != 0) {
3551 status = mNormalSink->getNextWriteTimestamp(&pts);
3552 } else {
3553 status = mOutputSink->getNextWriteTimestamp(&pts);
3554 }
3555
3556 if (status != NO_ERROR) {
3557 pts = AudioBufferProvider::kInvalidPTS;
3558 }
3559
3560 // mix buffers...
3561 mAudioMixer->process(pts);
Andy Hung25c2dac2014-02-27 14:56:00 -08003562 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003563 // increase sleep time progressively when application underrun condition clears.
3564 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3565 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3566 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003567 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003568 sleepTimeShift--;
3569 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003570 mSleepTimeUs = 0;
3571 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08003572 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003573
Eric Laurent81784c32012-11-19 14:55:58 -08003574}
3575
3576void AudioFlinger::MixerThread::threadLoop_sleepTime()
3577{
3578 // If no tracks are ready, sleep once for the duration of an output
3579 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003580 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003581 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003582 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
3583 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
3584 mSleepTimeUs = kMinThreadSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003585 }
3586 // reduce sleep time in case of consecutive application underruns to avoid
3587 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3588 // duration we would end up writing less data than needed by the audio HAL if
3589 // the condition persists.
3590 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3591 sleepTimeShift++;
3592 }
3593 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003594 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003595 }
3596 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003597 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3598 // before effects processing or output.
3599 if (mMixerBufferValid) {
3600 memset(mMixerBuffer, 0, mMixerBufferSize);
3601 } else {
3602 memset(mSinkBuffer, 0, mSinkBufferSize);
3603 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003604 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003605 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3606 "anticipated start");
3607 }
3608 // TODO add standby time extension fct of effect tail
3609}
3610
3611// prepareTracks_l() must be called with ThreadBase::mLock held
3612AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3613 Vector< sp<Track> > *tracksToRemove)
3614{
3615
3616 mixer_state mixerStatus = MIXER_IDLE;
3617 // find out which tracks need to be processed
3618 size_t count = mActiveTracks.size();
3619 size_t mixedTracks = 0;
3620 size_t tracksWithEffect = 0;
3621 // counts only _active_ fast tracks
3622 size_t fastTracks = 0;
3623 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
3624
3625 float masterVolume = mMasterVolume;
3626 bool masterMute = mMasterMute;
3627
3628 if (masterMute) {
3629 masterVolume = 0;
3630 }
3631 // Delegate master volume control to effect in output mix effect chain if needed
3632 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3633 if (chain != 0) {
3634 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
3635 chain->setVolume_l(&v, &v);
3636 masterVolume = (float)((v + (1 << 23)) >> 24);
3637 chain.clear();
3638 }
3639
3640 // prepare a new state to push
3641 FastMixerStateQueue *sq = NULL;
3642 FastMixerState *state = NULL;
3643 bool didModify = false;
3644 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003645 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003646 sq = mFastMixer->sq();
3647 state = sq->begin();
3648 }
3649
Andy Hung69aed5f2014-02-25 17:24:40 -08003650 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08003651 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08003652
Eric Laurent81784c32012-11-19 14:55:58 -08003653 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003654 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003655 if (t == 0) {
3656 continue;
3657 }
3658
3659 // this const just means the local variable doesn't change
3660 Track* const track = t.get();
3661
3662 // process fast tracks
3663 if (track->isFastTrack()) {
3664
3665 // It's theoretically possible (though unlikely) for a fast track to be created
3666 // and then removed within the same normal mix cycle. This is not a problem, as
3667 // the track never becomes active so it's fast mixer slot is never touched.
3668 // The converse, of removing an (active) track and then creating a new track
3669 // at the identical fast mixer slot within the same normal mix cycle,
3670 // is impossible because the slot isn't marked available until the end of each cycle.
3671 int j = track->mFastIndex;
3672 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
3673 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
3674 FastTrack *fastTrack = &state->mFastTracks[j];
3675
3676 // Determine whether the track is currently in underrun condition,
3677 // and whether it had a recent underrun.
3678 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
3679 FastTrackUnderruns underruns = ftDump->mUnderruns;
3680 uint32_t recentFull = (underruns.mBitFields.mFull -
3681 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
3682 uint32_t recentPartial = (underruns.mBitFields.mPartial -
3683 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
3684 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
3685 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
3686 uint32_t recentUnderruns = recentPartial + recentEmpty;
3687 track->mObservedUnderruns = underruns;
3688 // don't count underruns that occur while stopping or pausing
3689 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07003690 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
3691 recentUnderruns > 0) {
3692 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
3693 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003694 }
3695
3696 // This is similar to the state machine for normal tracks,
3697 // with a few modifications for fast tracks.
3698 bool isActive = true;
3699 switch (track->mState) {
3700 case TrackBase::STOPPING_1:
3701 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08003702 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003703 track->mState = TrackBase::STOPPING_2;
3704 }
3705 break;
3706 case TrackBase::PAUSING:
3707 // ramp down is not yet implemented
3708 track->setPaused();
3709 break;
3710 case TrackBase::RESUMING:
3711 // ramp up is not yet implemented
3712 track->mState = TrackBase::ACTIVE;
3713 break;
3714 case TrackBase::ACTIVE:
3715 if (recentFull > 0 || recentPartial > 0) {
3716 // track has provided at least some frames recently: reset retry count
3717 track->mRetryCount = kMaxTrackRetries;
3718 }
3719 if (recentUnderruns == 0) {
3720 // no recent underruns: stay active
3721 break;
3722 }
3723 // there has recently been an underrun of some kind
3724 if (track->sharedBuffer() == 0) {
3725 // were any of the recent underruns "empty" (no frames available)?
3726 if (recentEmpty == 0) {
3727 // no, then ignore the partial underruns as they are allowed indefinitely
3728 break;
3729 }
3730 // there has recently been an "empty" underrun: decrement the retry counter
3731 if (--(track->mRetryCount) > 0) {
3732 break;
3733 }
3734 // indicate to client process that the track was disabled because of underrun;
3735 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003736 android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003737 // remove from active list, but state remains ACTIVE [confusing but true]
3738 isActive = false;
3739 break;
3740 }
3741 // fall through
3742 case TrackBase::STOPPING_2:
3743 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003744 case TrackBase::STOPPED:
3745 case TrackBase::FLUSHED: // flush() while active
3746 // Check for presentation complete if track is inactive
3747 // We have consumed all the buffers of this track.
3748 // This would be incomplete if we auto-paused on underrun
3749 {
3750 size_t audioHALFrames =
3751 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3752 size_t framesWritten = mBytesWritten / mFrameSize;
3753 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
3754 // track stays in active list until presentation is complete
3755 break;
3756 }
3757 }
3758 if (track->isStopping_2()) {
3759 track->mState = TrackBase::STOPPED;
3760 }
3761 if (track->isStopped()) {
3762 // Can't reset directly, as fast mixer is still polling this track
3763 // track->reset();
3764 // So instead mark this track as needing to be reset after push with ack
3765 resetMask |= 1 << i;
3766 }
3767 isActive = false;
3768 break;
3769 case TrackBase::IDLE:
3770 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08003771 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08003772 }
3773
3774 if (isActive) {
3775 // was it previously inactive?
3776 if (!(state->mTrackMask & (1 << j))) {
3777 ExtendedAudioBufferProvider *eabp = track;
3778 VolumeProvider *vp = track;
3779 fastTrack->mBufferProvider = eabp;
3780 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08003781 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003782 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08003783 fastTrack->mGeneration++;
3784 state->mTrackMask |= 1 << j;
3785 didModify = true;
3786 // no acknowledgement required for newly active tracks
3787 }
3788 // cache the combined master volume and stream type volume for fast mixer; this
3789 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08003790 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08003791 ++fastTracks;
3792 } else {
3793 // was it previously active?
3794 if (state->mTrackMask & (1 << j)) {
3795 fastTrack->mBufferProvider = NULL;
3796 fastTrack->mGeneration++;
3797 state->mTrackMask &= ~(1 << j);
3798 didModify = true;
3799 // If any fast tracks were removed, we must wait for acknowledgement
3800 // because we're about to decrement the last sp<> on those tracks.
3801 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3802 } else {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003803 LOG_ALWAYS_FATAL("fast track %d should have been active", j);
Eric Laurent81784c32012-11-19 14:55:58 -08003804 }
3805 tracksToRemove->add(track);
3806 // Avoids a misleading display in dumpsys
3807 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
3808 }
3809 continue;
3810 }
3811
3812 { // local variable scope to avoid goto warning
3813
3814 audio_track_cblk_t* cblk = track->cblk();
3815
3816 // The first time a track is added we wait
3817 // for all its buffers to be filled before processing it
3818 int name = track->name();
3819 // make sure that we have enough frames to mix one full buffer.
3820 // enforce this condition only once to enable draining the buffer in case the client
3821 // app does not call stop() and relies on underrun to stop:
3822 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
3823 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003824 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07003825 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07003826 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07003827
3828 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07003829 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07003830 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
3831 // add frames already consumed but not yet released by the resampler
3832 // because mAudioTrackServerProxy->framesReady() will include these frames
3833 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
3834
Eric Laurent81784c32012-11-19 14:55:58 -08003835 uint32_t minFrames = 1;
3836 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
3837 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003838 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08003839 }
Eric Laurent13e4c962013-12-20 17:36:01 -08003840
3841 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07003842 if (ATRACE_ENABLED()) {
3843 // I wish we had formatted trace names
3844 char traceName[16];
3845 strcpy(traceName, "nRdy");
3846 int name = track->name();
3847 if (AudioMixer::TRACK0 <= name &&
3848 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
3849 name -= AudioMixer::TRACK0;
3850 traceName[4] = (name / 10) + '0';
3851 traceName[5] = (name % 10) + '0';
3852 } else {
3853 traceName[4] = '?';
3854 traceName[5] = '?';
3855 }
3856 traceName[6] = '\0';
3857 ATRACE_INT(traceName, framesReady);
3858 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003859 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08003860 !track->isPaused() && !track->isTerminated())
3861 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003862 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003863
3864 mixedTracks++;
3865
Andy Hung69aed5f2014-02-25 17:24:40 -08003866 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
3867 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08003868 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08003869 if (track->mainBuffer() != mSinkBuffer &&
3870 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08003871 if (mEffectBufferEnabled) {
3872 mEffectBufferValid = true; // Later can set directly.
3873 }
Eric Laurent81784c32012-11-19 14:55:58 -08003874 chain = getEffectChain_l(track->sessionId());
3875 // Delegate volume control to effect in track effect chain if needed
3876 if (chain != 0) {
3877 tracksWithEffect++;
3878 } else {
3879 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
3880 "session %d",
3881 name, track->sessionId());
3882 }
3883 }
3884
3885
3886 int param = AudioMixer::VOLUME;
3887 if (track->mFillingUpStatus == Track::FS_FILLED) {
3888 // no ramp for the first volume setting
3889 track->mFillingUpStatus = Track::FS_ACTIVE;
3890 if (track->mState == TrackBase::RESUMING) {
3891 track->mState = TrackBase::ACTIVE;
3892 param = AudioMixer::RAMP_VOLUME;
3893 }
3894 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003895 // FIXME should not make a decision based on mServer
3896 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003897 // If the track is stopped before the first frame was mixed,
3898 // do not apply ramp
3899 param = AudioMixer::RAMP_VOLUME;
3900 }
3901
3902 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07003903 uint32_t vl, vr; // in U8.24 integer format
3904 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08003905 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07003906 vl = vr = 0;
3907 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08003908 if (track->isPausing()) {
3909 track->setPaused();
3910 }
3911 } else {
3912
3913 // read original volumes with volume control
3914 float typeVolume = mStreamTypes[track->streamType()].volume;
3915 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003916 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07003917 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07003918 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
3919 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08003920 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07003921 if (vlf > GAIN_FLOAT_UNITY) {
3922 ALOGV("Track left volume out of range: %.3g", vlf);
3923 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003924 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07003925 if (vrf > GAIN_FLOAT_UNITY) {
3926 ALOGV("Track right volume out of range: %.3g", vrf);
3927 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003928 }
3929 // now apply the master volume and stream type volume
Andy Hung6be49402014-05-30 10:42:03 -07003930 vlf *= v;
3931 vrf *= v;
Eric Laurent81784c32012-11-19 14:55:58 -08003932 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07003933 // then derive vl and vr as U8.24 versions for the effect chain
3934 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
3935 vl = (uint32_t) (scaleto8_24 * vlf);
3936 vr = (uint32_t) (scaleto8_24 * vrf);
3937 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08003938 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08003939 // send level comes from shared memory and so may be corrupt
3940 if (sendLevel > MAX_GAIN_INT) {
3941 ALOGV("Track send level out of range: %04X", sendLevel);
3942 sendLevel = MAX_GAIN_INT;
3943 }
Andy Hung6be49402014-05-30 10:42:03 -07003944 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
3945 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08003946 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003947
Eric Laurent81784c32012-11-19 14:55:58 -08003948 // Delegate volume control to effect in track effect chain if needed
3949 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3950 // Do not ramp volume if volume is controlled by effect
3951 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08003952 // Update remaining floating point volume levels
3953 vlf = (float)vl / (1 << 24);
3954 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08003955 track->mHasVolumeController = true;
3956 } else {
3957 // force no volume ramp when volume controller was just disabled or removed
3958 // from effect chain to avoid volume spike
3959 if (track->mHasVolumeController) {
3960 param = AudioMixer::VOLUME;
3961 }
3962 track->mHasVolumeController = false;
3963 }
3964
Eric Laurent81784c32012-11-19 14:55:58 -08003965 // XXX: these things DON'T need to be done each time
3966 mAudioMixer->setBufferProvider(name, track);
3967 mAudioMixer->enable(name);
3968
Andy Hung6be49402014-05-30 10:42:03 -07003969 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
3970 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
3971 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08003972 mAudioMixer->setParameter(
3973 name,
3974 AudioMixer::TRACK,
3975 AudioMixer::FORMAT, (void *)track->format());
3976 mAudioMixer->setParameter(
3977 name,
3978 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003979 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07003980 mAudioMixer->setParameter(
3981 name,
3982 AudioMixer::TRACK,
3983 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08003984 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07003985 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003986 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08003987 if (reqSampleRate == 0) {
3988 reqSampleRate = mSampleRate;
3989 } else if (reqSampleRate > maxSampleRate) {
3990 reqSampleRate = maxSampleRate;
3991 }
Eric Laurent81784c32012-11-19 14:55:58 -08003992 mAudioMixer->setParameter(
3993 name,
3994 AudioMixer::RESAMPLE,
3995 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003996 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07003997
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07003998 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07003999 mAudioMixer->setParameter(
4000 name,
4001 AudioMixer::TIMESTRETCH,
4002 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004003 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004004
Andy Hung69aed5f2014-02-25 17:24:40 -08004005 /*
4006 * Select the appropriate output buffer for the track.
4007 *
Andy Hung98ef9782014-03-04 14:46:50 -08004008 * Tracks with effects go into their own effects chain buffer
4009 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08004010 *
4011 * Other tracks can use mMixerBuffer for higher precision
4012 * channel accumulation. If this buffer is enabled
4013 * (mMixerBufferEnabled true), then selected tracks will accumulate
4014 * into it.
4015 *
4016 */
4017 if (mMixerBufferEnabled
4018 && (track->mainBuffer() == mSinkBuffer
4019 || track->mainBuffer() == mMixerBuffer)) {
4020 mAudioMixer->setParameter(
4021 name,
4022 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004023 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08004024 mAudioMixer->setParameter(
4025 name,
4026 AudioMixer::TRACK,
4027 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
4028 // TODO: override track->mainBuffer()?
4029 mMixerBufferValid = true;
4030 } else {
4031 mAudioMixer->setParameter(
4032 name,
4033 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004034 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08004035 mAudioMixer->setParameter(
4036 name,
4037 AudioMixer::TRACK,
4038 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
4039 }
Eric Laurent81784c32012-11-19 14:55:58 -08004040 mAudioMixer->setParameter(
4041 name,
4042 AudioMixer::TRACK,
4043 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
4044
4045 // reset retry count
4046 track->mRetryCount = kMaxTrackRetries;
4047
4048 // If one track is ready, set the mixer ready if:
4049 // - the mixer was not ready during previous round OR
4050 // - no other track is not ready
4051 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
4052 mixerStatus != MIXER_TRACKS_ENABLED) {
4053 mixerStatus = MIXER_TRACKS_READY;
4054 }
4055 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004056 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hung08fb1742015-05-31 23:22:10 -07004057 ALOGV("track(%p) underrun, framesReady(%zu) < framesDesired(%zd)",
4058 track, framesReady, desiredFrames);
Glenn Kasten82aaf942013-07-17 16:05:07 -07004059 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004060 }
Eric Laurent81784c32012-11-19 14:55:58 -08004061 // clear effect chain input buffer if an active track underruns to avoid sending
4062 // previous audio buffer again to effects
4063 chain = getEffectChain_l(track->sessionId());
4064 if (chain != 0) {
4065 chain->clearInputBuffer();
4066 }
4067
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004068 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004069 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
4070 track->isStopped() || track->isPaused()) {
4071 // We have consumed all the buffers of this track.
4072 // Remove it from the list of active tracks.
4073 // TODO: use actual buffer filling status instead of latency when available from
4074 // audio HAL
4075 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
4076 size_t framesWritten = mBytesWritten / mFrameSize;
4077 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
4078 if (track->isStopped()) {
4079 track->reset();
4080 }
4081 tracksToRemove->add(track);
4082 }
4083 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08004084 // No buffers for this track. Give it a few chances to
4085 // fill a buffer, then remove it from active list.
4086 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004087 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004088 tracksToRemove->add(track);
4089 // indicate to client process that the track was disabled because of underrun;
4090 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07004091 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08004092 // If one track is not ready, mark the mixer also not ready if:
4093 // - the mixer was ready during previous round OR
4094 // - no other track is ready
4095 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
4096 mixerStatus != MIXER_TRACKS_READY) {
4097 mixerStatus = MIXER_TRACKS_ENABLED;
4098 }
4099 }
4100 mAudioMixer->disable(name);
4101 }
4102
4103 } // local variable scope to avoid goto warning
4104track_is_ready: ;
4105
4106 }
4107
4108 // Push the new FastMixer state if necessary
4109 bool pauseAudioWatchdog = false;
4110 if (didModify) {
4111 state->mFastTracksGen++;
4112 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4113 if (kUseFastMixer == FastMixer_Dynamic &&
4114 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4115 state->mCommand = FastMixerState::COLD_IDLE;
4116 state->mColdFutexAddr = &mFastMixerFutex;
4117 state->mColdGen++;
4118 mFastMixerFutex = 0;
4119 if (kUseFastMixer == FastMixer_Dynamic) {
4120 mNormalSink = mOutputSink;
4121 }
4122 // If we go into cold idle, need to wait for acknowledgement
4123 // so that fast mixer stops doing I/O.
4124 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4125 pauseAudioWatchdog = true;
4126 }
Eric Laurent81784c32012-11-19 14:55:58 -08004127 }
4128 if (sq != NULL) {
4129 sq->end(didModify);
4130 sq->push(block);
4131 }
4132#ifdef AUDIO_WATCHDOG
4133 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4134 mAudioWatchdog->pause();
4135 }
4136#endif
4137
4138 // Now perform the deferred reset on fast tracks that have stopped
4139 while (resetMask != 0) {
4140 size_t i = __builtin_ctz(resetMask);
4141 ALOG_ASSERT(i < count);
4142 resetMask &= ~(1 << i);
4143 sp<Track> t = mActiveTracks[i].promote();
4144 if (t == 0) {
4145 continue;
4146 }
4147 Track* track = t.get();
4148 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
4149 track->reset();
4150 }
4151
4152 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004153 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004154
Eric Laurent97d547d2014-09-02 14:45:53 -07004155 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
4156 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07004157 }
4158
4159 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07004160 // as long as there are effects we should clear the effects buffer, to avoid
4161 // passing a non-clean buffer to the effect chain
4162 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07004163 }
Andy Hung69aed5f2014-02-25 17:24:40 -08004164 // sink or mix buffer must be cleared if all tracks are connected to an
4165 // effect chain as in this case the mixer will not write to the sink or mix buffer
4166 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08004167 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4168 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08004169 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08004170 if (mMixerBufferValid) {
4171 memset(mMixerBuffer, 0, mMixerBufferSize);
4172 // TODO: In testing, mSinkBuffer below need not be cleared because
4173 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
4174 // after mixing.
4175 //
4176 // To enforce this guarantee:
4177 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4178 // (mixedTracks == 0 && fastTracks > 0))
4179 // must imply MIXER_TRACKS_READY.
4180 // Later, we may clear buffers regardless, and skip much of this logic.
4181 }
Andy Hung98ef9782014-03-04 14:46:50 -08004182 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07004183 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004184 }
4185
4186 // if any fast tracks, then status is ready
4187 mMixerStatusIgnoringFastTracks = mixerStatus;
4188 if (fastTracks > 0) {
4189 mixerStatus = MIXER_TRACKS_READY;
4190 }
4191 return mixerStatus;
4192}
4193
4194// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07004195int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
4196 audio_format_t format, int sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08004197{
Andy Hunge8a1ced2014-05-09 15:02:21 -07004198 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08004199}
4200
4201// deleteTrackName_l() must be called with ThreadBase::mLock held
4202void AudioFlinger::MixerThread::deleteTrackName_l(int name)
4203{
4204 ALOGV("remove track (%d) and delete from mixer", name);
4205 mAudioMixer->deleteTrackName(name);
4206}
4207
Eric Laurent10351942014-05-08 18:49:52 -07004208// checkForNewParameter_l() must be called with ThreadBase::mLock held
4209bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
4210 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004211{
Eric Laurent81784c32012-11-19 14:55:58 -08004212 bool reconfig = false;
4213
Eric Laurent10351942014-05-08 18:49:52 -07004214 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004215
Eric Laurent10351942014-05-08 18:49:52 -07004216 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
4217 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004218 if (mFastMixer != 0) {
Eric Laurent10351942014-05-08 18:49:52 -07004219 FastMixerStateQueue *sq = mFastMixer->sq();
4220 FastMixerState *state = sq->begin();
4221 if (!(state->mCommand & FastMixerState::IDLE)) {
4222 previousCommand = state->mCommand;
4223 state->mCommand = FastMixerState::HOT_IDLE;
4224 sq->end();
4225 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
4226 } else {
4227 sq->end(false /*didModify*/);
Eric Laurent81784c32012-11-19 14:55:58 -08004228 }
Eric Laurent10351942014-05-08 18:49:52 -07004229 }
Eric Laurent81784c32012-11-19 14:55:58 -08004230
Eric Laurent10351942014-05-08 18:49:52 -07004231 AudioParameter param = AudioParameter(keyValuePair);
4232 int value;
4233 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4234 reconfig = true;
4235 }
4236 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004237 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004238 status = BAD_VALUE;
4239 } else {
4240 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08004241 reconfig = true;
4242 }
Eric Laurent10351942014-05-08 18:49:52 -07004243 }
4244 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004245 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004246 status = BAD_VALUE;
4247 } else {
4248 // no need to save value, since it's constant
4249 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004250 }
Eric Laurent10351942014-05-08 18:49:52 -07004251 }
4252 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4253 // do not accept frame count changes if tracks are open as the track buffer
4254 // size depends on frame count and correct behavior would not be guaranteed
4255 // if frame count is changed after track creation
4256 if (!mTracks.isEmpty()) {
4257 status = INVALID_OPERATION;
4258 } else {
4259 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004260 }
Eric Laurent10351942014-05-08 18:49:52 -07004261 }
4262 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004263#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07004264 // when changing the audio output device, call addBatteryData to notify
4265 // the change
4266 if (mOutDevice != value) {
4267 uint32_t params = 0;
4268 // check whether speaker is on
4269 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
4270 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08004271 }
Eric Laurent10351942014-05-08 18:49:52 -07004272
4273 audio_devices_t deviceWithoutSpeaker
4274 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
4275 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07004276 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07004277 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4278 }
4279
4280 if (params != 0) {
4281 addBatteryData(params);
4282 }
4283 }
Eric Laurent81784c32012-11-19 14:55:58 -08004284#endif
4285
Eric Laurent10351942014-05-08 18:49:52 -07004286 // forward device change to effects that have requested to be
4287 // aware of attached audio device.
4288 if (value != AUDIO_DEVICE_NONE) {
4289 mOutDevice = value;
4290 for (size_t i = 0; i < mEffectChains.size(); i++) {
4291 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08004292 }
4293 }
Eric Laurent10351942014-05-08 18:49:52 -07004294 }
Eric Laurent81784c32012-11-19 14:55:58 -08004295
Eric Laurent10351942014-05-08 18:49:52 -07004296 if (status == NO_ERROR) {
4297 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4298 keyValuePair.string());
4299 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004300 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004301 mStandby = true;
4302 mBytesWritten = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004303 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Eric Laurent10351942014-05-08 18:49:52 -07004304 keyValuePair.string());
Eric Laurent81784c32012-11-19 14:55:58 -08004305 }
Eric Laurent10351942014-05-08 18:49:52 -07004306 if (status == NO_ERROR && reconfig) {
4307 readOutputParameters_l();
4308 delete mAudioMixer;
4309 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4310 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07004311 int name = getTrackName_l(mTracks[i]->mChannelMask,
4312 mTracks[i]->mFormat, mTracks[i]->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07004313 if (name < 0) {
4314 break;
4315 }
4316 mTracks[i]->mName = name;
4317 }
Eric Laurent73e26b62015-04-27 16:55:58 -07004318 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004319 }
Eric Laurent81784c32012-11-19 14:55:58 -08004320 }
4321
4322 if (!(previousCommand & FastMixerState::IDLE)) {
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004323 ALOG_ASSERT(mFastMixer != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08004324 FastMixerStateQueue *sq = mFastMixer->sq();
4325 FastMixerState *state = sq->begin();
4326 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
4327 state->mCommand = previousCommand;
4328 sq->end();
4329 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4330 }
4331
4332 return reconfig;
4333}
4334
4335
4336void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
4337{
4338 const size_t SIZE = 256;
4339 char buffer[SIZE];
4340 String8 result;
4341
4342 PlaybackThread::dumpInternals(fd, args);
4343
Elliott Hughes87cebad2014-05-22 10:14:43 -07004344 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Eric Laurent81784c32012-11-19 14:55:58 -08004345
4346 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten4182c4e2013-07-15 14:45:07 -07004347 const FastMixerDumpState copy(mFastMixerDumpState);
Eric Laurent81784c32012-11-19 14:55:58 -08004348 copy.dump(fd);
4349
4350#ifdef STATE_QUEUE_DUMP
4351 // Similar for state queue
4352 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4353 observerCopy.dump(fd);
4354 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4355 mutatorCopy.dump(fd);
4356#endif
4357
Glenn Kasten46909e72013-02-26 09:20:22 -08004358#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08004359 // Write the tee output to a .wav file
4360 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08004361#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004362
4363#ifdef AUDIO_WATCHDOG
4364 if (mAudioWatchdog != 0) {
4365 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4366 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4367 wdCopy.dump(fd);
4368 }
4369#endif
4370}
4371
4372uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4373{
4374 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4375}
4376
4377uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4378{
4379 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4380}
4381
4382void AudioFlinger::MixerThread::cacheParameters_l()
4383{
4384 PlaybackThread::cacheParameters_l();
4385
4386 // FIXME: Relaxed timing because of a certain device that can't meet latency
4387 // Should be reduced to 2x after the vendor fixes the driver issue
4388 // increase threshold again due to low power audio mode. The way this warning
4389 // threshold is calculated and its usefulness should be reconsidered anyway.
4390 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4391}
4392
4393// ----------------------------------------------------------------------------
4394
4395AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07004396 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device, bool systemReady)
4397 : PlaybackThread(audioFlinger, output, id, device, DIRECT, systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08004398 // mLeftVolFloat, mRightVolFloat
4399{
4400}
4401
Eric Laurentbfb1b832013-01-07 09:53:42 -08004402AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4403 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07004404 ThreadBase::type_t type, bool systemReady)
4405 : PlaybackThread(audioFlinger, output, id, device, type, systemReady)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004406 // mLeftVolFloat, mRightVolFloat
4407{
4408}
4409
Eric Laurent81784c32012-11-19 14:55:58 -08004410AudioFlinger::DirectOutputThread::~DirectOutputThread()
4411{
4412}
4413
Eric Laurentbfb1b832013-01-07 09:53:42 -08004414void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
4415{
4416 audio_track_cblk_t* cblk = track->cblk();
4417 float left, right;
4418
4419 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4420 left = right = 0;
4421 } else {
4422 float typeVolume = mStreamTypes[track->streamType()].volume;
4423 float v = mMasterVolume * typeVolume;
4424 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004425 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4426 left = float_from_gain(gain_minifloat_unpack_left(vlr));
4427 if (left > GAIN_FLOAT_UNITY) {
4428 left = GAIN_FLOAT_UNITY;
4429 }
4430 left *= v;
4431 right = float_from_gain(gain_minifloat_unpack_right(vlr));
4432 if (right > GAIN_FLOAT_UNITY) {
4433 right = GAIN_FLOAT_UNITY;
4434 }
4435 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004436 }
4437
4438 if (lastTrack) {
4439 if (left != mLeftVolFloat || right != mRightVolFloat) {
4440 mLeftVolFloat = left;
4441 mRightVolFloat = right;
4442
4443 // Convert volumes from float to 8.24
4444 uint32_t vl = (uint32_t)(left * (1 << 24));
4445 uint32_t vr = (uint32_t)(right * (1 << 24));
4446
4447 // Delegate volume control to effect in track effect chain if needed
4448 // only one effect chain can be present on DirectOutputThread, so if
4449 // there is one, the track is connected to it
4450 if (!mEffectChains.isEmpty()) {
4451 mEffectChains[0]->setVolume_l(&vl, &vr);
4452 left = (float)vl / (1 << 24);
4453 right = (float)vr / (1 << 24);
4454 }
4455 if (mOutput->stream->set_volume) {
4456 mOutput->stream->set_volume(mOutput->stream, left, right);
4457 }
4458 }
4459 }
4460}
4461
Phil Burk43b4dcc2015-06-09 16:53:44 -07004462void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
4463{
4464 sp<Track> previousTrack = mPreviousTrack.promote();
4465 sp<Track> latestTrack = mLatestActiveTrack.promote();
4466
4467 if (previousTrack != 0 && latestTrack != 0 &&
4468 (previousTrack->sessionId() != latestTrack->sessionId())) {
4469 mFlushPending = true;
4470 }
4471 PlaybackThread::onAddNewTrack_l();
4472}
Eric Laurentbfb1b832013-01-07 09:53:42 -08004473
Eric Laurent81784c32012-11-19 14:55:58 -08004474AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4475 Vector< sp<Track> > *tracksToRemove
4476)
4477{
Eric Laurentd595b7c2013-04-03 17:27:56 -07004478 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08004479 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004480 bool doHwPause = false;
4481 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004482
4483 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07004484 for (size_t i = 0; i < count; i++) {
4485 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08004486 // The track died recently
4487 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004488 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08004489 }
4490
Phil Burk43b4dcc2015-06-09 16:53:44 -07004491 if (t->isInvalid()) {
4492 ALOGW("An invalidated track shouldn't be in active list");
4493 tracksToRemove->add(t);
4494 continue;
4495 }
4496
Eric Laurent81784c32012-11-19 14:55:58 -08004497 Track* const track = t.get();
4498 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07004499 // Only consider last track started for volume and mixer state control.
4500 // In theory an older track could underrun and restart after the new one starts
4501 // but as we only care about the transition phase between two tracks on a
4502 // direct output, it is not a problem to ignore the underrun case.
4503 sp<Track> l = mLatestActiveTrack.promote();
4504 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08004505
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004506 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004507 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004508 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004509 doHwPause = true;
4510 mHwPaused = true;
4511 }
4512 tracksToRemove->add(track);
4513 } else if (track->isFlushPending()) {
4514 track->flushAck();
4515 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004516 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004517 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004518 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004519 track->resumeAck();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004520 if (last && mHwPaused) {
4521 doHwResume = true;
4522 mHwPaused = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004523 }
4524 }
4525
Eric Laurent81784c32012-11-19 14:55:58 -08004526 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08004527 // for all its buffers to be filled before processing it.
4528 // Allow draining the buffer in case the client
4529 // app does not call stop() and relies on underrun to stop:
4530 // hence the test on (track->mRetryCount > 1).
4531 // If retryCount<=1 then track is about to underrun and be removed.
Eric Laurent81784c32012-11-19 14:55:58 -08004532 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08004533 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
4534 && (track->mRetryCount > 1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004535 minFrames = mNormalFrameCount;
4536 } else {
4537 minFrames = 1;
4538 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004539
Eric Laurentab5cdba2014-06-09 17:22:27 -07004540 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4541 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08004542 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004543 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08004544
4545 if (track->mFillingUpStatus == Track::FS_FILLED) {
4546 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004547 // make sure processVolume_l() will apply new volume even if 0
4548 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004549 if (!mHwSupportsPause) {
4550 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08004551 }
4552 }
4553
4554 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004555 processVolume_l(track, last);
4556 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004557 sp<Track> previousTrack = mPreviousTrack.promote();
4558 if (previousTrack != 0) {
4559 if (track != previousTrack.get()) {
4560 // Flush any data still being written from last track
4561 mBytesRemaining = 0;
4562 // flush data already sent if changing audio session as audio
4563 // comes from a different source. Also invalidate previous track to force a
4564 // seek when resuming.
4565 if (previousTrack->sessionId() != track->sessionId()) {
4566 previousTrack->invalidate();
4567 }
4568 }
4569 }
4570 mPreviousTrack = track;
4571
Eric Laurentd595b7c2013-04-03 17:27:56 -07004572 // reset retry count
4573 track->mRetryCount = kMaxTrackRetriesDirect;
4574 mActiveTrack = t;
4575 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07004576 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004577 doHwResume = true;
4578 mHwPaused = false;
4579 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004580 }
Eric Laurent81784c32012-11-19 14:55:58 -08004581 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004582 // clear effect chain input buffer if the last active track started underruns
4583 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07004584 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004585 mEffectChains[0]->clearInputBuffer();
4586 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004587 if (track->isStopping_1()) {
4588 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07004589 if (last && mHwPaused) {
4590 doHwResume = true;
4591 mHwPaused = false;
4592 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004593 }
4594 if ((track->sharedBuffer() != 0) || track->isStopped() ||
4595 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004596 // We have consumed all the buffers of this track.
4597 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07004598 size_t audioHALFrames;
4599 if (audio_is_linear_pcm(mFormat)) {
4600 audioHALFrames = (latency_l() * mSampleRate) / 1000;
4601 } else {
4602 audioHALFrames = 0;
4603 }
4604
Eric Laurent81784c32012-11-19 14:55:58 -08004605 size_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07004606 if (mStandby || !last ||
4607 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004608 if (track->isStopping_2()) {
4609 track->mState = TrackBase::STOPPED;
4610 }
Eric Laurent81784c32012-11-19 14:55:58 -08004611 if (track->isStopped()) {
4612 track->reset();
4613 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004614 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08004615 }
4616 } else {
4617 // No buffers for this track. Give it a few chances to
4618 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07004619 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08004620 if (--(track->mRetryCount) <= 0) {
4621 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07004622 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004623 // indicate to client process that the track was disabled because of underrun;
4624 // it will then automatically call start() when data is available
4625 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004626 } else if (last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004627 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07004628 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004629 doHwPause = true;
4630 mHwPaused = true;
4631 }
Eric Laurent81784c32012-11-19 14:55:58 -08004632 }
4633 }
4634 }
4635 }
4636
Eric Laurentd1f69b02014-12-15 14:33:13 -08004637 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07004638 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004639 for (size_t i = 0; i < mTracks.size(); i++) {
4640 if (mTracks[i]->isFlushPending()) {
4641 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004642 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004643 }
4644 }
4645 }
4646
4647 // make sure the pause/flush/resume sequence is executed in the right order.
4648 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4649 // before flush and then resume HW. This can happen in case of pause/flush/resume
4650 // if resume is received before pause is executed.
4651 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07004652 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004653 mOutput->stream->pause(mOutput->stream);
4654 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004655 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004656 flushHw_l();
4657 }
4658 if (mHwSupportsPause && !mStandby && doHwResume) {
4659 mOutput->stream->resume(mOutput->stream);
4660 }
Eric Laurent81784c32012-11-19 14:55:58 -08004661 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004662 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004663
4664 return mixerStatus;
4665}
4666
4667void AudioFlinger::DirectOutputThread::threadLoop_mix()
4668{
Eric Laurent81784c32012-11-19 14:55:58 -08004669 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08004670 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004671 // output audio to hardware
4672 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07004673 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004674 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08004675 status_t status = mActiveTrack->getNextBuffer(&buffer);
4676 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08004677 memset(curBuf, 0, frameCount * mFrameSize);
4678 break;
4679 }
4680 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
4681 frameCount -= buffer.frameCount;
4682 curBuf += buffer.frameCount * mFrameSize;
4683 mActiveTrack->releaseBuffer(&buffer);
4684 }
Andy Hung2098f272014-02-27 14:00:06 -08004685 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004686 mSleepTimeUs = 0;
4687 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08004688 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004689}
4690
4691void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
4692{
Eric Laurentd1f69b02014-12-15 14:33:13 -08004693 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004694 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004695 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004696 return;
4697 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004698 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004699 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004700 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004701 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004702 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004703 }
4704 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08004705 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004706 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004707 }
4708}
4709
Eric Laurentd1f69b02014-12-15 14:33:13 -08004710void AudioFlinger::DirectOutputThread::threadLoop_exit()
4711{
4712 {
4713 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08004714 for (size_t i = 0; i < mTracks.size(); i++) {
4715 if (mTracks[i]->isFlushPending()) {
4716 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004717 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004718 }
4719 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004720 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004721 flushHw_l();
4722 }
4723 }
4724 PlaybackThread::threadLoop_exit();
4725}
4726
4727// must be called with thread mutex locked
4728bool AudioFlinger::DirectOutputThread::shouldStandby_l()
4729{
4730 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07004731 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004732
4733 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4734 // after a timeout and we will enter standby then.
4735 if (mTracks.size() > 0) {
4736 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07004737 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
4738 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004739 }
4740
Eric Laurent5cff4032015-05-26 13:49:58 -07004741 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08004742}
4743
Eric Laurent81784c32012-11-19 14:55:58 -08004744// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004745int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Andy Hunge8a1ced2014-05-09 15:02:21 -07004746 audio_format_t format __unused, int sessionId __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004747{
4748 return 0;
4749}
4750
4751// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004752void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004753{
4754}
4755
Eric Laurent10351942014-05-08 18:49:52 -07004756// checkForNewParameter_l() must be called with ThreadBase::mLock held
4757bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
4758 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004759{
4760 bool reconfig = false;
4761
Eric Laurent10351942014-05-08 18:49:52 -07004762 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004763
Eric Laurent10351942014-05-08 18:49:52 -07004764 AudioParameter param = AudioParameter(keyValuePair);
4765 int value;
4766 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4767 // forward device change to effects that have requested to be
4768 // aware of attached audio device.
4769 if (value != AUDIO_DEVICE_NONE) {
4770 mOutDevice = value;
4771 for (size_t i = 0; i < mEffectChains.size(); i++) {
4772 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07004773 }
4774 }
Eric Laurent81784c32012-11-19 14:55:58 -08004775 }
Eric Laurent10351942014-05-08 18:49:52 -07004776 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4777 // do not accept frame count changes if tracks are open as the track buffer
4778 // size depends on frame count and correct behavior would not be garantied
4779 // if frame count is changed after track creation
4780 if (!mTracks.isEmpty()) {
4781 status = INVALID_OPERATION;
4782 } else {
4783 reconfig = true;
4784 }
4785 }
4786 if (status == NO_ERROR) {
4787 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4788 keyValuePair.string());
4789 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004790 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004791 mStandby = true;
4792 mBytesWritten = 0;
4793 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4794 keyValuePair.string());
4795 }
4796 if (status == NO_ERROR && reconfig) {
4797 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07004798 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004799 }
4800 }
4801
Eric Laurent81784c32012-11-19 14:55:58 -08004802 return reconfig;
4803}
4804
4805uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
4806{
4807 uint32_t time;
4808 if (audio_is_linear_pcm(mFormat)) {
4809 time = PlaybackThread::activeSleepTimeUs();
4810 } else {
4811 time = 10000;
4812 }
4813 return time;
4814}
4815
4816uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
4817{
4818 uint32_t time;
4819 if (audio_is_linear_pcm(mFormat)) {
4820 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
4821 } else {
4822 time = 10000;
4823 }
4824 return time;
4825}
4826
4827uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
4828{
4829 uint32_t time;
4830 if (audio_is_linear_pcm(mFormat)) {
4831 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
4832 } else {
4833 time = 10000;
4834 }
4835 return time;
4836}
4837
4838void AudioFlinger::DirectOutputThread::cacheParameters_l()
4839{
4840 PlaybackThread::cacheParameters_l();
4841
4842 // use shorter standby delay as on normal output to release
4843 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07004844 // no delay on outputs with HW A/V sync
4845 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004846 mStandbyDelayNs = 0;
Eric Laurent5cff4032015-05-26 13:49:58 -07004847 } else if ((mType == OFFLOAD) && !audio_is_linear_pcm(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004848 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07004849 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004850 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07004851 }
Eric Laurent81784c32012-11-19 14:55:58 -08004852}
4853
Eric Laurente659ef42014-09-29 13:06:46 -07004854void AudioFlinger::DirectOutputThread::flushHw_l()
4855{
Phil Burk062e67a2015-02-11 13:40:50 -08004856 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08004857 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07004858 mFlushPending = false;
Eric Laurente659ef42014-09-29 13:06:46 -07004859}
4860
Eric Laurent81784c32012-11-19 14:55:58 -08004861// ----------------------------------------------------------------------------
4862
Eric Laurentbfb1b832013-01-07 09:53:42 -08004863AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07004864 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004865 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07004866 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07004867 mWriteAckSequence(0),
4868 mDrainSequence(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004869{
4870}
4871
4872AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
4873{
4874}
4875
4876void AudioFlinger::AsyncCallbackThread::onFirstRef()
4877{
4878 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
4879}
4880
4881bool AudioFlinger::AsyncCallbackThread::threadLoop()
4882{
4883 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004884 uint32_t writeAckSequence;
4885 uint32_t drainSequence;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004886
4887 {
4888 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08004889 while (!((mWriteAckSequence & 1) ||
4890 (mDrainSequence & 1) ||
4891 exitPending())) {
4892 mWaitWorkCV.wait(mLock);
4893 }
4894
Eric Laurentbfb1b832013-01-07 09:53:42 -08004895 if (exitPending()) {
4896 break;
4897 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004898 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
4899 mWriteAckSequence, mDrainSequence);
4900 writeAckSequence = mWriteAckSequence;
4901 mWriteAckSequence &= ~1;
4902 drainSequence = mDrainSequence;
4903 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004904 }
4905 {
Eric Laurent4de95592013-09-26 15:28:21 -07004906 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
4907 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004908 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004909 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004910 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004911 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004912 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004913 }
4914 }
4915 }
4916 }
4917 return false;
4918}
4919
4920void AudioFlinger::AsyncCallbackThread::exit()
4921{
4922 ALOGV("AsyncCallbackThread::exit");
4923 Mutex::Autolock _l(mLock);
4924 requestExit();
4925 mWaitWorkCV.broadcast();
4926}
4927
Eric Laurent3b4529e2013-09-05 18:09:19 -07004928void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004929{
4930 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004931 // bit 0 is cleared
4932 mWriteAckSequence = sequence << 1;
4933}
4934
4935void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
4936{
4937 Mutex::Autolock _l(mLock);
4938 // ignore unexpected callbacks
4939 if (mWriteAckSequence & 2) {
4940 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004941 mWaitWorkCV.signal();
4942 }
4943}
4944
Eric Laurent3b4529e2013-09-05 18:09:19 -07004945void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004946{
4947 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004948 // bit 0 is cleared
4949 mDrainSequence = sequence << 1;
4950}
4951
4952void AudioFlinger::AsyncCallbackThread::resetDraining()
4953{
4954 Mutex::Autolock _l(mLock);
4955 // ignore unexpected callbacks
4956 if (mDrainSequence & 2) {
4957 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004958 mWaitWorkCV.signal();
4959 }
4960}
4961
4962
4963// ----------------------------------------------------------------------------
4964AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07004965 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady)
4966 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady),
Eric Laurentd7e59222013-11-15 12:02:28 -08004967 mPausedBytesRemaining(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004968{
Eric Laurentfd477972013-10-25 18:10:40 -07004969 //FIXME: mStandby should be set to true by ThreadBase constructor
4970 mStandby = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004971}
4972
Eric Laurentbfb1b832013-01-07 09:53:42 -08004973void AudioFlinger::OffloadThread::threadLoop_exit()
4974{
4975 if (mFlushPending || mHwPaused) {
4976 // If a flush is pending or track was paused, just discard buffered data
4977 flushHw_l();
4978 } else {
4979 mMixerStatus = MIXER_DRAIN_ALL;
4980 threadLoop_drain();
4981 }
Uday Gupta56604aa2014-05-13 11:19:17 -07004982 if (mUseAsyncWrite) {
4983 ALOG_ASSERT(mCallbackThread != 0);
4984 mCallbackThread->exit();
4985 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004986 PlaybackThread::threadLoop_exit();
4987}
4988
4989AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
4990 Vector< sp<Track> > *tracksToRemove
4991)
4992{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004993 size_t count = mActiveTracks.size();
4994
4995 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07004996 bool doHwPause = false;
4997 bool doHwResume = false;
4998
Eric Laurentede6c3b2013-09-19 14:37:46 -07004999 ALOGV("OffloadThread::prepareTracks_l active tracks %d", count);
5000
Eric Laurentbfb1b832013-01-07 09:53:42 -08005001 // find out which tracks need to be processed
5002 for (size_t i = 0; i < count; i++) {
5003 sp<Track> t = mActiveTracks[i].promote();
5004 // The track died recently
5005 if (t == 0) {
5006 continue;
5007 }
5008 Track* const track = t.get();
5009 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07005010 // Only consider last track started for volume and mixer state control.
5011 // In theory an older track could underrun and restart after the new one starts
5012 // but as we only care about the transition phase between two tracks on a
5013 // direct output, it is not a problem to ignore the underrun case.
5014 sp<Track> l = mLatestActiveTrack.promote();
5015 bool last = l.get() == track;
5016
Haynes Mathew George7844f672014-01-15 12:32:55 -08005017 if (track->isInvalid()) {
5018 ALOGW("An invalidated track shouldn't be in active list");
5019 tracksToRemove->add(track);
5020 continue;
5021 }
5022
5023 if (track->mState == TrackBase::IDLE) {
5024 ALOGW("An idle track shouldn't be in active list");
5025 continue;
5026 }
5027
Eric Laurentbfb1b832013-01-07 09:53:42 -08005028 if (track->isPausing()) {
5029 track->setPaused();
5030 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07005031 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07005032 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005033 mHwPaused = true;
5034 }
5035 // If we were part way through writing the mixbuffer to
5036 // the HAL we must save this until we resume
5037 // BUG - this will be wrong if a different track is made active,
5038 // in that case we want to discard the pending data in the
5039 // mixbuffer and tell the client to present it again when the
5040 // track is resumed
5041 mPausedWriteLength = mCurrentWriteLength;
5042 mPausedBytesRemaining = mBytesRemaining;
5043 mBytesRemaining = 0; // stop writing
5044 }
5045 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08005046 } else if (track->isFlushPending()) {
5047 track->flushAck();
5048 if (last) {
5049 mFlushPending = true;
5050 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005051 } else if (track->isResumePending()){
5052 track->resumeAck();
5053 if (last) {
5054 if (mPausedBytesRemaining) {
5055 // Need to continue write that was interrupted
5056 mCurrentWriteLength = mPausedWriteLength;
5057 mBytesRemaining = mPausedBytesRemaining;
5058 mPausedBytesRemaining = 0;
5059 }
5060 if (mHwPaused) {
5061 doHwResume = true;
5062 mHwPaused = false;
5063 // threadLoop_mix() will handle the case that we need to
5064 // resume an interrupted write
5065 }
5066 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005067 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005068
5069 // Do not handle new data in this iteration even if track->framesReady()
5070 mixerStatus = MIXER_TRACKS_ENABLED;
5071 }
5072 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07005073 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005074 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005075 if (track->mFillingUpStatus == Track::FS_FILLED) {
5076 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07005077 // make sure processVolume_l() will apply new volume even if 0
5078 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005079 }
5080
5081 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08005082 sp<Track> previousTrack = mPreviousTrack.promote();
5083 if (previousTrack != 0) {
5084 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08005085 // Flush any data still being written from last track
5086 mBytesRemaining = 0;
5087 if (mPausedBytesRemaining) {
5088 // Last track was paused so we also need to flush saved
5089 // mixbuffer state and invalidate track so that it will
5090 // re-submit that unwritten data when it is next resumed
5091 mPausedBytesRemaining = 0;
5092 // Invalidate is a bit drastic - would be more efficient
5093 // to have a flag to tell client that some of the
5094 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08005095 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005096 }
5097 // flush data already sent to the DSP if changing audio session as audio
5098 // comes from a different source. Also invalidate previous track to force a
5099 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08005100 if (previousTrack->sessionId() != track->sessionId()) {
5101 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005102 }
5103 }
5104 }
5105 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005106 // reset retry count
5107 track->mRetryCount = kMaxTrackRetriesOffload;
5108 mActiveTrack = t;
5109 mixerStatus = MIXER_TRACKS_READY;
5110 }
5111 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005112 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005113 if (track->isStopping_1()) {
5114 // Hardware buffer can hold a large amount of audio so we must
5115 // wait for all current track's data to drain before we say
5116 // that the track is stopped.
5117 if (mBytesRemaining == 0) {
5118 // Only start draining when all data in mixbuffer
5119 // has been written
5120 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
5121 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005122 // do not drain if no data was ever sent to HAL (mStandby == true)
5123 if (last && !mStandby) {
Eric Laurent1b9f9b12013-11-12 19:10:17 -08005124 // do not modify drain sequence if we are already draining. This happens
5125 // when resuming from pause after drain.
5126 if ((mDrainSequence & 1) == 0) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005127 mSleepTimeUs = 0;
5128 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent1b9f9b12013-11-12 19:10:17 -08005129 mixerStatus = MIXER_DRAIN_TRACK;
5130 mDrainSequence += 2;
5131 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005132 if (mHwPaused) {
5133 // It is possible to move from PAUSED to STOPPING_1 without
5134 // a resume so we must ensure hardware is running
Eric Laurent1b9f9b12013-11-12 19:10:17 -08005135 doHwResume = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005136 mHwPaused = false;
5137 }
5138 }
5139 }
5140 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005141 // Drain has completed or we are in standby, signal presentation complete
5142 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005143 track->mState = TrackBase::STOPPED;
5144 size_t audioHALFrames =
5145 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
5146 size_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08005147 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005148 track->presentationComplete(framesWritten, audioHALFrames);
5149 track->reset();
5150 tracksToRemove->add(track);
5151 }
5152 } else {
5153 // No buffers for this track. Give it a few chances to
5154 // fill a buffer, then remove it from active list.
5155 if (--(track->mRetryCount) <= 0) {
5156 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
5157 track->name());
5158 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08005159 // indicate to client process that the track was disabled because of underrun;
5160 // it will then automatically call start() when data is available
5161 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005162 } else if (last){
5163 mixerStatus = MIXER_TRACKS_ENABLED;
5164 }
5165 }
5166 }
5167 // compute volume for this track
5168 processVolume_l(track, last);
5169 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005170
Eric Laurentea0fade2013-10-04 16:23:48 -07005171 // make sure the pause/flush/resume sequence is executed in the right order.
5172 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5173 // before flush and then resume HW. This can happen in case of pause/flush/resume
5174 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07005175 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurent972a1732013-09-04 09:42:59 -07005176 mOutput->stream->pause(mOutput->stream);
5177 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005178 if (mFlushPending) {
5179 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005180 }
Eric Laurentfd477972013-10-25 18:10:40 -07005181 if (!mStandby && doHwResume) {
Eric Laurent972a1732013-09-04 09:42:59 -07005182 mOutput->stream->resume(mOutput->stream);
5183 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005184
Eric Laurentbfb1b832013-01-07 09:53:42 -08005185 // remove all the tracks that need to be...
5186 removeTracks_l(*tracksToRemove);
5187
5188 return mixerStatus;
5189}
5190
Eric Laurentbfb1b832013-01-07 09:53:42 -08005191// must be called with thread mutex locked
5192bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
5193{
Eric Laurent3b4529e2013-09-05 18:09:19 -07005194 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
5195 mWriteAckSequence, mDrainSequence);
5196 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005197 return true;
5198 }
5199 return false;
5200}
5201
Eric Laurentbfb1b832013-01-07 09:53:42 -08005202bool AudioFlinger::OffloadThread::waitingAsyncCallback()
5203{
5204 Mutex::Autolock _l(mLock);
5205 return waitingAsyncCallback_l();
5206}
5207
5208void AudioFlinger::OffloadThread::flushHw_l()
5209{
Eric Laurente659ef42014-09-29 13:06:46 -07005210 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005211 // Flush anything still waiting in the mixbuffer
5212 mCurrentWriteLength = 0;
5213 mBytesRemaining = 0;
5214 mPausedWriteLength = 0;
5215 mPausedBytesRemaining = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08005216
Eric Laurentbfb1b832013-01-07 09:53:42 -08005217 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005218 // discard any pending drain or write ack by incrementing sequence
5219 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5220 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005221 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005222 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5223 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005224 }
5225}
5226
5227// ----------------------------------------------------------------------------
5228
Eric Laurent81784c32012-11-19 14:55:58 -08005229AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07005230 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08005231 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
Eric Laurent72e3f392015-05-20 14:43:50 -07005232 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08005233 mWaitTimeMs(UINT_MAX)
5234{
5235 addOutputTrack(mainThread);
5236}
5237
5238AudioFlinger::DuplicatingThread::~DuplicatingThread()
5239{
5240 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5241 mOutputTracks[i]->destroy();
5242 }
5243}
5244
5245void AudioFlinger::DuplicatingThread::threadLoop_mix()
5246{
5247 // mix buffers...
5248 if (outputsReady(outputTracks)) {
5249 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
5250 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08005251 if (mMixerBufferValid) {
5252 memset(mMixerBuffer, 0, mMixerBufferSize);
5253 } else {
5254 memset(mSinkBuffer, 0, mSinkBufferSize);
5255 }
Eric Laurent81784c32012-11-19 14:55:58 -08005256 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005257 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005258 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005259 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005260 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005261}
5262
5263void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
5264{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005265 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005266 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005267 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005268 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005269 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005270 }
5271 } else if (mBytesWritten != 0) {
5272 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5273 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005274 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005275 } else {
5276 // flush remaining overflow buffers in output tracks
5277 writeFrames = 0;
5278 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005279 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005280 }
5281}
5282
Eric Laurentbfb1b832013-01-07 09:53:42 -08005283ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005284{
5285 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08005286 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005287 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07005288 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08005289 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005290}
5291
5292void AudioFlinger::DuplicatingThread::threadLoop_standby()
5293{
5294 // DuplicatingThread implements standby by stopping all tracks
5295 for (size_t i = 0; i < outputTracks.size(); i++) {
5296 outputTracks[i]->stop();
5297 }
5298}
5299
5300void AudioFlinger::DuplicatingThread::saveOutputTracks()
5301{
5302 outputTracks = mOutputTracks;
5303}
5304
5305void AudioFlinger::DuplicatingThread::clearOutputTracks()
5306{
5307 outputTracks.clear();
5308}
5309
5310void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
5311{
5312 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08005313 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
5314 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
5315 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
5316 const size_t frameCount =
5317 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
5318 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
5319 // from different OutputTracks and their associated MixerThreads (e.g. one may
5320 // nearly empty and the other may be dropping data).
5321
5322 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08005323 this,
5324 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08005325 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08005326 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005327 frameCount,
5328 IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08005329 if (outputTrack->cblk() != NULL) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005330 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
Eric Laurent81784c32012-11-19 14:55:58 -08005331 mOutputTracks.add(outputTrack);
Andy Hungc25b84a2015-01-14 19:04:10 -08005332 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005333 updateWaitTime_l();
5334 }
5335}
5336
5337void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
5338{
5339 Mutex::Autolock _l(mLock);
5340 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5341 if (mOutputTracks[i]->thread() == thread) {
5342 mOutputTracks[i]->destroy();
5343 mOutputTracks.removeAt(i);
5344 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07005345 if (thread->getOutput() == mOutput) {
5346 mOutput = NULL;
5347 }
Eric Laurent81784c32012-11-19 14:55:58 -08005348 return;
5349 }
5350 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07005351 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005352}
5353
5354// caller must hold mLock
5355void AudioFlinger::DuplicatingThread::updateWaitTime_l()
5356{
5357 mWaitTimeMs = UINT_MAX;
5358 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5359 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
5360 if (strong != 0) {
5361 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
5362 if (waitTimeMs < mWaitTimeMs) {
5363 mWaitTimeMs = waitTimeMs;
5364 }
5365 }
5366 }
5367}
5368
5369
5370bool AudioFlinger::DuplicatingThread::outputsReady(
5371 const SortedVector< sp<OutputTrack> > &outputTracks)
5372{
5373 for (size_t i = 0; i < outputTracks.size(); i++) {
5374 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
5375 if (thread == 0) {
5376 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
5377 outputTracks[i].get());
5378 return false;
5379 }
5380 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5381 // see note at standby() declaration
5382 if (playbackThread->standby() && !playbackThread->isSuspended()) {
5383 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
5384 thread.get());
5385 return false;
5386 }
5387 }
5388 return true;
5389}
5390
5391uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
5392{
5393 return (mWaitTimeMs * 1000) / 2;
5394}
5395
5396void AudioFlinger::DuplicatingThread::cacheParameters_l()
5397{
5398 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
5399 updateWaitTime_l();
5400
5401 MixerThread::cacheParameters_l();
5402}
5403
5404// ----------------------------------------------------------------------------
5405// Record
5406// ----------------------------------------------------------------------------
5407
5408AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5409 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08005410 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08005411 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07005412 audio_devices_t inDevice,
5413 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08005414#ifdef TEE_SINK
5415 , const sp<NBAIO_Sink>& teeSink
5416#endif
5417 ) :
Eric Laurent72e3f392015-05-20 14:43:50 -07005418 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005419 mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005420 // mRsmpInFrames and mRsmpInFramesP2 are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005421 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08005422#ifdef TEE_SINK
5423 , mTeeSink(teeSink)
5424#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07005425 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
5426 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005427 // mFastCapture below
5428 , mFastCaptureFutex(0)
5429 // mInputSource
5430 // mPipeSink
5431 // mPipeSource
5432 , mPipeFramesP2(0)
5433 // mPipeMemory
5434 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005435 , mFastTrackAvail(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005436{
Glenn Kastend7dca052015-03-05 16:05:54 -08005437 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
5438 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08005439
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005440 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005441
5442 // create an NBAIO source for the HAL input stream, and negotiate
5443 mInputSource = new AudioStreamInSource(input->stream);
5444 size_t numCounterOffers = 0;
5445 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
5446 ssize_t index = mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
5447 ALOG_ASSERT(index == 0);
5448
5449 // initialize fast capture depending on configuration
5450 bool initFastCapture;
5451 switch (kUseFastCapture) {
5452 case FastCapture_Never:
5453 initFastCapture = false;
5454 break;
5455 case FastCapture_Always:
5456 initFastCapture = true;
5457 break;
5458 case FastCapture_Static:
5459 uint32_t primaryOutputSampleRate;
5460 {
5461 AutoMutex _l(audioFlinger->mHardwareLock);
5462 primaryOutputSampleRate = audioFlinger->mPrimaryOutputSampleRate;
5463 }
5464 initFastCapture =
5465 // either capture sample rate is same as (a reasonable) primary output sample rate
Andy Hungdb4c0312015-05-06 08:46:52 -07005466 ((isMusicRate(primaryOutputSampleRate) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005467 (mSampleRate == primaryOutputSampleRate)) ||
5468 // or primary output sample rate is unknown, and capture sample rate is reasonable
5469 ((primaryOutputSampleRate == 0) &&
Andy Hungdb4c0312015-05-06 08:46:52 -07005470 isMusicRate(mSampleRate))) &&
Glenn Kasten9f81de32014-07-27 15:02:23 -07005471 // and the buffer size is < 12 ms
5472 (mFrameCount * 1000) / mSampleRate < 12;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005473 break;
5474 // case FastCapture_Dynamic:
5475 }
5476
5477 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07005478 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005479 NBAIO_Format format = mInputSource->format();
Glenn Kasten49d00ad2014-07-21 11:22:03 -07005480 size_t pipeFramesP2 = roundup(mSampleRate / 25); // double-buffering of 20 ms each
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005481 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
5482 void *pipeBuffer;
5483 const sp<MemoryDealer> roHeap(readOnlyHeap());
5484 sp<IMemory> pipeMemory;
5485 if ((roHeap == 0) ||
5486 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
5487 (pipeBuffer = pipeMemory->pointer()) == NULL) {
5488 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
5489 goto failed;
5490 }
5491 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
5492 memset(pipeBuffer, 0, pipeSize);
5493 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
5494 const NBAIO_Format offers[1] = {format};
5495 size_t numCounterOffers = 0;
5496 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
5497 ALOG_ASSERT(index == 0);
5498 mPipeSink = pipe;
5499 PipeReader *pipeReader = new PipeReader(*pipe);
5500 numCounterOffers = 0;
5501 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
5502 ALOG_ASSERT(index == 0);
5503 mPipeSource = pipeReader;
5504 mPipeFramesP2 = pipeFramesP2;
5505 mPipeMemory = pipeMemory;
5506
5507 // create fast capture
5508 mFastCapture = new FastCapture();
5509 FastCaptureStateQueue *sq = mFastCapture->sq();
5510#ifdef STATE_QUEUE_DUMP
5511 // FIXME
5512#endif
5513 FastCaptureState *state = sq->begin();
5514 state->mCblk = NULL;
5515 state->mInputSource = mInputSource.get();
5516 state->mInputSourceGen++;
5517 state->mPipeSink = pipe;
5518 state->mPipeSinkGen++;
5519 state->mFrameCount = mFrameCount;
5520 state->mCommand = FastCaptureState::COLD_IDLE;
5521 // already done in constructor initialization list
5522 //mFastCaptureFutex = 0;
5523 state->mColdFutexAddr = &mFastCaptureFutex;
5524 state->mColdGen++;
5525 state->mDumpState = &mFastCaptureDumpState;
5526#ifdef TEE_SINK
5527 // FIXME
5528#endif
5529 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
5530 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
5531 sq->end();
5532 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5533
5534 // start the fast capture
5535 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
5536 pid_t tid = mFastCapture->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07005537 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005538#ifdef AUDIO_WATCHDOG
5539 // FIXME
5540#endif
5541
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005542 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005543 }
5544failed: ;
5545
5546 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08005547}
5548
Eric Laurent81784c32012-11-19 14:55:58 -08005549AudioFlinger::RecordThread::~RecordThread()
5550{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005551 if (mFastCapture != 0) {
5552 FastCaptureStateQueue *sq = mFastCapture->sq();
5553 FastCaptureState *state = sq->begin();
5554 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5555 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5556 if (old == -1) {
5557 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5558 }
5559 }
5560 state->mCommand = FastCaptureState::EXIT;
5561 sq->end();
5562 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5563 mFastCapture->join();
5564 mFastCapture.clear();
5565 }
5566 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07005567 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07005568 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08005569}
5570
5571void AudioFlinger::RecordThread::onFirstRef()
5572{
Glenn Kastend7dca052015-03-05 16:05:54 -08005573 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08005574}
5575
Eric Laurent81784c32012-11-19 14:55:58 -08005576bool AudioFlinger::RecordThread::threadLoop()
5577{
Eric Laurent81784c32012-11-19 14:55:58 -08005578 nsecs_t lastWarning = 0;
5579
5580 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08005581
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005582reacquire_wakelock:
5583 sp<RecordTrack> activeTrack;
Glenn Kasten2b806402013-11-20 16:37:38 -08005584 int activeTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005585 {
5586 Mutex::Autolock _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005587 size_t size = mActiveTracks.size();
5588 activeTracksGen = mActiveTracksGen;
5589 if (size > 0) {
5590 // FIXME an arbitrary choice
5591 activeTrack = mActiveTracks[0];
5592 acquireWakeLock_l(activeTrack->uid());
5593 if (size > 1) {
5594 SortedVector<int> tmp;
5595 for (size_t i = 0; i < size; i++) {
5596 tmp.add(mActiveTracks[i]->uid());
5597 }
5598 updateWakeLockUids_l(tmp);
5599 }
5600 } else {
5601 acquireWakeLock_l(-1);
5602 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005603 }
5604
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005605 // used to request a deferred sleep, to be executed later while mutex is unlocked
5606 uint32_t sleepUs = 0;
5607
5608 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005609 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005610 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07005611
Glenn Kasten5edadd42013-08-14 16:30:49 -07005612 // sleep with mutex unlocked
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005613 if (sleepUs > 0) {
Glenn Kastene7754022014-10-31 12:11:26 -07005614 ATRACE_BEGIN("sleep");
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005615 usleep(sleepUs);
Glenn Kastene7754022014-10-31 12:11:26 -07005616 ATRACE_END();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005617 sleepUs = 0;
Glenn Kasten5edadd42013-08-14 16:30:49 -07005618 }
5619
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005620 // activeTracks accumulates a copy of a subset of mActiveTracks
5621 Vector< sp<RecordTrack> > activeTracks;
5622
Glenn Kasten735f45f2014-08-18 15:51:59 -07005623 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005624 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07005625
Glenn Kasten735f45f2014-08-18 15:51:59 -07005626 // reference to a fast track which is about to be removed
5627 sp<RecordTrack> fastTrackToRemove;
5628
Eric Laurent81784c32012-11-19 14:55:58 -08005629 { // scope for mLock
5630 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08005631
Eric Laurent021cf962014-05-13 10:18:14 -07005632 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005633
Eric Laurent000a4192014-01-29 15:17:32 -08005634 // check exitPending here because checkForNewParameters_l() and
5635 // checkForNewParameters_l() can temporarily release mLock
5636 if (exitPending()) {
5637 break;
5638 }
5639
Glenn Kasten2b806402013-11-20 16:37:38 -08005640 // if no active track(s), then standby and release wakelock
5641 size_t size = mActiveTracks.size();
5642 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07005643 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005644 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08005645 releaseWakeLock_l();
5646 ALOGV("RecordThread: loop stopping");
5647 // go to sleep
5648 mWaitWorkCV.wait(mLock);
5649 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005650 goto reacquire_wakelock;
5651 }
5652
Glenn Kasten2b806402013-11-20 16:37:38 -08005653 if (mActiveTracksGen != activeTracksGen) {
5654 activeTracksGen = mActiveTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005655 SortedVector<int> tmp;
Glenn Kasten2b806402013-11-20 16:37:38 -08005656 for (size_t i = 0; i < size; i++) {
5657 tmp.add(mActiveTracks[i]->uid());
5658 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005659 updateWakeLockUids_l(tmp);
Eric Laurent81784c32012-11-19 14:55:58 -08005660 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005661
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005662 bool doBroadcast = false;
5663 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07005664
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005665 activeTrack = mActiveTracks[i];
5666 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07005667 if (activeTrack->isFastTrack()) {
5668 ALOG_ASSERT(fastTrackToRemove == 0);
5669 fastTrackToRemove = activeTrack;
5670 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005671 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08005672 mActiveTracks.remove(activeTrack);
5673 mActiveTracksGen++;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005674 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07005675 continue;
5676 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005677
5678 TrackBase::track_state activeTrackState = activeTrack->mState;
5679 switch (activeTrackState) {
5680
5681 case TrackBase::PAUSING:
5682 mActiveTracks.remove(activeTrack);
5683 mActiveTracksGen++;
5684 doBroadcast = true;
5685 size--;
5686 continue;
5687
5688 case TrackBase::STARTING_1:
5689 sleepUs = 10000;
5690 i++;
5691 continue;
5692
5693 case TrackBase::STARTING_2:
5694 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005695 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07005696 activeTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005697 break;
5698
5699 case TrackBase::ACTIVE:
5700 break;
5701
5702 case TrackBase::IDLE:
5703 i++;
5704 continue;
5705
5706 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08005707 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07005708 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005709
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005710 activeTracks.add(activeTrack);
5711 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07005712
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005713 if (activeTrack->isFastTrack()) {
5714 ALOG_ASSERT(!mFastTrackAvail);
5715 ALOG_ASSERT(fastTrack == 0);
5716 fastTrack = activeTrack;
5717 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005718 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005719 if (doBroadcast) {
5720 mStartStopCond.broadcast();
5721 }
5722
5723 // sleep if there are no active tracks to process
5724 if (activeTracks.size() == 0) {
5725 if (sleepUs == 0) {
5726 sleepUs = kRecordThreadSleepUs;
5727 }
5728 continue;
5729 }
5730 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07005731
Eric Laurent81784c32012-11-19 14:55:58 -08005732 lockEffectChains_l(effectChains);
5733 }
5734
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005735 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07005736
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005737 size_t size = effectChains.size();
5738 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005739 // thread mutex is not locked, but effect chain is locked
5740 effectChains[i]->process_l();
5741 }
5742
Glenn Kasten735f45f2014-08-18 15:51:59 -07005743 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005744 if (mFastCapture != 0) {
5745 FastCaptureStateQueue *sq = mFastCapture->sq();
5746 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07005747 bool didModify = false;
5748 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005749 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
5750 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
5751 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5752 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5753 if (old == -1) {
5754 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5755 }
5756 }
5757 state->mCommand = FastCaptureState::READ_WRITE;
5758#if 0 // FIXME
5759 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08005760 FastThreadDumpState::kSamplingNforLowRamDevice :
5761 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005762#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07005763 didModify = true;
5764 }
5765 audio_track_cblk_t *cblkOld = state->mCblk;
5766 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
5767 if (cblkNew != cblkOld) {
5768 state->mCblk = cblkNew;
5769 // block until acked if removing a fast track
5770 if (cblkOld != NULL) {
5771 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
5772 }
5773 didModify = true;
5774 }
5775 sq->end(didModify);
5776 if (didModify) {
5777 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005778#if 0
5779 if (kUseFastCapture == FastCapture_Dynamic) {
5780 mNormalSource = mPipeSource;
5781 }
5782#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005783 }
5784 }
5785
Glenn Kasten735f45f2014-08-18 15:51:59 -07005786 // now run the fast track destructor with thread mutex unlocked
5787 fastTrackToRemove.clear();
5788
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005789 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
5790 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
5791 // slow, then this RecordThread will overrun by not calling HAL read often enough.
5792 // If destination is non-contiguous, first read past the nominal end of buffer, then
5793 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005794
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005795 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005796 ssize_t framesRead;
5797
5798 // If an NBAIO source is present, use it to read the normal capture's data
5799 if (mPipeSource != 0) {
5800 size_t framesToRead = mBufferSize / mFrameSize;
Andy Hung57446612015-04-19 23:56:46 -07005801 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005802 framesToRead, AudioBufferProvider::kInvalidPTS);
5803 if (framesRead == 0) {
5804 // since pipe is non-blocking, simulate blocking input
5805 sleepUs = (framesToRead * 1000000LL) / mSampleRate;
5806 }
5807 // otherwise use the HAL / AudioStreamIn directly
5808 } else {
5809 ssize_t bytesRead = mInput->stream->read(mInput->stream,
Andy Hung57446612015-04-19 23:56:46 -07005810 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005811 if (bytesRead < 0) {
5812 framesRead = bytesRead;
5813 } else {
5814 framesRead = bytesRead / mFrameSize;
5815 }
5816 }
5817
5818 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
5819 ALOGE("read failed: framesRead=%d", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005820 // Force input into standby so that it tries to recover at next read attempt
5821 inputStandBy();
5822 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005823 }
5824 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005825 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005826 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005827 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005828
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005829 if (mTeeSink != 0) {
Andy Hung57446612015-04-19 23:56:46 -07005830 (void) mTeeSink->write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005831 }
5832 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005833 {
5834 size_t part1 = mRsmpInFramesP2 - rear;
5835 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07005836 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005837 (framesRead - part1) * mFrameSize);
5838 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005839 }
5840 rear = mRsmpInRear += framesRead;
5841
5842 size = activeTracks.size();
5843 // loop over each active track
5844 for (size_t i = 0; i < size; i++) {
5845 activeTrack = activeTracks[i];
5846
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005847 // skip fast tracks, as those are handled directly by FastCapture
5848 if (activeTrack->isFastTrack()) {
5849 continue;
5850 }
5851
Andy Hung73c02e42015-03-29 01:13:58 -07005852 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07005853 // TODO: Update the activeTrack buffer converter in case of reconfigure.
5854
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005855 enum {
5856 OVERRUN_UNKNOWN,
5857 OVERRUN_TRUE,
5858 OVERRUN_FALSE
5859 } overrun = OVERRUN_UNKNOWN;
5860
5861 // loop over getNextBuffer to handle circular sink
5862 for (;;) {
5863
5864 activeTrack->mSink.frameCount = ~0;
5865 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
5866 size_t framesOut = activeTrack->mSink.frameCount;
5867 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
5868
Andy Hung73c02e42015-03-29 01:13:58 -07005869 // check available frames and handle overrun conditions
5870 // if the record track isn't draining fast enough.
5871 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005872 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07005873 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
5874 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005875 overrun = OVERRUN_TRUE;
5876 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005877 if (framesOut == 0 || framesIn == 0) {
5878 break;
5879 }
5880
Andy Hung6770c6f2015-04-07 13:43:36 -07005881 // Don't allow framesOut to be larger than what is possible with resampling
5882 // from framesIn.
5883 // This isn't strictly necessary but helps limit buffer resizing in
5884 // RecordBufferConverter. TODO: remove when no longer needed.
5885 framesOut = min(framesOut,
5886 destinationFramesPossible(
5887 framesIn, mSampleRate, activeTrack->mSampleRate));
Andy Hung97a893e2015-03-29 01:03:07 -07005888 // process frames from the RecordThread buffer provider to the RecordTrack buffer
5889 framesOut = activeTrack->mRecordBufferConverter->convert(
5890 activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005891
5892 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
5893 overrun = OVERRUN_FALSE;
5894 }
5895
5896 if (activeTrack->mFramesToDrop == 0) {
5897 if (framesOut > 0) {
5898 activeTrack->mSink.frameCount = framesOut;
5899 activeTrack->releaseBuffer(&activeTrack->mSink);
5900 }
5901 } else {
5902 // FIXME could do a partial drop of framesOut
5903 if (activeTrack->mFramesToDrop > 0) {
5904 activeTrack->mFramesToDrop -= framesOut;
5905 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005906 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005907 }
5908 } else {
5909 activeTrack->mFramesToDrop += framesOut;
5910 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
5911 activeTrack->mSyncStartEvent->isCancelled()) {
5912 ALOGW("Synced record %s, session %d, trigger session %d",
5913 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
5914 activeTrack->sessionId(),
5915 (activeTrack->mSyncStartEvent != 0) ?
5916 activeTrack->mSyncStartEvent->triggerSession() : 0);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005917 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005918 }
5919 }
5920 }
5921
5922 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005923 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005924 }
5925 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005926
5927 switch (overrun) {
5928 case OVERRUN_TRUE:
5929 // client isn't retrieving buffers fast enough
5930 if (!activeTrack->setOverflow()) {
5931 nsecs_t now = systemTime();
5932 // FIXME should lastWarning per track?
5933 if ((now - lastWarning) > kWarningThrottleNs) {
5934 ALOGW("RecordThread: buffer overflow");
5935 lastWarning = now;
5936 }
5937 }
5938 break;
5939 case OVERRUN_FALSE:
5940 activeTrack->clearOverflow();
5941 break;
5942 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005943 break;
5944 }
5945
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005946 }
5947
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005948unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08005949 // enable changes in effect chain
5950 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005951 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08005952 }
5953
Glenn Kasten93e471f2013-08-19 08:40:07 -07005954 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08005955
5956 {
5957 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07005958 for (size_t i = 0; i < mTracks.size(); i++) {
5959 sp<RecordTrack> track = mTracks[i];
5960 track->invalidate();
5961 }
Glenn Kasten2b806402013-11-20 16:37:38 -08005962 mActiveTracks.clear();
5963 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08005964 mStartStopCond.broadcast();
5965 }
5966
5967 releaseWakeLock();
5968
5969 ALOGV("RecordThread %p exiting", this);
5970 return false;
5971}
5972
Glenn Kasten93e471f2013-08-19 08:40:07 -07005973void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08005974{
5975 if (!mStandby) {
5976 inputStandBy();
5977 mStandby = true;
5978 }
5979}
5980
5981void AudioFlinger::RecordThread::inputStandBy()
5982{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005983 // Idle the fast capture if it's currently running
5984 if (mFastCapture != 0) {
5985 FastCaptureStateQueue *sq = mFastCapture->sq();
5986 FastCaptureState *state = sq->begin();
5987 if (!(state->mCommand & FastCaptureState::IDLE)) {
5988 state->mCommand = FastCaptureState::COLD_IDLE;
5989 state->mColdFutexAddr = &mFastCaptureFutex;
5990 state->mColdGen++;
5991 mFastCaptureFutex = 0;
5992 sq->end();
5993 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
5994 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
5995#if 0
5996 if (kUseFastCapture == FastCapture_Dynamic) {
5997 // FIXME
5998 }
5999#endif
6000#ifdef AUDIO_WATCHDOG
6001 // FIXME
6002#endif
6003 } else {
6004 sq->end(false /*didModify*/);
6005 }
6006 }
Eric Laurent81784c32012-11-19 14:55:58 -08006007 mInput->stream->common.standby(&mInput->stream->common);
6008}
6009
Glenn Kasten05997e22014-03-13 15:08:33 -07006010// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07006011sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08006012 const sp<AudioFlinger::Client>& client,
6013 uint32_t sampleRate,
6014 audio_format_t format,
6015 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08006016 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08006017 int sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07006018 size_t *notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08006019 int uid,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07006020 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08006021 pid_t tid,
6022 status_t *status)
6023{
Glenn Kasten74935e42013-12-19 08:56:45 -08006024 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08006025 sp<RecordTrack> track;
6026 status_t lStatus;
6027
Glenn Kasten90e58b12013-07-31 16:16:02 -07006028 // client expresses a preference for FAST, but we get the final say
6029 if (*flags & IAudioFlinger::TRACK_FAST) {
6030 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07006031 // we formerly checked for a callback handler (non-0 tid),
6032 // but that is no longer required for TRANSFER_OBTAIN mode
6033 //
Glenn Kasten74105912014-07-03 12:28:53 -07006034 // frame count is not specified, or is exactly the pipe depth
6035 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006036 // PCM data
6037 audio_is_linear_pcm(format) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006038 // native format
6039 (format == mFormat) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006040 // native channel mask
6041 (channelMask == mChannelMask) &&
6042 // native hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07006043 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006044 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006045 hasFastCapture() &&
6046 // there are sufficient fast track slots available
6047 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07006048 ) {
Glenn Kasten74105912014-07-03 12:28:53 -07006049 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%u mFrameCount=%u",
Glenn Kasten90e58b12013-07-31 16:16:02 -07006050 frameCount, mFrameCount);
6051 } else {
Glenn Kasten74105912014-07-03 12:28:53 -07006052 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%u mFrameCount=%u mPipeFramesP2=%u "
6053 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006054 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Glenn Kasten74105912014-07-03 12:28:53 -07006055 frameCount, mFrameCount, mPipeFramesP2,
6056 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
6057 hasFastCapture(), tid, mFastTrackAvail);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006058 *flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kasten74105912014-07-03 12:28:53 -07006059 }
6060 }
6061
6062 // compute track buffer size in frames, and suggest the notification frame count
6063 if (*flags & IAudioFlinger::TRACK_FAST) {
6064 // fast track: frame count is exactly the pipe depth
6065 frameCount = mPipeFramesP2;
6066 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
6067 *notificationFrames = mFrameCount;
6068 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006069 // not fast track: max notification period is resampled equivalent of one HAL buffer time
6070 // or 20 ms if there is a fast capture
6071 // TODO This could be a roundupRatio inline, and const
6072 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
6073 * sampleRate + mSampleRate - 1) / mSampleRate;
6074 // minimum number of notification periods is at least kMinNotifications,
6075 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
6076 static const size_t kMinNotifications = 3;
6077 static const uint32_t kMinMs = 30;
6078 // TODO This could be a roundupRatio inline
6079 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
6080 // TODO This could be a roundupRatio inline
6081 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
6082 maxNotificationFrames;
6083 const size_t minFrameCount = maxNotificationFrames *
6084 max(kMinNotifications, minNotificationsByMs);
6085 frameCount = max(frameCount, minFrameCount);
6086 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
6087 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07006088 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07006089 }
Glenn Kasten74935e42013-12-19 08:56:45 -08006090 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07006091
Glenn Kasten15e57982013-09-24 11:52:37 -07006092 lStatus = initCheck();
6093 if (lStatus != NO_ERROR) {
6094 ALOGE("createRecordTrack_l() audio driver not initialized");
6095 goto Exit;
6096 }
Eric Laurent81784c32012-11-19 14:55:58 -08006097
6098 { // scope for mLock
6099 Mutex::Autolock _l(mLock);
6100
6101 track = new RecordTrack(this, client, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07006102 format, channelMask, frameCount, NULL, sessionId, uid,
6103 *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08006104
Glenn Kasten03003332013-08-06 15:40:54 -07006105 lStatus = track->initCheck();
6106 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07006107 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08006108 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08006109 goto Exit;
6110 }
6111 mTracks.add(track);
6112
6113 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6114 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6115 mAudioFlinger->btNrecIsOff();
6116 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6117 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006118
6119 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
6120 pid_t callingPid = IPCThreadState::self()->getCallingPid();
6121 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
6122 // so ask activity manager to do this on our behalf
6123 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
6124 }
Eric Laurent81784c32012-11-19 14:55:58 -08006125 }
Glenn Kasten05997e22014-03-13 15:08:33 -07006126
Eric Laurent81784c32012-11-19 14:55:58 -08006127 lStatus = NO_ERROR;
6128
6129Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07006130 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08006131 return track;
6132}
6133
6134status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
6135 AudioSystem::sync_event_t event,
6136 int triggerSession)
6137{
6138 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
6139 sp<ThreadBase> strongMe = this;
6140 status_t status = NO_ERROR;
6141
6142 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006143 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006144 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006145 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08006146 triggerSession,
6147 recordTrack->sessionId(),
6148 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006149 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08006150 // Sync event can be cancelled by the trigger session if the track is not in a
6151 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006152 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006153 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006154 } else {
6155 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006156 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006157 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08006158 }
6159 }
6160
6161 {
Glenn Kasten47c20702013-08-13 15:37:35 -07006162 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08006163 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006164 if (mActiveTracks.indexOf(recordTrack) >= 0) {
6165 if (recordTrack->mState == TrackBase::PAUSING) {
6166 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006167 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006168 } else {
6169 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08006170 }
6171 return status;
6172 }
6173
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006174 // TODO consider other ways of handling this, such as changing the state to :STARTING and
6175 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
6176 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006177 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08006178 mActiveTracks.add(recordTrack);
6179 mActiveTracksGen++;
Eric Laurent83b88082014-06-20 18:31:16 -07006180 status_t status = NO_ERROR;
6181 if (recordTrack->isExternalTrack()) {
6182 mLock.unlock();
Eric Laurent4dc68062014-07-28 17:26:49 -07006183 status = AudioSystem::startInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006184 mLock.lock();
6185 // FIXME should verify that recordTrack is still in mActiveTracks
6186 if (status != NO_ERROR) {
6187 mActiveTracks.remove(recordTrack);
6188 mActiveTracksGen++;
6189 recordTrack->clearSyncStartEvent();
6190 ALOGV("RecordThread::start error %d", status);
6191 return status;
6192 }
Eric Laurent81784c32012-11-19 14:55:58 -08006193 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006194 // Catch up with current buffer indices if thread is already running.
6195 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
6196 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
6197 // see previously buffered data before it called start(), but with greater risk of overrun.
6198
Andy Hung73c02e42015-03-29 01:13:58 -07006199 recordTrack->mResamplerBufferProvider->reset();
Andy Hung97a893e2015-03-29 01:03:07 -07006200 // clear any converter state as new data will be discontinuous
6201 recordTrack->mRecordBufferConverter->reset();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006202 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08006203 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08006204 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08006205 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006206 ALOGV("Record failed to start");
6207 status = BAD_VALUE;
6208 goto startError;
6209 }
Eric Laurent81784c32012-11-19 14:55:58 -08006210 return status;
6211 }
Glenn Kasten7c027242012-12-26 14:43:16 -08006212
Eric Laurent81784c32012-11-19 14:55:58 -08006213startError:
Eric Laurent83b88082014-06-20 18:31:16 -07006214 if (recordTrack->isExternalTrack()) {
Eric Laurent4dc68062014-07-28 17:26:49 -07006215 AudioSystem::stopInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006216 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006217 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006218 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08006219 return status;
6220}
6221
Eric Laurent81784c32012-11-19 14:55:58 -08006222void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6223{
6224 sp<SyncEvent> strongEvent = event.promote();
6225
6226 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08006227 sp<RefBase> ptr = strongEvent->cookie().promote();
6228 if (ptr != 0) {
6229 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
6230 recordTrack->handleSyncStartEvent(strongEvent);
6231 }
Eric Laurent81784c32012-11-19 14:55:58 -08006232 }
6233}
6234
Glenn Kastena8356f62013-07-25 14:37:52 -07006235bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08006236 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07006237 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006238 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08006239 return false;
6240 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006241 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08006242 recordTrack->mState = TrackBase::PAUSING;
6243 // do not wait for mStartStopCond if exiting
6244 if (exitPending()) {
6245 return true;
6246 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006247 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08006248 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006249 // if we have been restarted, recordTrack is in mActiveTracks here
6250 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006251 ALOGV("Record stopped OK");
6252 return true;
6253 }
6254 return false;
6255}
6256
Glenn Kasten0f11b512014-01-31 16:18:54 -08006257bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08006258{
6259 return false;
6260}
6261
Glenn Kasten0f11b512014-01-31 16:18:54 -08006262status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006263{
6264#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
6265 if (!isValidSyncEvent(event)) {
6266 return BAD_VALUE;
6267 }
6268
6269 int eventSession = event->triggerSession();
6270 status_t ret = NAME_NOT_FOUND;
6271
6272 Mutex::Autolock _l(mLock);
6273
6274 for (size_t i = 0; i < mTracks.size(); i++) {
6275 sp<RecordTrack> track = mTracks[i];
6276 if (eventSession == track->sessionId()) {
6277 (void) track->setSyncEvent(event);
6278 ret = NO_ERROR;
6279 }
6280 }
6281 return ret;
6282#else
6283 return BAD_VALUE;
6284#endif
6285}
6286
6287// destroyTrack_l() must be called with ThreadBase::mLock held
6288void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6289{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006290 track->terminate();
6291 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08006292 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08006293 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006294 removeTrack_l(track);
6295 }
6296}
6297
6298void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6299{
6300 mTracks.remove(track);
6301 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006302 if (track->isFastTrack()) {
6303 ALOG_ASSERT(!mFastTrackAvail);
6304 mFastTrackAvail = true;
6305 }
Eric Laurent81784c32012-11-19 14:55:58 -08006306}
6307
6308void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6309{
6310 dumpInternals(fd, args);
6311 dumpTracks(fd, args);
6312 dumpEffectChains(fd, args);
6313}
6314
6315void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6316{
Elliott Hughes87cebad2014-05-22 10:14:43 -07006317 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08006318
Glenn Kasten44182c22015-03-05 17:12:23 -08006319 dumpBase(fd, args);
6320
6321 if (mActiveTracks.size() == 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006322 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006323 }
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006324 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006325 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08006326
6327 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
6328 const FastCaptureDumpState copy(mFastCaptureDumpState);
6329 copy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006330}
6331
Glenn Kasten0f11b512014-01-31 16:18:54 -08006332void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006333{
6334 const size_t SIZE = 256;
6335 char buffer[SIZE];
6336 String8 result;
6337
Marco Nelissenb2208842014-02-07 14:00:50 -08006338 size_t numtracks = mTracks.size();
6339 size_t numactive = mActiveTracks.size();
6340 size_t numactiveseen = 0;
Elliott Hughes87cebad2014-05-22 10:14:43 -07006341 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08006342 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006343 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08006344 RecordTrack::appendDumpHeader(result);
6345 for (size_t i = 0; i < numtracks ; ++i) {
6346 sp<RecordTrack> track = mTracks[i];
6347 if (track != 0) {
6348 bool active = mActiveTracks.indexOf(track) >= 0;
6349 if (active) {
6350 numactiveseen++;
6351 }
6352 track->dump(buffer, SIZE, active);
6353 result.append(buffer);
6354 }
Eric Laurent81784c32012-11-19 14:55:58 -08006355 }
Marco Nelissenb2208842014-02-07 14:00:50 -08006356 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006357 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006358 }
6359
Marco Nelissenb2208842014-02-07 14:00:50 -08006360 if (numactiveseen != numactive) {
6361 snprintf(buffer, SIZE, " The following tracks are in the active list but"
6362 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006363 result.append(buffer);
6364 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08006365 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08006366 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08006367 if (mTracks.indexOf(track) < 0) {
6368 track->dump(buffer, SIZE, true);
6369 result.append(buffer);
6370 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006371 }
Eric Laurent81784c32012-11-19 14:55:58 -08006372
6373 }
6374 write(fd, result.string(), result.size());
6375}
6376
Andy Hung73c02e42015-03-29 01:13:58 -07006377
6378void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
6379{
6380 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6381 RecordThread *recordThread = (RecordThread *) threadBase.get();
6382 mRsmpInFront = recordThread->mRsmpInRear;
6383 mRsmpInUnrel = 0;
6384}
6385
6386void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
6387 size_t *framesAvailable, bool *hasOverrun)
6388{
6389 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6390 RecordThread *recordThread = (RecordThread *) threadBase.get();
6391 const int32_t rear = recordThread->mRsmpInRear;
6392 const int32_t front = mRsmpInFront;
6393 const ssize_t filled = rear - front;
6394
6395 size_t framesIn;
6396 bool overrun = false;
6397 if (filled < 0) {
6398 // should not happen, but treat like a massive overrun and re-sync
6399 framesIn = 0;
6400 mRsmpInFront = rear;
6401 overrun = true;
6402 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
6403 framesIn = (size_t) filled;
6404 } else {
6405 // client is not keeping up with server, but give it latest data
6406 framesIn = recordThread->mRsmpInFrames;
6407 mRsmpInFront = /* front = */ rear - framesIn;
6408 overrun = true;
6409 }
6410 if (framesAvailable != NULL) {
6411 *framesAvailable = framesIn;
6412 }
6413 if (hasOverrun != NULL) {
6414 *hasOverrun = overrun;
6415 }
6416}
6417
Eric Laurent81784c32012-11-19 14:55:58 -08006418// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006419status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
6420 AudioBufferProvider::Buffer* buffer, int64_t pts __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006421{
Andy Hung73c02e42015-03-29 01:13:58 -07006422 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006423 if (threadBase == 0) {
6424 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006425 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006426 return NOT_ENOUGH_DATA;
6427 }
6428 RecordThread *recordThread = (RecordThread *) threadBase.get();
6429 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07006430 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07006431 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006432 // FIXME should not be P2 (don't want to increase latency)
6433 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006434 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07006435 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006436 front &= recordThread->mRsmpInFramesP2 - 1;
6437 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07006438 if (part1 > (size_t) filled) {
6439 part1 = filled;
6440 }
6441 size_t ask = buffer->frameCount;
6442 ALOG_ASSERT(ask > 0);
6443 if (part1 > ask) {
6444 part1 = ask;
6445 }
6446 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07006447 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07006448 buffer->raw = NULL;
6449 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07006450 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07006451 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08006452 }
6453
Andy Hung57446612015-04-19 23:56:46 -07006454 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07006455 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07006456 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08006457 return NO_ERROR;
6458}
6459
6460// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006461void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
6462 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006463{
Glenn Kasten85948432013-08-19 12:09:05 -07006464 size_t stepCount = buffer->frameCount;
6465 if (stepCount == 0) {
6466 return;
6467 }
Andy Hung73c02e42015-03-29 01:13:58 -07006468 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
6469 mRsmpInUnrel -= stepCount;
6470 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07006471 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006472 buffer->frameCount = 0;
6473}
6474
Andy Hung97a893e2015-03-29 01:03:07 -07006475AudioFlinger::RecordThread::RecordBufferConverter::RecordBufferConverter(
6476 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6477 uint32_t srcSampleRate,
6478 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6479 uint32_t dstSampleRate) :
6480 mSrcChannelMask(AUDIO_CHANNEL_INVALID), // updateParameters will set following vars
6481 // mSrcFormat
6482 // mSrcSampleRate
6483 // mDstChannelMask
6484 // mDstFormat
6485 // mDstSampleRate
6486 // mSrcChannelCount
6487 // mDstChannelCount
6488 // mDstFrameSize
6489 mBuf(NULL), mBufFrames(0), mBufFrameSize(0),
Andy Hungd330ee42015-04-20 13:23:41 -07006490 mResampler(NULL),
6491 mIsLegacyDownmix(false),
6492 mIsLegacyUpmix(false),
6493 mRequiresFloat(false),
6494 mInputConverterProvider(NULL)
Andy Hung97a893e2015-03-29 01:03:07 -07006495{
6496 (void)updateParameters(srcChannelMask, srcFormat, srcSampleRate,
6497 dstChannelMask, dstFormat, dstSampleRate);
6498}
6499
6500AudioFlinger::RecordThread::RecordBufferConverter::~RecordBufferConverter() {
6501 free(mBuf);
6502 delete mResampler;
Andy Hungd330ee42015-04-20 13:23:41 -07006503 delete mInputConverterProvider;
Andy Hung97a893e2015-03-29 01:03:07 -07006504}
6505
6506size_t AudioFlinger::RecordThread::RecordBufferConverter::convert(void *dst,
6507 AudioBufferProvider *provider, size_t frames)
6508{
Andy Hungd330ee42015-04-20 13:23:41 -07006509 if (mInputConverterProvider != NULL) {
6510 mInputConverterProvider->setBufferProvider(provider);
6511 provider = mInputConverterProvider;
6512 }
6513
6514 if (mResampler == NULL) {
Andy Hung97a893e2015-03-29 01:03:07 -07006515 ALOGVV("NO RESAMPLING sampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6516 mSrcSampleRate, mSrcFormat, mDstFormat);
6517
6518 AudioBufferProvider::Buffer buffer;
6519 for (size_t i = frames; i > 0; ) {
6520 buffer.frameCount = i;
6521 status_t status = provider->getNextBuffer(&buffer, 0);
6522 if (status != OK || buffer.frameCount == 0) {
6523 frames -= i; // cannot fill request.
6524 break;
6525 }
Andy Hungd330ee42015-04-20 13:23:41 -07006526 // format convert to destination buffer
6527 convertNoResampler(dst, buffer.raw, buffer.frameCount);
Andy Hung97a893e2015-03-29 01:03:07 -07006528
6529 dst = (int8_t*)dst + buffer.frameCount * mDstFrameSize;
6530 i -= buffer.frameCount;
6531 provider->releaseBuffer(&buffer);
6532 }
6533 } else {
6534 ALOGVV("RESAMPLING mSrcSampleRate:%u mDstSampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6535 mSrcSampleRate, mDstSampleRate, mSrcFormat, mDstFormat);
6536
Andy Hungd330ee42015-04-20 13:23:41 -07006537 // reallocate buffer if needed
6538 if (mBufFrameSize != 0 && mBufFrames < frames) {
6539 free(mBuf);
6540 mBufFrames = frames;
6541 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
6542 }
Andy Hung97a893e2015-03-29 01:03:07 -07006543 // resampler accumulates, but we only have one source track
Andy Hungd330ee42015-04-20 13:23:41 -07006544 memset(mBuf, 0, frames * mBufFrameSize);
6545 frames = mResampler->resample((int32_t*)mBuf, frames, provider);
6546 // format convert to destination buffer
6547 convertResampler(dst, mBuf, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006548 }
6549 return frames;
6550}
6551
6552status_t AudioFlinger::RecordThread::RecordBufferConverter::updateParameters(
6553 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6554 uint32_t srcSampleRate,
6555 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6556 uint32_t dstSampleRate)
6557{
6558 // quick evaluation if there is any change.
6559 if (mSrcFormat == srcFormat
6560 && mSrcChannelMask == srcChannelMask
6561 && mSrcSampleRate == srcSampleRate
6562 && mDstFormat == dstFormat
6563 && mDstChannelMask == dstChannelMask
6564 && mDstSampleRate == dstSampleRate) {
6565 return NO_ERROR;
6566 }
6567
Andy Hungdb4c0312015-05-06 08:46:52 -07006568 ALOGV("RecordBufferConverter updateParameters srcMask:%#x dstMask:%#x"
6569 " srcFormat:%#x dstFormat:%#x srcRate:%u dstRate:%u",
6570 srcChannelMask, dstChannelMask, srcFormat, dstFormat, srcSampleRate, dstSampleRate);
Andy Hung97a893e2015-03-29 01:03:07 -07006571 const bool valid =
6572 audio_is_input_channel(srcChannelMask)
6573 && audio_is_input_channel(dstChannelMask)
6574 && audio_is_valid_format(srcFormat) && audio_is_linear_pcm(srcFormat)
6575 && audio_is_valid_format(dstFormat) && audio_is_linear_pcm(dstFormat)
6576 && (srcSampleRate <= dstSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX)
6577 ; // no upsampling checks for now
6578 if (!valid) {
6579 return BAD_VALUE;
6580 }
6581
6582 mSrcFormat = srcFormat;
6583 mSrcChannelMask = srcChannelMask;
6584 mSrcSampleRate = srcSampleRate;
6585 mDstFormat = dstFormat;
6586 mDstChannelMask = dstChannelMask;
6587 mDstSampleRate = dstSampleRate;
6588
6589 // compute derived parameters
6590 mSrcChannelCount = audio_channel_count_from_in_mask(srcChannelMask);
6591 mDstChannelCount = audio_channel_count_from_in_mask(dstChannelMask);
6592 mDstFrameSize = mDstChannelCount * audio_bytes_per_sample(mDstFormat);
6593
Andy Hungd330ee42015-04-20 13:23:41 -07006594 // do we need to resample?
6595 delete mResampler;
6596 mResampler = NULL;
6597 if (mSrcSampleRate != mDstSampleRate) {
6598 mResampler = AudioResampler::create(AUDIO_FORMAT_PCM_FLOAT,
6599 mSrcChannelCount, mDstSampleRate);
6600 mResampler->setSampleRate(mSrcSampleRate);
6601 mResampler->setVolume(AudioMixer::UNITY_GAIN_FLOAT, AudioMixer::UNITY_GAIN_FLOAT);
6602 }
6603
6604 // are we running legacy channel conversion modes?
6605 mIsLegacyDownmix = (mSrcChannelMask == AUDIO_CHANNEL_IN_STEREO
6606 || mSrcChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK)
6607 && mDstChannelMask == AUDIO_CHANNEL_IN_MONO;
6608 mIsLegacyUpmix = mSrcChannelMask == AUDIO_CHANNEL_IN_MONO
6609 && (mDstChannelMask == AUDIO_CHANNEL_IN_STEREO
6610 || mDstChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK);
6611
6612 // do we need to process in float?
6613 mRequiresFloat = mResampler != NULL || mIsLegacyDownmix || mIsLegacyUpmix;
6614
6615 // do we need a staging buffer to convert for destination (we can still optimize this)?
6616 // we use mBufFrameSize > 0 to indicate both frame size as well as buffer necessity
6617 if (mResampler != NULL) {
6618 mBufFrameSize = max(mSrcChannelCount, FCC_2)
6619 * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
6620 } else if ((mIsLegacyUpmix || mIsLegacyDownmix) && mDstFormat != AUDIO_FORMAT_PCM_FLOAT) {
6621 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
6622 } else if (mSrcChannelMask != mDstChannelMask && mDstFormat != mSrcFormat) {
Andy Hung97a893e2015-03-29 01:03:07 -07006623 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(mSrcFormat);
6624 } else {
6625 mBufFrameSize = 0;
6626 }
6627 mBufFrames = 0; // force the buffer to be resized.
6628
Andy Hungd330ee42015-04-20 13:23:41 -07006629 // do we need an input converter buffer provider to give us float?
6630 delete mInputConverterProvider;
6631 mInputConverterProvider = NULL;
6632 if (mRequiresFloat && mSrcFormat != AUDIO_FORMAT_PCM_FLOAT) {
6633 mInputConverterProvider = new ReformatBufferProvider(
6634 audio_channel_count_from_in_mask(mSrcChannelMask),
6635 mSrcFormat,
6636 AUDIO_FORMAT_PCM_FLOAT,
6637 256 /* provider buffer frame count */);
6638 }
6639
6640 // do we need a remixer to do channel mask conversion
6641 if (!mIsLegacyDownmix && !mIsLegacyUpmix && mSrcChannelMask != mDstChannelMask) {
6642 (void) memcpy_by_index_array_initialization_from_channel_mask(
6643 mIdxAry, ARRAY_SIZE(mIdxAry), mDstChannelMask, mSrcChannelMask);
Andy Hung97a893e2015-03-29 01:03:07 -07006644 }
6645 return NO_ERROR;
6646}
6647
Andy Hungd330ee42015-04-20 13:23:41 -07006648void AudioFlinger::RecordThread::RecordBufferConverter::convertNoResampler(
6649 void *dst, const void *src, size_t frames)
Andy Hung97a893e2015-03-29 01:03:07 -07006650{
Andy Hungd330ee42015-04-20 13:23:41 -07006651 // src is native type unless there is legacy upmix or downmix, whereupon it is float.
Andy Hung97a893e2015-03-29 01:03:07 -07006652 if (mBufFrameSize != 0 && mBufFrames < frames) {
6653 free(mBuf);
6654 mBufFrames = frames;
6655 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
6656 }
Andy Hungd330ee42015-04-20 13:23:41 -07006657 // do we need to do legacy upmix and downmix?
6658 if (mIsLegacyUpmix || mIsLegacyDownmix) {
Andy Hung97a893e2015-03-29 01:03:07 -07006659 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07006660 if (mIsLegacyUpmix) {
6661 upmix_to_stereo_float_from_mono_float((float *)dstBuf,
6662 (const float *)src, frames);
6663 } else /*mIsLegacyDownmix */ {
6664 downmix_to_mono_float_from_stereo_float((float *)dstBuf,
6665 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006666 }
Andy Hungd330ee42015-04-20 13:23:41 -07006667 if (mBuf != NULL) {
6668 memcpy_by_audio_format(dst, mDstFormat, mBuf, AUDIO_FORMAT_PCM_FLOAT,
6669 frames * mDstChannelCount);
6670 }
6671 return;
6672 }
6673 // do we need to do channel mask conversion?
6674 if (mSrcChannelMask != mDstChannelMask) {
Andy Hung97a893e2015-03-29 01:03:07 -07006675 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07006676 memcpy_by_index_array(dstBuf, mDstChannelCount,
6677 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mSrcFormat), frames);
6678 if (dstBuf == dst) {
6679 return; // format is the same
6680 }
6681 }
6682 // convert to destination buffer
6683 const void *convertBuf = mBuf != NULL ? mBuf : src;
6684 memcpy_by_audio_format(dst, mDstFormat, convertBuf, mSrcFormat,
6685 frames * mDstChannelCount);
6686}
6687
6688void AudioFlinger::RecordThread::RecordBufferConverter::convertResampler(
6689 void *dst, /*not-a-const*/ void *src, size_t frames)
6690{
6691 // src buffer format is ALWAYS float when entering this routine
6692 if (mIsLegacyUpmix) {
6693 ; // mono to stereo already handled by resampler
6694 } else if (mIsLegacyDownmix
6695 || (mSrcChannelMask == mDstChannelMask && mSrcChannelCount == 1)) {
6696 // the resampler outputs stereo for mono input channel (a feature?)
6697 // must convert to mono
6698 downmix_to_mono_float_from_stereo_float((float *)src,
6699 (const float *)src, frames);
6700 } else if (mSrcChannelMask != mDstChannelMask) {
6701 // convert to mono channel again for channel mask conversion (could be skipped
6702 // with further optimization).
Andy Hung97a893e2015-03-29 01:03:07 -07006703 if (mSrcChannelCount == 1) {
Andy Hungd330ee42015-04-20 13:23:41 -07006704 downmix_to_mono_float_from_stereo_float((float *)src,
6705 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006706 }
Andy Hungd330ee42015-04-20 13:23:41 -07006707 // convert to destination format (in place, OK as float is larger than other types)
6708 if (mDstFormat != AUDIO_FORMAT_PCM_FLOAT) {
6709 memcpy_by_audio_format(src, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
6710 frames * mSrcChannelCount);
6711 }
6712 // channel convert and save to dst
6713 memcpy_by_index_array(dst, mDstChannelCount,
6714 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mDstFormat), frames);
6715 return;
Andy Hung97a893e2015-03-29 01:03:07 -07006716 }
Andy Hungd330ee42015-04-20 13:23:41 -07006717 // convert to destination format and save to dst
6718 memcpy_by_audio_format(dst, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
6719 frames * mDstChannelCount);
Andy Hung97a893e2015-03-29 01:03:07 -07006720}
6721
Eric Laurent10351942014-05-08 18:49:52 -07006722bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
6723 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006724{
6725 bool reconfig = false;
6726
Eric Laurent10351942014-05-08 18:49:52 -07006727 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006728
Eric Laurent10351942014-05-08 18:49:52 -07006729 audio_format_t reqFormat = mFormat;
6730 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07006731 // 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 -07006732 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
6733
6734 AudioParameter param = AudioParameter(keyValuePair);
6735 int value;
6736 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
6737 // channel count change can be requested. Do we mandate the first client defines the
6738 // HAL sampling rate and channel count or do we allow changes on the fly?
6739 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6740 samplingRate = value;
6741 reconfig = true;
6742 }
6743 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07006744 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07006745 status = BAD_VALUE;
6746 } else {
6747 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08006748 reconfig = true;
6749 }
Eric Laurent10351942014-05-08 18:49:52 -07006750 }
6751 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
6752 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07006753 if (!audio_is_input_channel(mask) ||
6754 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07006755 status = BAD_VALUE;
6756 } else {
6757 channelMask = mask;
6758 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006759 }
Eric Laurent10351942014-05-08 18:49:52 -07006760 }
6761 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6762 // do not accept frame count changes if tracks are open as the track buffer
6763 // size depends on frame count and correct behavior would not be guaranteed
6764 // if frame count is changed after track creation
6765 if (mActiveTracks.size() > 0) {
6766 status = INVALID_OPERATION;
6767 } else {
6768 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006769 }
Eric Laurent10351942014-05-08 18:49:52 -07006770 }
6771 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6772 // forward device change to effects that have requested to be
6773 // aware of attached audio device.
6774 for (size_t i = 0; i < mEffectChains.size(); i++) {
6775 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08006776 }
Eric Laurent81784c32012-11-19 14:55:58 -08006777
Eric Laurent10351942014-05-08 18:49:52 -07006778 // store input device and output device but do not forward output device to audio HAL.
6779 // Note that status is ignored by the caller for output device
6780 // (see AudioFlinger::setParameters()
6781 if (audio_is_output_devices(value)) {
6782 mOutDevice = value;
6783 status = BAD_VALUE;
6784 } else {
6785 mInDevice = value;
6786 // disable AEC and NS if the device is a BT SCO headset supporting those
6787 // pre processings
6788 if (mTracks.size() > 0) {
6789 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6790 mAudioFlinger->btNrecIsOff();
6791 for (size_t i = 0; i < mTracks.size(); i++) {
6792 sp<RecordTrack> track = mTracks[i];
6793 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
6794 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08006795 }
6796 }
6797 }
Eric Laurent10351942014-05-08 18:49:52 -07006798 }
6799 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
6800 mAudioSource != (audio_source_t)value) {
6801 // forward device change to effects that have requested to be
6802 // aware of attached audio device.
6803 for (size_t i = 0; i < mEffectChains.size(); i++) {
6804 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08006805 }
Eric Laurent10351942014-05-08 18:49:52 -07006806 mAudioSource = (audio_source_t)value;
6807 }
Glenn Kastene198c362013-08-13 09:13:36 -07006808
Eric Laurent10351942014-05-08 18:49:52 -07006809 if (status == NO_ERROR) {
6810 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6811 keyValuePair.string());
6812 if (status == INVALID_OPERATION) {
6813 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006814 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6815 keyValuePair.string());
Eric Laurent10351942014-05-08 18:49:52 -07006816 }
6817 if (reconfig) {
6818 if (status == BAD_VALUE &&
Andy Hung97a893e2015-03-29 01:03:07 -07006819 audio_is_linear_pcm(mInput->stream->common.get_format(&mInput->stream->common)) &&
6820 audio_is_linear_pcm(reqFormat) &&
Eric Laurent10351942014-05-08 18:49:52 -07006821 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
Andy Hung97a893e2015-03-29 01:03:07 -07006822 <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate)) &&
Andy Hunge5412692014-05-16 11:25:07 -07006823 audio_channel_count_from_in_mask(
Andy Hungd1abb8f2015-05-05 23:42:34 -07006824 mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07006825 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006826 }
Eric Laurent10351942014-05-08 18:49:52 -07006827 if (status == NO_ERROR) {
6828 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07006829 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08006830 }
6831 }
Eric Laurent81784c32012-11-19 14:55:58 -08006832 }
Eric Laurent10351942014-05-08 18:49:52 -07006833
Eric Laurent81784c32012-11-19 14:55:58 -08006834 return reconfig;
6835}
6836
6837String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6838{
Eric Laurent81784c32012-11-19 14:55:58 -08006839 Mutex::Autolock _l(mLock);
6840 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07006841 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08006842 }
6843
Glenn Kastend8ea6992013-07-16 14:17:15 -07006844 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
6845 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08006846 free(s);
6847 return out_s8;
6848}
6849
Eric Laurent73e26b62015-04-27 16:55:58 -07006850void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event) {
6851 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
6852
6853 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08006854
6855 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07006856 case AUDIO_INPUT_OPENED:
6857 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07006858 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07006859 desc->mChannelMask = mChannelMask;
6860 desc->mSamplingRate = mSampleRate;
6861 desc->mFormat = mFormat;
6862 desc->mFrameCount = mFrameCount;
6863 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006864 break;
6865
Eric Laurent73e26b62015-04-27 16:55:58 -07006866 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08006867 default:
6868 break;
6869 }
Eric Laurent73e26b62015-04-27 16:55:58 -07006870 mAudioFlinger->ioConfigChanged(event, desc);
Eric Laurent81784c32012-11-19 14:55:58 -08006871}
6872
Glenn Kastendeca2ae2014-02-07 10:25:56 -08006873void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006874{
Eric Laurent81784c32012-11-19 14:55:58 -08006875 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
6876 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Andy Hunge5412692014-05-16 11:25:07 -07006877 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Andy Hungd330ee42015-04-20 13:23:41 -07006878 if (mChannelCount > FCC_8) {
6879 ALOGE("HAL channel count %d > %d", mChannelCount, FCC_8);
6880 }
Andy Hung463be252014-07-10 16:56:07 -07006881 mHALFormat = mInput->stream->common.get_format(&mInput->stream->common);
6882 mFormat = mHALFormat;
Andy Hungd330ee42015-04-20 13:23:41 -07006883 if (!audio_is_linear_pcm(mFormat)) {
6884 ALOGE("HAL format %#x is not linear pcm", mFormat);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07006885 }
Eric Laurent665470b2014-07-03 16:37:08 -07006886 mFrameSize = audio_stream_in_frame_size(mInput->stream);
Glenn Kasten548efc92012-11-29 08:48:51 -08006887 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
6888 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006889 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08006890 // 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 -07006891 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08006892 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006893 // A larger value should allow more old data to be read after a track calls start(),
6894 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07006895 //
6896 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08006897 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07006898 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07006899 free(mRsmpInBuffer);
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006900
6901 // TODO optimize audio capture buffer sizes ...
6902 // Here we calculate the size of the sliding buffer used as a source
6903 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
6904 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
6905 // be better to have it derived from the pipe depth in the long term.
6906 // The current value is higher than necessary. However it should not add to latency.
6907
Glenn Kasten85948432013-08-19 12:09:05 -07006908 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Andy Hung57446612015-04-19 23:56:46 -07006909 (void)posix_memalign(&mRsmpInBuffer, 32, (mRsmpInFramesP2 + mFrameCount - 1) * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006910
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006911 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
6912 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08006913}
6914
Glenn Kasten5f972c02014-01-13 09:59:31 -08006915uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08006916{
6917 Mutex::Autolock _l(mLock);
6918 if (initCheck() != NO_ERROR) {
6919 return 0;
6920 }
6921
6922 return mInput->stream->get_input_frames_lost(mInput->stream);
6923}
6924
6925uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
6926{
6927 Mutex::Autolock _l(mLock);
6928 uint32_t result = 0;
6929 if (getEffectChain_l(sessionId) != 0) {
6930 result = EFFECT_SESSION;
6931 }
6932
6933 for (size_t i = 0; i < mTracks.size(); ++i) {
6934 if (sessionId == mTracks[i]->sessionId()) {
6935 result |= TRACK_SESSION;
6936 break;
6937 }
6938 }
6939
6940 return result;
6941}
6942
6943KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
6944{
6945 KeyedVector<int, bool> ids;
6946 Mutex::Autolock _l(mLock);
6947 for (size_t j = 0; j < mTracks.size(); ++j) {
6948 sp<RecordThread::RecordTrack> track = mTracks[j];
6949 int sessionId = track->sessionId();
6950 if (ids.indexOfKey(sessionId) < 0) {
6951 ids.add(sessionId, true);
6952 }
6953 }
6954 return ids;
6955}
6956
6957AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
6958{
6959 Mutex::Autolock _l(mLock);
6960 AudioStreamIn *input = mInput;
6961 mInput = NULL;
6962 return input;
6963}
6964
6965// this method must always be called either with ThreadBase mLock held or inside the thread loop
6966audio_stream_t* AudioFlinger::RecordThread::stream() const
6967{
6968 if (mInput == NULL) {
6969 return NULL;
6970 }
6971 return &mInput->stream->common;
6972}
6973
6974status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6975{
6976 // only one chain per input thread
6977 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07006978 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08006979 return INVALID_OPERATION;
6980 }
6981 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07006982 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08006983 chain->setInBuffer(NULL);
6984 chain->setOutBuffer(NULL);
6985
6986 checkSuspendOnAddEffectChain_l(chain);
6987
Eric Laurent1b928682014-10-02 19:41:47 -07006988 // make sure enabled pre processing effects state is communicated to the HAL as we
6989 // just moved them to a new input stream.
6990 chain->syncHalEffectsState();
6991
Eric Laurent81784c32012-11-19 14:55:58 -08006992 mEffectChains.add(chain);
6993
6994 return NO_ERROR;
6995}
6996
6997size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6998{
6999 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
7000 ALOGW_IF(mEffectChains.size() != 1,
7001 "removeEffectChain_l() %p invalid chain size %d on thread %p",
7002 chain.get(), mEffectChains.size(), this);
7003 if (mEffectChains.size() == 1) {
7004 mEffectChains.removeAt(0);
7005 }
7006 return 0;
7007}
7008
Eric Laurent1c333e22014-05-20 10:48:17 -07007009status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
7010 audio_patch_handle_t *handle)
7011{
7012 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007013
7014 // store new device and send to effects
7015 mInDevice = patch->sources[0].ext.device.type;
Eric Laurent296fb132015-05-01 11:38:42 -07007016 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07007017 for (size_t i = 0; i < mEffectChains.size(); i++) {
7018 mEffectChains[i]->setDevice_l(mInDevice);
7019 }
7020
7021 // disable AEC and NS if the device is a BT SCO headset supporting those
7022 // pre processings
7023 if (mTracks.size() > 0) {
7024 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7025 mAudioFlinger->btNrecIsOff();
7026 for (size_t i = 0; i < mTracks.size(); i++) {
7027 sp<RecordTrack> track = mTracks[i];
7028 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7029 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
7030 }
7031 }
7032
7033 // store new source and send to effects
7034 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7035 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07007036 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07007037 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07007038 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007039 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007040
Eric Laurent054d9d32015-04-24 08:48:48 -07007041 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007042 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
7043 status = hwDevice->create_audio_patch(hwDevice,
7044 patch->num_sources,
7045 patch->sources,
7046 patch->num_sinks,
7047 patch->sinks,
7048 handle);
7049 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007050 char *address;
7051 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
7052 address = audio_device_address_to_parameter(
7053 patch->sources[0].ext.device.type,
7054 patch->sources[0].ext.device.address);
7055 } else {
7056 address = (char *)calloc(1, 1);
7057 }
7058 AudioParameter param = AudioParameter(String8(address));
7059 free(address);
7060 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING),
7061 (int)patch->sources[0].ext.device.type);
7062 param.addInt(String8(AUDIO_PARAMETER_STREAM_INPUT_SOURCE),
7063 (int)patch->sinks[0].ext.mix.usecase.source);
7064 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7065 param.toString().string());
7066 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07007067 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007068
Eric Laurent296fb132015-05-01 11:38:42 -07007069 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
7070
Eric Laurent1c333e22014-05-20 10:48:17 -07007071 return status;
7072}
7073
7074status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
7075{
7076 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007077
7078 mInDevice = AUDIO_DEVICE_NONE;
7079
Eric Laurent1c333e22014-05-20 10:48:17 -07007080 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
7081 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
7082 status = hwDevice->release_audio_patch(hwDevice, handle);
7083 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007084 AudioParameter param;
7085 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
7086 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7087 param.toString().string());
Eric Laurent1c333e22014-05-20 10:48:17 -07007088 }
7089 return status;
7090}
7091
Eric Laurent83b88082014-06-20 18:31:16 -07007092void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
7093{
7094 Mutex::Autolock _l(mLock);
7095 mTracks.add(record);
7096}
7097
7098void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
7099{
7100 Mutex::Autolock _l(mLock);
7101 destroyTrack_l(record);
7102}
7103
7104void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
7105{
7106 ThreadBase::getAudioPortConfig(config);
7107 config->role = AUDIO_PORT_ROLE_SINK;
7108 config->ext.mix.hw_module = mInput->audioHwDev->handle();
7109 config->ext.mix.usecase.source = mAudioSource;
7110}
Eric Laurent1c333e22014-05-20 10:48:17 -07007111
Glenn Kasten63238ef2015-03-02 15:50:29 -08007112} // namespace android