blob: f5862919024da49885c707cd872faa29f8b1518f [file] [log] [blame]
Eric Laurent81784c32012-11-19 14:55:58 -08001/*
2**
3** Copyright 2012, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
Alex Ray371eb972012-11-30 11:11:54 -080021#define ATRACE_TAG ATRACE_TAG_AUDIO
Eric Laurent81784c32012-11-19 14:55:58 -080022
Glenn Kasten153b9fe2013-07-15 11:23:36 -070023#include "Configuration.h"
Eric Laurent81784c32012-11-19 14:55:58 -080024#include <math.h>
25#include <fcntl.h>
Glenn Kastenad8510a2015-02-17 16:24:07 -080026#include <linux/futex.h>
Eric Laurent81784c32012-11-19 14:55:58 -080027#include <sys/stat.h>
Glenn Kastenad8510a2015-02-17 16:24:07 -080028#include <sys/syscall.h>
Eric Laurent81784c32012-11-19 14:55:58 -080029#include <cutils/properties.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070030#include <media/AudioParameter.h>
Andy Hungcd044842014-08-07 11:04:34 -070031#include <media/AudioResamplerPublic.h>
Eric Laurent81784c32012-11-19 14:55:58 -080032#include <utils/Log.h>
Alex Ray371eb972012-11-30 11:11:54 -080033#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080034
35#include <private/media/AudioTrackShared.h>
36#include <hardware/audio.h>
37#include <audio_effects/effect_ns.h>
38#include <audio_effects/effect_aec.h>
39#include <audio_utils/primitives.h>
Andy Hung98ef9782014-03-04 14:46:50 -080040#include <audio_utils/format.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070041#include <audio_utils/minifloat.h>
Eric Laurent81784c32012-11-19 14:55:58 -080042
43// NBAIO implementations
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070044#include <media/nbaio/AudioStreamInSource.h>
Eric Laurent81784c32012-11-19 14:55:58 -080045#include <media/nbaio/AudioStreamOutSink.h>
46#include <media/nbaio/MonoPipe.h>
47#include <media/nbaio/MonoPipeReader.h>
48#include <media/nbaio/Pipe.h>
49#include <media/nbaio/PipeReader.h>
50#include <media/nbaio/SourceAudioBufferProvider.h>
51
52#include <powermanager/PowerManager.h>
53
54#include <common_time/cc_helper.h>
55#include <common_time/local_clock.h>
56
57#include "AudioFlinger.h"
58#include "AudioMixer.h"
Andy Hungd330ee42015-04-20 13:23:41 -070059#include "BufferProviders.h"
Eric Laurent81784c32012-11-19 14:55:58 -080060#include "FastMixer.h"
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070061#include "FastCapture.h"
Eric Laurent81784c32012-11-19 14:55:58 -080062#include "ServiceUtilities.h"
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -070063#include "mediautils/SchedulingPolicyService.h"
Eric Laurent81784c32012-11-19 14:55:58 -080064
Eric Laurent81784c32012-11-19 14:55:58 -080065#ifdef ADD_BATTERY_DATA
66#include <media/IMediaPlayerService.h>
67#include <media/IMediaDeathNotifier.h>
68#endif
69
Eric Laurent81784c32012-11-19 14:55:58 -080070#ifdef DEBUG_CPU_USAGE
71#include <cpustats/CentralTendencyStatistics.h>
72#include <cpustats/ThreadCpuUsage.h>
73#endif
74
75// ----------------------------------------------------------------------------
76
77// Note: the following macro is used for extremely verbose logging message. In
78// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
79// 0; but one side effect of this is to turn all LOGV's as well. Some messages
80// are so verbose that we want to suppress them even when we have ALOG_ASSERT
81// turned on. Do not uncomment the #def below unless you really know what you
82// are doing and want to see all of the extremely verbose messages.
83//#define VERY_VERY_VERBOSE_LOGGING
84#ifdef VERY_VERY_VERBOSE_LOGGING
85#define ALOGVV ALOGV
86#else
87#define ALOGVV(a...) do { } while(0)
88#endif
89
Andy Hung6770c6f2015-04-07 13:43:36 -070090// TODO: Move these macro/inlines to a header file.
Glenn Kasten49d00ad2014-07-21 11:22:03 -070091#define max(a, b) ((a) > (b) ? (a) : (b))
Andy Hung6770c6f2015-04-07 13:43:36 -070092template <typename T>
93static inline T min(const T& a, const T& b)
94{
95 return a < b ? a : b;
96}
Glenn Kasten49d00ad2014-07-21 11:22:03 -070097
Andy Hungd330ee42015-04-20 13:23:41 -070098#ifndef ARRAY_SIZE
99#define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
100#endif
101
Eric Laurent81784c32012-11-19 14:55:58 -0800102namespace android {
103
104// retry counts for buffer fill timeout
105// 50 * ~20msecs = 1 second
106static const int8_t kMaxTrackRetries = 50;
107static const int8_t kMaxTrackStartupRetries = 50;
108// allow less retry attempts on direct output thread.
109// direct outputs can be a scarce resource in audio hardware and should
110// be released as quickly as possible.
111static const int8_t kMaxTrackRetriesDirect = 2;
112
113// don't warn about blocked writes or record buffer overflows more often than this
114static const nsecs_t kWarningThrottleNs = seconds(5);
115
116// RecordThread loop sleep time upon application overrun or audio HAL read error
117static const int kRecordThreadSleepUs = 5000;
118
Eric Laurent10351942014-05-08 18:49:52 -0700119// maximum time to wait in sendConfigEvent_l() for a status to be received
120static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800121
122// minimum sleep time for the mixer thread loop when tracks are active but in underrun
123static const uint32_t kMinThreadSleepTimeUs = 5000;
124// maximum divider applied to the active sleep time in the mixer thread loop
125static const uint32_t kMaxThreadSleepTimeShift = 2;
126
Andy Hung09a50072014-02-27 14:30:47 -0800127// minimum normal sink buffer size, expressed in milliseconds rather than frames
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700128// FIXME This should be based on experimentally observed scheduling jitter
Andy Hung09a50072014-02-27 14:30:47 -0800129static const uint32_t kMinNormalSinkBufferSizeMs = 20;
130// maximum normal sink buffer size
131static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800132
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700133// minimum capture buffer size in milliseconds to _not_ need a fast capture thread
134// FIXME This should be based on experimentally observed scheduling jitter
135static const uint32_t kMinNormalCaptureBufferSizeMs = 12;
136
Eric Laurent972a1732013-09-04 09:42:59 -0700137// Offloaded output thread standby delay: allows track transition without going to standby
138static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
139
Eric Laurent81784c32012-11-19 14:55:58 -0800140// Whether to use fast mixer
141static const enum {
142 FastMixer_Never, // never initialize or use: for debugging only
143 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
144 // normal mixer multiplier is 1
145 FastMixer_Static, // initialize if needed, then use all the time if initialized,
146 // multiplier is calculated based on min & max normal mixer buffer size
147 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
148 // multiplier is calculated based on min & max normal mixer buffer size
149 // FIXME for FastMixer_Dynamic:
150 // Supporting this option will require fixing HALs that can't handle large writes.
151 // For example, one HAL implementation returns an error from a large write,
152 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
153 // We could either fix the HAL implementations, or provide a wrapper that breaks
154 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
155} kUseFastMixer = FastMixer_Static;
156
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700157// Whether to use fast capture
158static const enum {
159 FastCapture_Never, // never initialize or use: for debugging only
160 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
161 FastCapture_Static, // initialize if needed, then use all the time if initialized
162} kUseFastCapture = FastCapture_Static;
163
Eric Laurent81784c32012-11-19 14:55:58 -0800164// Priorities for requestPriority
165static const int kPriorityAudioApp = 2;
166static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700167static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800168
169// IAudioFlinger::createTrack() reports back to client the total size of shared memory area
170// for the track. The client then sub-divides this into smaller buffers for its use.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800171// Currently the client uses N-buffering by default, but doesn't tell us about the value of N.
172// So for now we just assume that client is double-buffered for fast tracks.
173// FIXME It would be better for client to tell AudioFlinger the value of N,
174// so AudioFlinger could allocate the right amount of memory.
Eric Laurent81784c32012-11-19 14:55:58 -0800175// See the client's minBufCount and mNotificationFramesAct calculations for details.
Glenn Kasten03490092014-05-27 12:30:54 -0700176
177// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800178static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800179
Glenn Kasten03490092014-05-27 12:30:54 -0700180// The minimum and maximum allowed values
181static const int kFastTrackMultiplierMin = 1;
182static const int kFastTrackMultiplierMax = 2;
183
184// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
185static int sFastTrackMultiplier = kFastTrackMultiplier;
186
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700187// See Thread::readOnlyHeap().
188// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
189// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
190// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Glenn Kasten9f81de32014-07-27 15:02:23 -0700191static const size_t kRecordThreadReadOnlyHeapSize = 0x2000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700192
Eric Laurent81784c32012-11-19 14:55:58 -0800193// ----------------------------------------------------------------------------
194
Glenn Kasten03490092014-05-27 12:30:54 -0700195static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
196
197static void sFastTrackMultiplierInit()
198{
199 char value[PROPERTY_VALUE_MAX];
200 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
201 char *endptr;
202 unsigned long ul = strtoul(value, &endptr, 0);
203 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
204 sFastTrackMultiplier = (int) ul;
205 }
206 }
207}
208
209// ----------------------------------------------------------------------------
210
Eric Laurent81784c32012-11-19 14:55:58 -0800211#ifdef ADD_BATTERY_DATA
212// To collect the amplifier usage
213static void addBatteryData(uint32_t params) {
214 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
215 if (service == NULL) {
216 // it already logged
217 return;
218 }
219
220 service->addBatteryData(params);
221}
222#endif
223
224
225// ----------------------------------------------------------------------------
226// CPU Stats
227// ----------------------------------------------------------------------------
228
229class CpuStats {
230public:
231 CpuStats();
232 void sample(const String8 &title);
233#ifdef DEBUG_CPU_USAGE
234private:
235 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
236 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
237
238 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
239
240 int mCpuNum; // thread's current CPU number
241 int mCpukHz; // frequency of thread's current CPU in kHz
242#endif
243};
244
245CpuStats::CpuStats()
246#ifdef DEBUG_CPU_USAGE
247 : mCpuNum(-1), mCpukHz(-1)
248#endif
249{
250}
251
Glenn Kasten0f11b512014-01-31 16:18:54 -0800252void CpuStats::sample(const String8 &title
253#ifndef DEBUG_CPU_USAGE
254 __unused
255#endif
256 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800257#ifdef DEBUG_CPU_USAGE
258 // get current thread's delta CPU time in wall clock ns
259 double wcNs;
260 bool valid = mCpuUsage.sampleAndEnable(wcNs);
261
262 // record sample for wall clock statistics
263 if (valid) {
264 mWcStats.sample(wcNs);
265 }
266
267 // get the current CPU number
268 int cpuNum = sched_getcpu();
269
270 // get the current CPU frequency in kHz
271 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
272
273 // check if either CPU number or frequency changed
274 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
275 mCpuNum = cpuNum;
276 mCpukHz = cpukHz;
277 // ignore sample for purposes of cycles
278 valid = false;
279 }
280
281 // if no change in CPU number or frequency, then record sample for cycle statistics
282 if (valid && mCpukHz > 0) {
283 double cycles = wcNs * cpukHz * 0.000001;
284 mHzStats.sample(cycles);
285 }
286
287 unsigned n = mWcStats.n();
288 // mCpuUsage.elapsed() is expensive, so don't call it every loop
289 if ((n & 127) == 1) {
290 long long elapsed = mCpuUsage.elapsed();
291 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
292 double perLoop = elapsed / (double) n;
293 double perLoop100 = perLoop * 0.01;
294 double perLoop1k = perLoop * 0.001;
295 double mean = mWcStats.mean();
296 double stddev = mWcStats.stddev();
297 double minimum = mWcStats.minimum();
298 double maximum = mWcStats.maximum();
299 double meanCycles = mHzStats.mean();
300 double stddevCycles = mHzStats.stddev();
301 double minCycles = mHzStats.minimum();
302 double maxCycles = mHzStats.maximum();
303 mCpuUsage.resetElapsed();
304 mWcStats.reset();
305 mHzStats.reset();
306 ALOGD("CPU usage for %s over past %.1f secs\n"
307 " (%u mixer loops at %.1f mean ms per loop):\n"
308 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
309 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
310 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
311 title.string(),
312 elapsed * .000000001, n, perLoop * .000001,
313 mean * .001,
314 stddev * .001,
315 minimum * .001,
316 maximum * .001,
317 mean / perLoop100,
318 stddev / perLoop100,
319 minimum / perLoop100,
320 maximum / perLoop100,
321 meanCycles / perLoop1k,
322 stddevCycles / perLoop1k,
323 minCycles / perLoop1k,
324 maxCycles / perLoop1k);
325
326 }
327 }
328#endif
329};
330
331// ----------------------------------------------------------------------------
332// ThreadBase
333// ----------------------------------------------------------------------------
334
Glenn Kasten97b7b752014-09-28 13:04:24 -0700335// static
336const char *AudioFlinger::ThreadBase::threadTypeToString(AudioFlinger::ThreadBase::type_t type)
337{
338 switch (type) {
339 case MIXER:
340 return "MIXER";
341 case DIRECT:
342 return "DIRECT";
343 case DUPLICATING:
344 return "DUPLICATING";
345 case RECORD:
346 return "RECORD";
347 case OFFLOAD:
348 return "OFFLOAD";
349 default:
350 return "unknown";
351 }
352}
353
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800354String8 devicesToString(audio_devices_t devices)
355{
356 static const struct mapping {
357 audio_devices_t mDevices;
358 const char * mString;
359 } mappingsOut[] = {
360 AUDIO_DEVICE_OUT_EARPIECE, "EARPIECE",
361 AUDIO_DEVICE_OUT_SPEAKER, "SPEAKER",
362 AUDIO_DEVICE_OUT_WIRED_HEADSET, "WIRED_HEADSET",
363 AUDIO_DEVICE_OUT_WIRED_HEADPHONE, "WIRED_HEADPHONE",
Glenn Kasten84d61ca2015-05-06 18:32:13 -0700364 AUDIO_DEVICE_OUT_BLUETOOTH_SCO, "BLUETOOTH_SCO",
365 AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET, "BLUETOOTH_SCO_HEADSET",
366 AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT, "BLUETOOTH_SCO_CARKIT",
367 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, "BLUETOOTH_A2DP",
368 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES, "BLUETOOTH_A2DP_HEADPHONES",
369 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER, "BLUETOOTH_A2DP_SPEAKER",
370 AUDIO_DEVICE_OUT_AUX_DIGITAL, "AUX_DIGITAL",
371 AUDIO_DEVICE_OUT_HDMI, "HDMI",
372 AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET, "ANLG_DOCK_HEADSET",
373 AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET, "DGTL_DOCK_HEADSET",
374 AUDIO_DEVICE_OUT_USB_ACCESSORY, "USB_ACCESSORY",
375 AUDIO_DEVICE_OUT_USB_DEVICE, "USB_DEVICE",
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800376 AUDIO_DEVICE_OUT_TELEPHONY_TX, "TELEPHONY_TX",
Glenn Kasten84d61ca2015-05-06 18:32:13 -0700377 AUDIO_DEVICE_OUT_LINE, "LINE",
378 AUDIO_DEVICE_OUT_HDMI_ARC, "HDMI_ARC",
379 AUDIO_DEVICE_OUT_SPDIF, "SPDIF",
380 AUDIO_DEVICE_OUT_FM, "FM",
381 AUDIO_DEVICE_OUT_AUX_LINE, "AUX_LINE",
382 AUDIO_DEVICE_OUT_SPEAKER_SAFE, "SPEAKER_SAFE",
Eric Laurentb9d73332015-06-30 17:09:20 -0700383 AUDIO_DEVICE_OUT_IP, "IP",
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800384 AUDIO_DEVICE_NONE, "NONE", // must be last
385 }, mappingsIn[] = {
Glenn Kasten84d61ca2015-05-06 18:32:13 -0700386 AUDIO_DEVICE_IN_COMMUNICATION, "COMMUNICATION",
387 AUDIO_DEVICE_IN_AMBIENT, "AMBIENT",
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800388 AUDIO_DEVICE_IN_BUILTIN_MIC, "BUILTIN_MIC",
Glenn Kasten84d61ca2015-05-06 18:32:13 -0700389 AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET, "BLUETOOTH_SCO_HEADSET",
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800390 AUDIO_DEVICE_IN_WIRED_HEADSET, "WIRED_HEADSET",
Glenn Kasten84d61ca2015-05-06 18:32:13 -0700391 AUDIO_DEVICE_IN_AUX_DIGITAL, "AUX_DIGITAL",
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800392 AUDIO_DEVICE_IN_VOICE_CALL, "VOICE_CALL",
Glenn Kasten84d61ca2015-05-06 18:32:13 -0700393 AUDIO_DEVICE_IN_TELEPHONY_RX, "TELEPHONY_RX",
394 AUDIO_DEVICE_IN_BACK_MIC, "BACK_MIC",
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800395 AUDIO_DEVICE_IN_REMOTE_SUBMIX, "REMOTE_SUBMIX",
Glenn Kasten84d61ca2015-05-06 18:32:13 -0700396 AUDIO_DEVICE_IN_ANLG_DOCK_HEADSET, "ANLG_DOCK_HEADSET",
397 AUDIO_DEVICE_IN_DGTL_DOCK_HEADSET, "DGTL_DOCK_HEADSET",
398 AUDIO_DEVICE_IN_USB_ACCESSORY, "USB_ACCESSORY",
399 AUDIO_DEVICE_IN_USB_DEVICE, "USB_DEVICE",
400 AUDIO_DEVICE_IN_FM_TUNER, "FM_TUNER",
401 AUDIO_DEVICE_IN_TV_TUNER, "TV_TUNER",
402 AUDIO_DEVICE_IN_LINE, "LINE",
403 AUDIO_DEVICE_IN_SPDIF, "SPDIF",
404 AUDIO_DEVICE_IN_BLUETOOTH_A2DP, "BLUETOOTH_A2DP",
405 AUDIO_DEVICE_IN_LOOPBACK, "LOOPBACK",
Eric Laurentb9d73332015-06-30 17:09:20 -0700406 AUDIO_DEVICE_IN_IP, "IP",
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800407 AUDIO_DEVICE_NONE, "NONE", // must be last
408 };
409 String8 result;
410 audio_devices_t allDevices = AUDIO_DEVICE_NONE;
411 const mapping *entry;
412 if (devices & AUDIO_DEVICE_BIT_IN) {
413 devices &= ~AUDIO_DEVICE_BIT_IN;
414 entry = mappingsIn;
415 } else {
416 entry = mappingsOut;
417 }
418 for ( ; entry->mDevices != AUDIO_DEVICE_NONE; entry++) {
419 allDevices = (audio_devices_t) (allDevices | entry->mDevices);
420 if (devices & entry->mDevices) {
421 if (!result.isEmpty()) {
422 result.append("|");
423 }
424 result.append(entry->mString);
425 }
426 }
427 if (devices & ~allDevices) {
428 if (!result.isEmpty()) {
429 result.append("|");
430 }
431 result.appendFormat("0x%X", devices & ~allDevices);
432 }
433 if (result.isEmpty()) {
434 result.append(entry->mString);
435 }
436 return result;
437}
438
439String8 inputFlagsToString(audio_input_flags_t flags)
440{
441 static const struct mapping {
442 audio_input_flags_t mFlag;
443 const char * mString;
444 } mappings[] = {
445 AUDIO_INPUT_FLAG_FAST, "FAST",
446 AUDIO_INPUT_FLAG_HW_HOTWORD, "HW_HOTWORD",
447 AUDIO_INPUT_FLAG_NONE, "NONE", // must be last
448 };
449 String8 result;
450 audio_input_flags_t allFlags = AUDIO_INPUT_FLAG_NONE;
451 const mapping *entry;
452 for (entry = mappings; entry->mFlag != AUDIO_INPUT_FLAG_NONE; entry++) {
453 allFlags = (audio_input_flags_t) (allFlags | entry->mFlag);
454 if (flags & entry->mFlag) {
455 if (!result.isEmpty()) {
456 result.append("|");
457 }
458 result.append(entry->mString);
459 }
460 }
461 if (flags & ~allFlags) {
462 if (!result.isEmpty()) {
463 result.append("|");
464 }
465 result.appendFormat("0x%X", flags & ~allFlags);
466 }
467 if (result.isEmpty()) {
468 result.append(entry->mString);
469 }
470 return result;
471}
472
473String8 outputFlagsToString(audio_output_flags_t flags)
Glenn Kasten97b7b752014-09-28 13:04:24 -0700474{
475 static const struct mapping {
476 audio_output_flags_t mFlag;
477 const char * mString;
478 } mappings[] = {
479 AUDIO_OUTPUT_FLAG_DIRECT, "DIRECT",
480 AUDIO_OUTPUT_FLAG_PRIMARY, "PRIMARY",
481 AUDIO_OUTPUT_FLAG_FAST, "FAST",
482 AUDIO_OUTPUT_FLAG_DEEP_BUFFER, "DEEP_BUFFER",
Glenn Kastendfb0e112015-02-18 14:33:39 -0800483 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD, "COMPRESS_OFFLOAD",
Glenn Kasten97b7b752014-09-28 13:04:24 -0700484 AUDIO_OUTPUT_FLAG_NON_BLOCKING, "NON_BLOCKING",
485 AUDIO_OUTPUT_FLAG_HW_AV_SYNC, "HW_AV_SYNC",
486 AUDIO_OUTPUT_FLAG_NONE, "NONE", // must be last
487 };
488 String8 result;
489 audio_output_flags_t allFlags = AUDIO_OUTPUT_FLAG_NONE;
490 const mapping *entry;
491 for (entry = mappings; entry->mFlag != AUDIO_OUTPUT_FLAG_NONE; entry++) {
492 allFlags = (audio_output_flags_t) (allFlags | entry->mFlag);
493 if (flags & entry->mFlag) {
494 if (!result.isEmpty()) {
495 result.append("|");
496 }
497 result.append(entry->mString);
498 }
499 }
500 if (flags & ~allFlags) {
501 if (!result.isEmpty()) {
502 result.append("|");
503 }
504 result.appendFormat("0x%X", flags & ~allFlags);
505 }
506 if (result.isEmpty()) {
507 result.append(entry->mString);
508 }
509 return result;
510}
511
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800512const char *sourceToString(audio_source_t source)
513{
514 switch (source) {
515 case AUDIO_SOURCE_DEFAULT: return "default";
516 case AUDIO_SOURCE_MIC: return "mic";
517 case AUDIO_SOURCE_VOICE_UPLINK: return "voice uplink";
518 case AUDIO_SOURCE_VOICE_DOWNLINK: return "voice downlink";
519 case AUDIO_SOURCE_VOICE_CALL: return "voice call";
520 case AUDIO_SOURCE_CAMCORDER: return "camcorder";
521 case AUDIO_SOURCE_VOICE_RECOGNITION: return "voice recognition";
522 case AUDIO_SOURCE_VOICE_COMMUNICATION: return "voice communication";
523 case AUDIO_SOURCE_REMOTE_SUBMIX: return "remote submix";
524 case AUDIO_SOURCE_FM_TUNER: return "FM tuner";
525 case AUDIO_SOURCE_HOTWORD: return "hotword";
526 default: return "unknown";
527 }
528}
529
Eric Laurent81784c32012-11-19 14:55:58 -0800530AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -0700531 audio_devices_t outDevice, audio_devices_t inDevice, type_t type, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -0800532 : Thread(false /*canCallJava*/),
533 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700534 mAudioFlinger(audioFlinger),
Glenn Kasten70949c42013-08-06 07:40:12 -0700535 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800536 // are set by PlaybackThread::readOutputParameters_l() or
537 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700538 //FIXME: mStandby should be true here. Is this some kind of hack?
Eric Laurent81784c32012-11-19 14:55:58 -0800539 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700540 mPrevOutDevice(AUDIO_DEVICE_NONE), mPrevInDevice(AUDIO_DEVICE_NONE),
541 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Eric Laurent81784c32012-11-19 14:55:58 -0800542 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700543 mDeathRecipient(new PMDeathRecipient(this)),
544 mSystemReady(systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -0800545{
Eric Laurent296fb132015-05-01 11:38:42 -0700546 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800547}
548
549AudioFlinger::ThreadBase::~ThreadBase()
550{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700551 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700552 mConfigEvents.clear();
553
Eric Laurent81784c32012-11-19 14:55:58 -0800554 // do not lock the mutex in destructor
555 releaseWakeLock_l();
556 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800557 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800558 binder->unlinkToDeath(mDeathRecipient);
559 }
560}
561
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700562status_t AudioFlinger::ThreadBase::readyToRun()
563{
564 status_t status = initCheck();
565 if (status == NO_ERROR) {
566 ALOGI("AudioFlinger's thread %p ready to run", this);
567 } else {
568 ALOGE("No working audio driver found.");
569 }
570 return status;
571}
572
Eric Laurent81784c32012-11-19 14:55:58 -0800573void AudioFlinger::ThreadBase::exit()
574{
575 ALOGV("ThreadBase::exit");
576 // do any cleanup required for exit to succeed
577 preExit();
578 {
579 // This lock prevents the following race in thread (uniprocessor for illustration):
580 // if (!exitPending()) {
581 // // context switch from here to exit()
582 // // exit() calls requestExit(), what exitPending() observes
583 // // exit() calls signal(), which is dropped since no waiters
584 // // context switch back from exit() to here
585 // mWaitWorkCV.wait(...);
586 // // now thread is hung
587 // }
588 AutoMutex lock(mLock);
589 requestExit();
590 mWaitWorkCV.broadcast();
591 }
592 // When Thread::requestExitAndWait is made virtual and this method is renamed to
593 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
594 requestExitAndWait();
595}
596
597status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
598{
599 status_t status;
600
601 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
602 Mutex::Autolock _l(mLock);
603
Eric Laurent10351942014-05-08 18:49:52 -0700604 return sendSetParameterConfigEvent_l(keyValuePairs);
605}
606
607// sendConfigEvent_l() must be called with ThreadBase::mLock held
608// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
609status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
610{
611 status_t status = NO_ERROR;
612
Eric Laurent72e3f392015-05-20 14:43:50 -0700613 if (event->mRequiresSystemReady && !mSystemReady) {
614 event->mWaitStatus = false;
615 mPendingConfigEvents.add(event);
616 return status;
617 }
Eric Laurent10351942014-05-08 18:49:52 -0700618 mConfigEvents.add(event);
619 ALOGV("sendConfigEvent_l() num events %d event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800620 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700621 mLock.unlock();
622 {
623 Mutex::Autolock _l(event->mLock);
624 while (event->mWaitStatus) {
625 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
626 event->mStatus = TIMED_OUT;
627 event->mWaitStatus = false;
628 }
629 }
630 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800631 }
Eric Laurent10351942014-05-08 18:49:52 -0700632 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800633 return status;
634}
635
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700636void AudioFlinger::ThreadBase::sendIoConfigEvent(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800637{
638 Mutex::Autolock _l(mLock);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700639 sendIoConfigEvent_l(event, pid);
Eric Laurent81784c32012-11-19 14:55:58 -0800640}
641
642// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700643void AudioFlinger::ThreadBase::sendIoConfigEvent_l(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800644{
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700645 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid);
Eric Laurent10351942014-05-08 18:49:52 -0700646 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800647}
648
Eric Laurent72e3f392015-05-20 14:43:50 -0700649void AudioFlinger::ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio)
650{
651 Mutex::Autolock _l(mLock);
652 sendPrioConfigEvent_l(pid, tid, prio);
653}
654
Eric Laurent81784c32012-11-19 14:55:58 -0800655// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
656void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
657{
Eric Laurent10351942014-05-08 18:49:52 -0700658 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio);
659 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800660}
661
Eric Laurent10351942014-05-08 18:49:52 -0700662// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
663status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800664{
Eric Laurent10351942014-05-08 18:49:52 -0700665 sp<ConfigEvent> configEvent = (ConfigEvent *)new SetParameterConfigEvent(keyValuePair);
666 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700667}
668
Eric Laurent1c333e22014-05-20 10:48:17 -0700669status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
670 const struct audio_patch *patch,
671 audio_patch_handle_t *handle)
672{
673 Mutex::Autolock _l(mLock);
674 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
675 status_t status = sendConfigEvent_l(configEvent);
676 if (status == NO_ERROR) {
677 CreateAudioPatchConfigEventData *data =
678 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
679 *handle = data->mHandle;
680 }
681 return status;
682}
683
684status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
685 const audio_patch_handle_t handle)
686{
687 Mutex::Autolock _l(mLock);
688 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
689 return sendConfigEvent_l(configEvent);
690}
691
692
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700693// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700694void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700695{
Eric Laurent10351942014-05-08 18:49:52 -0700696 bool configChanged = false;
697
Eric Laurent81784c32012-11-19 14:55:58 -0800698 while (!mConfigEvents.isEmpty()) {
Eric Laurent10351942014-05-08 18:49:52 -0700699 ALOGV("processConfigEvents_l() remaining events %d", mConfigEvents.size());
700 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800701 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700702 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700703 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700704 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
705 // FIXME Need to understand why this has to be done asynchronously
706 int err = requestPriority(data->mPid, data->mTid, data->mPrio,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700707 true /*asynchronous*/);
708 if (err != 0) {
709 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700710 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700711 }
712 } break;
713 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700714 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700715 ioConfigChanged(data->mEvent, data->mPid);
Eric Laurent10351942014-05-08 18:49:52 -0700716 } break;
717 case CFG_EVENT_SET_PARAMETER: {
718 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
719 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
720 configChanged = true;
Glenn Kastend5418eb2013-08-14 13:11:06 -0700721 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700722 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700723 case CFG_EVENT_CREATE_AUDIO_PATCH: {
724 CreateAudioPatchConfigEventData *data =
725 (CreateAudioPatchConfigEventData *)event->mData.get();
726 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
727 } break;
728 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
729 ReleaseAudioPatchConfigEventData *data =
730 (ReleaseAudioPatchConfigEventData *)event->mData.get();
731 event->mStatus = releaseAudioPatch_l(data->mHandle);
732 } break;
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700733 default:
Eric Laurent10351942014-05-08 18:49:52 -0700734 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700735 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800736 }
Eric Laurent10351942014-05-08 18:49:52 -0700737 {
738 Mutex::Autolock _l(event->mLock);
739 if (event->mWaitStatus) {
740 event->mWaitStatus = false;
741 event->mCond.signal();
742 }
743 }
744 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
745 }
746
747 if (configChanged) {
748 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800749 }
Eric Laurent81784c32012-11-19 14:55:58 -0800750}
751
Marco Nelissenb2208842014-02-07 14:00:50 -0800752String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
753 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700754 const audio_channel_representation_t representation =
755 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700756
757 switch (representation) {
758 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
759 if (output) {
760 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
761 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
762 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
763 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
764 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
765 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
766 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
767 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
768 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
769 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
770 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
771 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
772 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
773 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
774 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
775 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
776 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
777 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
778 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
779 } else {
780 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
781 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
782 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
783 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
784 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
785 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
786 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
787 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
788 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
789 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
790 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
791 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
792 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
793 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
794 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
795 }
796 const int len = s.length();
797 if (len > 2) {
798 char *str = s.lockBuffer(len); // needed?
799 s.unlockBuffer(len - 2); // remove trailing ", "
800 }
801 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800802 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700803 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
804 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
805 return s;
806 default:
807 s.appendFormat("unknown mask, representation:%d bits:%#x",
808 representation, audio_channel_mask_get_bits(mask));
809 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800810 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800811}
812
Glenn Kasten0f11b512014-01-31 16:18:54 -0800813void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800814{
815 const size_t SIZE = 256;
816 char buffer[SIZE];
817 String8 result;
818
819 bool locked = AudioFlinger::dumpTryLock(mLock);
820 if (!locked) {
Glenn Kasten97b7b752014-09-28 13:04:24 -0700821 dprintf(fd, "thread %p may be deadlocked\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -0800822 }
823
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800824 dprintf(fd, " Thread name: %s\n", mThreadName);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700825 dprintf(fd, " I/O handle: %d\n", mId);
826 dprintf(fd, " TID: %d\n", getTid());
827 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700828 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700829 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700830 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat));
Elliott Hughes87cebad2014-05-22 10:14:43 -0700831 dprintf(fd, " HAL buffer size: %u bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700832 dprintf(fd, " Channel count: %u\n", mChannelCount);
833 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800834 channelMaskToString(mChannelMask, mType != RECORD).string());
Glenn Kasten97b7b752014-09-28 13:04:24 -0700835 dprintf(fd, " Format: 0x%x (%s)\n", mFormat, formatToString(mFormat));
836 dprintf(fd, " Frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700837 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800838 size_t numConfig = mConfigEvents.size();
839 if (numConfig) {
840 for (size_t i = 0; i < numConfig; i++) {
841 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700842 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800843 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700844 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800845 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700846 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800847 }
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800848 dprintf(fd, " Output device: %#x (%s)\n", mOutDevice, devicesToString(mOutDevice).string());
849 dprintf(fd, " Input device: %#x (%s)\n", mInDevice, devicesToString(mInDevice).string());
850 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, sourceToString(mAudioSource));
Eric Laurent81784c32012-11-19 14:55:58 -0800851
852 if (locked) {
853 mLock.unlock();
854 }
855}
856
857void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
858{
859 const size_t SIZE = 256;
860 char buffer[SIZE];
861 String8 result;
862
Marco Nelissenb2208842014-02-07 14:00:50 -0800863 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000864 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800865 write(fd, buffer, strlen(buffer));
866
Marco Nelissenb2208842014-02-07 14:00:50 -0800867 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800868 sp<EffectChain> chain = mEffectChains[i];
869 if (chain != 0) {
870 chain->dump(fd, args);
871 }
872 }
873}
874
Marco Nelissene14a5d62013-10-03 08:51:24 -0700875void AudioFlinger::ThreadBase::acquireWakeLock(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800876{
877 Mutex::Autolock _l(mLock);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700878 acquireWakeLock_l(uid);
Eric Laurent81784c32012-11-19 14:55:58 -0800879}
880
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100881String16 AudioFlinger::ThreadBase::getWakeLockTag()
882{
883 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -0800884 case MIXER:
885 return String16("AudioMix");
886 case DIRECT:
887 return String16("AudioDirectOut");
888 case DUPLICATING:
889 return String16("AudioDup");
890 case RECORD:
891 return String16("AudioIn");
892 case OFFLOAD:
893 return String16("AudioOffload");
894 default:
895 ALOG_ASSERT(false);
896 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100897 }
898}
899
Marco Nelissene14a5d62013-10-03 08:51:24 -0700900void AudioFlinger::ThreadBase::acquireWakeLock_l(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800901{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800902 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800903 if (mPowerManager != 0) {
904 sp<IBinder> binder = new BBinder();
Marco Nelissene14a5d62013-10-03 08:51:24 -0700905 status_t status;
906 if (uid >= 0) {
Eric Laurent547789d2013-10-04 11:46:55 -0700907 status = mPowerManager->acquireWakeLockWithUid(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700908 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100909 getWakeLockTag(),
Marco Nelissene14a5d62013-10-03 08:51:24 -0700910 String16("media"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700911 uid,
912 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700913 } else {
Eric Laurent547789d2013-10-04 11:46:55 -0700914 status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700915 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100916 getWakeLockTag(),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700917 String16("media"),
918 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700919 }
Eric Laurent81784c32012-11-19 14:55:58 -0800920 if (status == NO_ERROR) {
921 mWakeLockToken = binder;
922 }
Glenn Kastend7dca052015-03-05 16:05:54 -0800923 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Eric Laurent81784c32012-11-19 14:55:58 -0800924 }
925}
926
927void AudioFlinger::ThreadBase::releaseWakeLock()
928{
929 Mutex::Autolock _l(mLock);
930 releaseWakeLock_l();
931}
932
933void AudioFlinger::ThreadBase::releaseWakeLock_l()
934{
935 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800936 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -0800937 if (mPowerManager != 0) {
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700938 mPowerManager->releaseWakeLock(mWakeLockToken, 0,
939 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800940 }
941 mWakeLockToken.clear();
942 }
943}
944
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800945void AudioFlinger::ThreadBase::updateWakeLockUids(const SortedVector<int> &uids) {
946 Mutex::Autolock _l(mLock);
947 updateWakeLockUids_l(uids);
948}
949
950void AudioFlinger::ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -0700951 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800952 // use checkService() to avoid blocking if power service is not up yet
953 sp<IBinder> binder =
954 defaultServiceManager()->checkService(String16("power"));
955 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800956 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800957 } else {
958 mPowerManager = interface_cast<IPowerManager>(binder);
959 binder->linkToDeath(mDeathRecipient);
960 }
961 }
962}
963
964void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<int> &uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800965 getPowerManager_l();
966 if (mWakeLockToken == NULL) {
967 ALOGE("no wake lock to update!");
968 return;
969 }
970 if (mPowerManager != 0) {
971 sp<IBinder> binder = new BBinder();
972 status_t status;
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700973 status = mPowerManager->updateWakeLockUids(mWakeLockToken, uids.size(), uids.array(),
974 true /* FIXME force oneway contrary to .aidl */);
Glenn Kastend7dca052015-03-05 16:05:54 -0800975 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800976 }
977}
978
Eric Laurent81784c32012-11-19 14:55:58 -0800979void AudioFlinger::ThreadBase::clearPowerManager()
980{
981 Mutex::Autolock _l(mLock);
982 releaseWakeLock_l();
983 mPowerManager.clear();
984}
985
Glenn Kasten0f11b512014-01-31 16:18:54 -0800986void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800987{
988 sp<ThreadBase> thread = mThread.promote();
989 if (thread != 0) {
990 thread->clearPowerManager();
991 }
992 ALOGW("power manager service died !!!");
993}
994
995void AudioFlinger::ThreadBase::setEffectSuspended(
996 const effect_uuid_t *type, bool suspend, int sessionId)
997{
998 Mutex::Autolock _l(mLock);
999 setEffectSuspended_l(type, suspend, sessionId);
1000}
1001
1002void AudioFlinger::ThreadBase::setEffectSuspended_l(
1003 const effect_uuid_t *type, bool suspend, int sessionId)
1004{
1005 sp<EffectChain> chain = getEffectChain_l(sessionId);
1006 if (chain != 0) {
1007 if (type != NULL) {
1008 chain->setEffectSuspended_l(type, suspend);
1009 } else {
1010 chain->setEffectSuspendedAll_l(suspend);
1011 }
1012 }
1013
1014 updateSuspendedSessions_l(type, suspend, sessionId);
1015}
1016
1017void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1018{
1019 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1020 if (index < 0) {
1021 return;
1022 }
1023
1024 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1025 mSuspendedSessions.valueAt(index);
1026
1027 for (size_t i = 0; i < sessionEffects.size(); i++) {
1028 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
1029 for (int j = 0; j < desc->mRefCount; j++) {
1030 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1031 chain->setEffectSuspendedAll_l(true);
1032 } else {
1033 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1034 desc->mType.timeLow);
1035 chain->setEffectSuspended_l(&desc->mType, true);
1036 }
1037 }
1038 }
1039}
1040
1041void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1042 bool suspend,
1043 int sessionId)
1044{
1045 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1046
1047 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1048
1049 if (suspend) {
1050 if (index >= 0) {
1051 sessionEffects = mSuspendedSessions.valueAt(index);
1052 } else {
1053 mSuspendedSessions.add(sessionId, sessionEffects);
1054 }
1055 } else {
1056 if (index < 0) {
1057 return;
1058 }
1059 sessionEffects = mSuspendedSessions.valueAt(index);
1060 }
1061
1062
1063 int key = EffectChain::kKeyForSuspendAll;
1064 if (type != NULL) {
1065 key = type->timeLow;
1066 }
1067 index = sessionEffects.indexOfKey(key);
1068
1069 sp<SuspendedSessionDesc> desc;
1070 if (suspend) {
1071 if (index >= 0) {
1072 desc = sessionEffects.valueAt(index);
1073 } else {
1074 desc = new SuspendedSessionDesc();
1075 if (type != NULL) {
1076 desc->mType = *type;
1077 }
1078 sessionEffects.add(key, desc);
1079 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1080 }
1081 desc->mRefCount++;
1082 } else {
1083 if (index < 0) {
1084 return;
1085 }
1086 desc = sessionEffects.valueAt(index);
1087 if (--desc->mRefCount == 0) {
1088 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1089 sessionEffects.removeItemsAt(index);
1090 if (sessionEffects.isEmpty()) {
1091 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1092 sessionId);
1093 mSuspendedSessions.removeItem(sessionId);
1094 }
1095 }
1096 }
1097 if (!sessionEffects.isEmpty()) {
1098 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1099 }
1100}
1101
1102void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1103 bool enabled,
1104 int sessionId)
1105{
1106 Mutex::Autolock _l(mLock);
1107 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1108}
1109
1110void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1111 bool enabled,
1112 int sessionId)
1113{
1114 if (mType != RECORD) {
1115 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1116 // another session. This gives the priority to well behaved effect control panels
1117 // and applications not using global effects.
1118 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1119 // global effects
1120 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
1121 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1122 }
1123 }
1124
1125 sp<EffectChain> chain = getEffectChain_l(sessionId);
1126 if (chain != 0) {
1127 chain->checkSuspendOnEffectEnabled(effect, enabled);
1128 }
1129}
1130
1131// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1132sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1133 const sp<AudioFlinger::Client>& client,
1134 const sp<IEffectClient>& effectClient,
1135 int32_t priority,
1136 int sessionId,
1137 effect_descriptor_t *desc,
1138 int *enabled,
Glenn Kasten9156ef32013-08-06 15:39:08 -07001139 status_t *status)
Eric Laurent81784c32012-11-19 14:55:58 -08001140{
1141 sp<EffectModule> effect;
1142 sp<EffectHandle> handle;
1143 status_t lStatus;
1144 sp<EffectChain> chain;
1145 bool chainCreated = false;
1146 bool effectCreated = false;
1147 bool effectRegistered = false;
1148
1149 lStatus = initCheck();
1150 if (lStatus != NO_ERROR) {
1151 ALOGW("createEffect_l() Audio driver not initialized.");
1152 goto Exit;
1153 }
1154
Andy Hung98ef9782014-03-04 14:46:50 -08001155 // Reject any effect on Direct output threads for now, since the format of
1156 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1157 if (mType == DIRECT) {
1158 ALOGW("createEffect_l() Cannot add effect %s on Direct output type thread %s",
Glenn Kastend7dca052015-03-05 16:05:54 -08001159 desc->name, mThreadName);
Andy Hung98ef9782014-03-04 14:46:50 -08001160 lStatus = BAD_VALUE;
1161 goto Exit;
1162 }
1163
Andy Hung389cfdb2014-08-07 17:49:53 -07001164 // Reject any effect on mixer or duplicating multichannel sinks.
Andy Hung9a592762014-07-21 21:56:01 -07001165 // TODO: fix both format and multichannel issues with effects.
Andy Hung389cfdb2014-08-07 17:49:53 -07001166 if ((mType == MIXER || mType == DUPLICATING) && mChannelCount != FCC_2) {
1167 ALOGW("createEffect_l() Cannot add effect %s for multichannel(%d) %s threads",
1168 desc->name, mChannelCount, mType == MIXER ? "MIXER" : "DUPLICATING");
Andy Hung9a592762014-07-21 21:56:01 -07001169 lStatus = BAD_VALUE;
1170 goto Exit;
1171 }
1172
Eric Laurent5baf2af2013-09-12 17:37:00 -07001173 // Allow global effects only on offloaded and mixer threads
1174 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1175 switch (mType) {
1176 case MIXER:
1177 case OFFLOAD:
1178 break;
1179 case DIRECT:
1180 case DUPLICATING:
1181 case RECORD:
1182 default:
Glenn Kastend7dca052015-03-05 16:05:54 -08001183 ALOGW("createEffect_l() Cannot add global effect %s on thread %s",
1184 desc->name, mThreadName);
Eric Laurent5baf2af2013-09-12 17:37:00 -07001185 lStatus = BAD_VALUE;
1186 goto Exit;
1187 }
Eric Laurent81784c32012-11-19 14:55:58 -08001188 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07001189
Eric Laurent81784c32012-11-19 14:55:58 -08001190 // Only Pre processor effects are allowed on input threads and only on input threads
1191 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
1192 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
1193 desc->name, desc->flags, mType);
1194 lStatus = BAD_VALUE;
1195 goto Exit;
1196 }
1197
1198 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1199
1200 { // scope for mLock
1201 Mutex::Autolock _l(mLock);
1202
1203 // check for existing effect chain with the requested audio session
1204 chain = getEffectChain_l(sessionId);
1205 if (chain == 0) {
1206 // create a new chain for this session
1207 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1208 chain = new EffectChain(this, sessionId);
1209 addEffectChain_l(chain);
1210 chain->setStrategy(getStrategyForSession_l(sessionId));
1211 chainCreated = true;
1212 } else {
1213 effect = chain->getEffectFromDesc_l(desc);
1214 }
1215
1216 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1217
1218 if (effect == 0) {
1219 int id = mAudioFlinger->nextUniqueId();
1220 // Check CPU and memory usage
1221 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
1222 if (lStatus != NO_ERROR) {
1223 goto Exit;
1224 }
1225 effectRegistered = true;
1226 // create a new effect module if none present in the chain
1227 effect = new EffectModule(this, chain, desc, id, sessionId);
1228 lStatus = effect->status();
1229 if (lStatus != NO_ERROR) {
1230 goto Exit;
1231 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07001232 effect->setOffloaded(mType == OFFLOAD, mId);
1233
Eric Laurent81784c32012-11-19 14:55:58 -08001234 lStatus = chain->addEffect_l(effect);
1235 if (lStatus != NO_ERROR) {
1236 goto Exit;
1237 }
1238 effectCreated = true;
1239
1240 effect->setDevice(mOutDevice);
1241 effect->setDevice(mInDevice);
1242 effect->setMode(mAudioFlinger->getMode());
1243 effect->setAudioSource(mAudioSource);
1244 }
1245 // create effect handle and connect it to effect module
1246 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001247 lStatus = handle->initCheck();
1248 if (lStatus == OK) {
1249 lStatus = effect->addHandle(handle.get());
1250 }
Eric Laurent81784c32012-11-19 14:55:58 -08001251 if (enabled != NULL) {
1252 *enabled = (int)effect->isEnabled();
1253 }
1254 }
1255
1256Exit:
1257 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1258 Mutex::Autolock _l(mLock);
1259 if (effectCreated) {
1260 chain->removeEffect_l(effect);
1261 }
1262 if (effectRegistered) {
1263 AudioSystem::unregisterEffect(effect->id());
1264 }
1265 if (chainCreated) {
1266 removeEffectChain_l(chain);
1267 }
1268 handle.clear();
1269 }
1270
Glenn Kasten9156ef32013-08-06 15:39:08 -07001271 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001272 return handle;
1273}
1274
1275sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
1276{
1277 Mutex::Autolock _l(mLock);
1278 return getEffect_l(sessionId, effectId);
1279}
1280
1281sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
1282{
1283 sp<EffectChain> chain = getEffectChain_l(sessionId);
1284 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1285}
1286
1287// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1288// PlaybackThread::mLock held
1289status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1290{
1291 // check for existing effect chain with the requested audio session
1292 int sessionId = effect->sessionId();
1293 sp<EffectChain> chain = getEffectChain_l(sessionId);
1294 bool chainCreated = false;
1295
Eric Laurent5baf2af2013-09-12 17:37:00 -07001296 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
1297 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
1298 this, effect->desc().name, effect->desc().flags);
1299
Eric Laurent81784c32012-11-19 14:55:58 -08001300 if (chain == 0) {
1301 // create a new chain for this session
1302 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1303 chain = new EffectChain(this, sessionId);
1304 addEffectChain_l(chain);
1305 chain->setStrategy(getStrategyForSession_l(sessionId));
1306 chainCreated = true;
1307 }
1308 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1309
1310 if (chain->getEffectFromId_l(effect->id()) != 0) {
1311 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1312 this, effect->desc().name, chain.get());
1313 return BAD_VALUE;
1314 }
1315
Eric Laurent5baf2af2013-09-12 17:37:00 -07001316 effect->setOffloaded(mType == OFFLOAD, mId);
1317
Eric Laurent81784c32012-11-19 14:55:58 -08001318 status_t status = chain->addEffect_l(effect);
1319 if (status != NO_ERROR) {
1320 if (chainCreated) {
1321 removeEffectChain_l(chain);
1322 }
1323 return status;
1324 }
1325
1326 effect->setDevice(mOutDevice);
1327 effect->setDevice(mInDevice);
1328 effect->setMode(mAudioFlinger->getMode());
1329 effect->setAudioSource(mAudioSource);
1330 return NO_ERROR;
1331}
1332
1333void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
1334
1335 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
1336 effect_descriptor_t desc = effect->desc();
1337 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1338 detachAuxEffect_l(effect->id());
1339 }
1340
1341 sp<EffectChain> chain = effect->chain().promote();
1342 if (chain != 0) {
1343 // remove effect chain if removing last effect
1344 if (chain->removeEffect_l(effect) == 0) {
1345 removeEffectChain_l(chain);
1346 }
1347 } else {
1348 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1349 }
1350}
1351
1352void AudioFlinger::ThreadBase::lockEffectChains_l(
1353 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1354{
1355 effectChains = mEffectChains;
1356 for (size_t i = 0; i < mEffectChains.size(); i++) {
1357 mEffectChains[i]->lock();
1358 }
1359}
1360
1361void AudioFlinger::ThreadBase::unlockEffectChains(
1362 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1363{
1364 for (size_t i = 0; i < effectChains.size(); i++) {
1365 effectChains[i]->unlock();
1366 }
1367}
1368
1369sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
1370{
1371 Mutex::Autolock _l(mLock);
1372 return getEffectChain_l(sessionId);
1373}
1374
1375sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const
1376{
1377 size_t size = mEffectChains.size();
1378 for (size_t i = 0; i < size; i++) {
1379 if (mEffectChains[i]->sessionId() == sessionId) {
1380 return mEffectChains[i];
1381 }
1382 }
1383 return 0;
1384}
1385
1386void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1387{
1388 Mutex::Autolock _l(mLock);
1389 size_t size = mEffectChains.size();
1390 for (size_t i = 0; i < size; i++) {
1391 mEffectChains[i]->setMode_l(mode);
1392 }
1393}
1394
Eric Laurent83b88082014-06-20 18:31:16 -07001395void AudioFlinger::ThreadBase::getAudioPortConfig(struct audio_port_config *config)
1396{
1397 config->type = AUDIO_PORT_TYPE_MIX;
1398 config->ext.mix.handle = mId;
1399 config->sample_rate = mSampleRate;
1400 config->format = mFormat;
1401 config->channel_mask = mChannelMask;
1402 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1403 AUDIO_PORT_CONFIG_FORMAT;
1404}
1405
Eric Laurent72e3f392015-05-20 14:43:50 -07001406void AudioFlinger::ThreadBase::systemReady()
1407{
1408 Mutex::Autolock _l(mLock);
1409 if (mSystemReady) {
1410 return;
1411 }
1412 mSystemReady = true;
1413
1414 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1415 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1416 }
1417 mPendingConfigEvents.clear();
1418}
1419
Eric Laurent83b88082014-06-20 18:31:16 -07001420
Eric Laurent81784c32012-11-19 14:55:58 -08001421// ----------------------------------------------------------------------------
1422// Playback
1423// ----------------------------------------------------------------------------
1424
1425AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1426 AudioStreamOut* output,
1427 audio_io_handle_t id,
1428 audio_devices_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07001429 type_t type,
1430 bool systemReady)
1431 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type, systemReady),
Andy Hung2098f272014-02-27 14:00:06 -08001432 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001433 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001434 mMixerBuffer(NULL),
1435 mMixerBufferSize(0),
1436 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1437 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001438 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001439 mEffectBuffer(NULL),
1440 mEffectBufferSize(0),
1441 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1442 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001443 mSuspended(0), mBytesWritten(0),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001444 mActiveTracksGeneration(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001445 // mStreamTypes[] initialized in constructor body
1446 mOutput(output),
1447 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
1448 mMixerStatus(MIXER_IDLE),
1449 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001450 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001451 mBytesRemaining(0),
1452 mCurrentWriteLength(0),
1453 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001454 mWriteAckSequence(0),
1455 mDrainSequence(0),
Eric Laurentede6c3b2013-09-19 14:37:46 -07001456 mSignalPending(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001457 mScreenState(AudioFlinger::mScreenState),
1458 // index 0 is reserved for normal mixer's submix
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001459 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1),
Eric Laurentd1f69b02014-12-15 14:33:13 -08001460 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001461 // mLatchD, mLatchQ,
1462 mLatchDValid(false), mLatchQValid(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001463{
Glenn Kastend7dca052015-03-05 16:05:54 -08001464 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1465 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001466
1467 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1468 // it would be safer to explicitly pass initial masterVolume/masterMute as
1469 // parameter.
1470 //
1471 // If the HAL we are using has support for master volume or master mute,
1472 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1473 // and the mute set to false).
1474 mMasterVolume = audioFlinger->masterVolume_l();
1475 mMasterMute = audioFlinger->masterMute_l();
1476 if (mOutput && mOutput->audioHwDev) {
1477 if (mOutput->audioHwDev->canSetMasterVolume()) {
1478 mMasterVolume = 1.0;
1479 }
1480
1481 if (mOutput->audioHwDev->canSetMasterMute()) {
1482 mMasterMute = false;
1483 }
1484 }
1485
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001486 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001487
Eric Laurent223fd5c2014-11-11 13:43:36 -08001488 // ++ operator does not compile
Glenn Kasten66e46352014-01-16 17:44:23 -08001489 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001490 stream = (audio_stream_type_t) (stream + 1)) {
1491 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1492 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1493 }
Eric Laurent81784c32012-11-19 14:55:58 -08001494}
1495
1496AudioFlinger::PlaybackThread::~PlaybackThread()
1497{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001498 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001499 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001500 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001501 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001502}
1503
1504void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1505{
1506 dumpInternals(fd, args);
1507 dumpTracks(fd, args);
1508 dumpEffectChains(fd, args);
1509}
1510
Glenn Kasten0f11b512014-01-31 16:18:54 -08001511void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001512{
1513 const size_t SIZE = 256;
1514 char buffer[SIZE];
1515 String8 result;
1516
Marco Nelissenb2208842014-02-07 14:00:50 -08001517 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001518 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1519 const stream_type_t *st = &mStreamTypes[i];
1520 if (i > 0) {
1521 result.appendFormat(", ");
1522 }
1523 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1524 if (st->mute) {
1525 result.append("M");
1526 }
1527 }
1528 result.append("\n");
1529 write(fd, result.string(), result.length());
1530 result.clear();
1531
Eric Laurent81784c32012-11-19 14:55:58 -08001532 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1533 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001534 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001535 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001536
1537 size_t numtracks = mTracks.size();
1538 size_t numactive = mActiveTracks.size();
Elliott Hughes87cebad2014-05-22 10:14:43 -07001539 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001540 size_t numactiveseen = 0;
1541 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07001542 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08001543 Track::appendDumpHeader(result);
1544 for (size_t i = 0; i < numtracks; ++i) {
1545 sp<Track> track = mTracks[i];
1546 if (track != 0) {
1547 bool active = mActiveTracks.indexOf(track) >= 0;
1548 if (active) {
1549 numactiveseen++;
1550 }
1551 track->dump(buffer, SIZE, active);
1552 result.append(buffer);
1553 }
1554 }
1555 } else {
1556 result.append("\n");
1557 }
1558 if (numactiveseen != numactive) {
1559 // some tracks in the active list were not in the tracks list
1560 snprintf(buffer, SIZE, " The following tracks are in the active list but"
1561 " not in the track list\n");
1562 result.append(buffer);
1563 Track::appendDumpHeader(result);
1564 for (size_t i = 0; i < numactive; ++i) {
1565 sp<Track> track = mActiveTracks[i].promote();
1566 if (track != 0 && mTracks.indexOf(track) < 0) {
1567 track->dump(buffer, SIZE, true);
1568 result.append(buffer);
1569 }
1570 }
1571 }
1572
1573 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001574}
1575
1576void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1577{
Glenn Kasten97b7b752014-09-28 13:04:24 -07001578 dprintf(fd, "\nOutput thread %p type %d (%s):\n", this, type(), threadTypeToString(type()));
Glenn Kasten44182c22015-03-05 17:12:23 -08001579
1580 dumpBase(fd, args);
1581
Elliott Hughes87cebad2014-05-22 10:14:43 -07001582 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
1583 dprintf(fd, " Last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1584 dprintf(fd, " Total writes: %d\n", mNumWrites);
1585 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1586 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1587 dprintf(fd, " Suspend count: %d\n", mSuspended);
1588 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1589 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1590 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1591 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001592 AudioStreamOut *output = mOutput;
1593 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
1594 String8 flagsAsString = outputFlagsToString(flags);
1595 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n", output, flags, flagsAsString.string());
Eric Laurent81784c32012-11-19 14:55:58 -08001596}
1597
1598// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001599
1600void AudioFlinger::PlaybackThread::onFirstRef()
1601{
Glenn Kastend7dca052015-03-05 16:05:54 -08001602 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001603}
1604
1605// ThreadBase virtuals
1606void AudioFlinger::PlaybackThread::preExit()
1607{
1608 ALOGV(" preExit()");
1609 // FIXME this is using hard-coded strings but in the future, this functionality will be
1610 // converted to use audio HAL extensions required to support tunneling
1611 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1612}
1613
1614// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1615sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1616 const sp<AudioFlinger::Client>& client,
1617 audio_stream_type_t streamType,
1618 uint32_t sampleRate,
1619 audio_format_t format,
1620 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001621 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001622 const sp<IMemory>& sharedBuffer,
1623 int sessionId,
1624 IAudioFlinger::track_flags_t *flags,
1625 pid_t tid,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001626 int uid,
Eric Laurent81784c32012-11-19 14:55:58 -08001627 status_t *status)
1628{
Glenn Kasten74935e42013-12-19 08:56:45 -08001629 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001630 sp<Track> track;
1631 status_t lStatus;
1632
1633 bool isTimed = (*flags & IAudioFlinger::TRACK_TIMED) != 0;
1634
1635 // client expresses a preference for FAST, but we get the final say
1636 if (*flags & IAudioFlinger::TRACK_FAST) {
1637 if (
1638 // not timed
1639 (!isTimed) &&
1640 // either of these use cases:
1641 (
1642 // use case 1: shared buffer with any frame count
1643 (
1644 (sharedBuffer != 0)
1645 ) ||
Glenn Kasten1dfe2f92015-03-09 12:03:14 -07001646 // use case 2: frame count is default or at least as large as HAL
Eric Laurent81784c32012-11-19 14:55:58 -08001647 (
Glenn Kasten1dfe2f92015-03-09 12:03:14 -07001648 // we formerly checked for a callback handler (non-0 tid),
1649 // but that is no longer required for TRANSFER_OBTAIN mode
Eric Laurent81784c32012-11-19 14:55:58 -08001650 ((frameCount == 0) ||
Glenn Kastenb5fed682013-12-03 09:06:43 -08001651 (frameCount >= mFrameCount))
Eric Laurent81784c32012-11-19 14:55:58 -08001652 )
1653 ) &&
1654 // PCM data
1655 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07001656 // TODO: extract as a data library function that checks that a computationally
1657 // expensive downmixer is not required: isFastOutputChannelConversion()
Andy Hung9a592762014-07-21 21:56:01 -07001658 (channelMask == mChannelMask ||
Andy Hung1f439e12015-05-19 12:57:41 -07001659 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
1660 (channelMask == AUDIO_CHANNEL_OUT_MONO
1661 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001662 // hardware sample rate
1663 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001664 // normal mixer has an associated fast mixer
1665 hasFastMixer() &&
1666 // there are sufficient fast track slots available
1667 (mFastTrackAvailMask != 0)
1668 // FIXME test that MixerThread for this fast track has a capable output HAL
1669 // FIXME add a permission test also?
1670 ) {
1671 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1672 if (frameCount == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001673 // read the fast track multiplier property the first time it is needed
1674 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1675 if (ok != 0) {
1676 ALOGE("%s pthread_once failed: %d", __func__, ok);
1677 }
1678 frameCount = mFrameCount * sFastTrackMultiplier;
Eric Laurent81784c32012-11-19 14:55:58 -08001679 }
1680 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
1681 frameCount, mFrameCount);
1682 } else {
1683 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
Andy Hung6146c082014-03-18 11:56:15 -07001684 "mFrameCount=%d format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
1685 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001686 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Andy Hung6146c082014-03-18 11:56:15 -07001687 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001688 audio_is_linear_pcm(format),
1689 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
1690 *flags &= ~IAudioFlinger::TRACK_FAST;
Andy Hung0e48d252015-01-26 11:43:15 -08001691 }
1692 }
1693 // For normal PCM streaming tracks, update minimum frame count.
1694 // For compatibility with AudioTrack calculation, buffer depth is forced
1695 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1696 // This is probably too conservative, but legacy application code may depend on it.
1697 // If you change this calculation, also review the start threshold which is related.
1698 if (!(*flags & IAudioFlinger::TRACK_FAST)
1699 && audio_is_linear_pcm(format) && sharedBuffer == 0) {
Andy Hung8edb8dc2015-03-26 19:13:55 -07001700 // this must match AudioTrack.cpp calculateMinFrameCount().
1701 // TODO: Move to a common library
Eric Laurent81784c32012-11-19 14:55:58 -08001702 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1703 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1704 if (minBufCount < 2) {
1705 minBufCount = 2;
1706 }
Andy Hung8edb8dc2015-03-26 19:13:55 -07001707 // For normal mixing tracks, if speed is > 1.0f (normal), AudioTrack
1708 // or the client should compute and pass in a larger buffer request.
Andy Hung0e48d252015-01-26 11:43:15 -08001709 size_t minFrameCount =
Andy Hung8edb8dc2015-03-26 19:13:55 -07001710 minBufCount * sourceFramesNeededWithTimestretch(
1711 sampleRate, mNormalFrameCount,
1712 mSampleRate, AUDIO_TIMESTRETCH_SPEED_NORMAL /*speed*/);
Andy Hung0e48d252015-01-26 11:43:15 -08001713 if (frameCount < minFrameCount) { // including frameCount == 0
Eric Laurent81784c32012-11-19 14:55:58 -08001714 frameCount = minFrameCount;
1715 }
Eric Laurent81784c32012-11-19 14:55:58 -08001716 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001717 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001718
Glenn Kastenc3df8382014-03-13 15:05:25 -07001719 switch (mType) {
1720
1721 case DIRECT:
Glenn Kasten993fa062014-05-02 11:14:34 -07001722 if (audio_is_linear_pcm(format)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001723 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001724 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1725 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001726 sampleRate, format, channelMask, mOutput, mFormat);
1727 lStatus = BAD_VALUE;
1728 goto Exit;
1729 }
1730 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001731 break;
1732
1733 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001734 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001735 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1736 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001737 sampleRate, format, channelMask, mOutput, mFormat);
1738 lStatus = BAD_VALUE;
1739 goto Exit;
1740 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001741 break;
1742
1743 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07001744 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001745 ALOGE("createTrack_l() Bad parameter: format %#x \""
1746 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001747 format, mOutput, mFormat);
1748 lStatus = BAD_VALUE;
1749 goto Exit;
1750 }
Andy Hungcd044842014-08-07 11:04:34 -07001751 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08001752 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1753 lStatus = BAD_VALUE;
1754 goto Exit;
1755 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001756 break;
1757
Eric Laurent81784c32012-11-19 14:55:58 -08001758 }
1759
1760 lStatus = initCheck();
1761 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07001762 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08001763 goto Exit;
1764 }
1765
1766 { // scope for mLock
1767 Mutex::Autolock _l(mLock);
1768
1769 // all tracks in same audio session must share the same routing strategy otherwise
1770 // conflicts will happen when tracks are moved from one output to another by audio policy
1771 // manager
1772 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1773 for (size_t i = 0; i < mTracks.size(); ++i) {
1774 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07001775 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001776 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1777 if (sessionId == t->sessionId() && strategy != actual) {
1778 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1779 strategy, actual);
1780 lStatus = BAD_VALUE;
1781 goto Exit;
1782 }
1783 }
1784 }
1785
1786 if (!isTimed) {
1787 track = new Track(this, client, streamType, sampleRate, format,
Eric Laurent83b88082014-06-20 18:31:16 -07001788 channelMask, frameCount, NULL, sharedBuffer,
1789 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08001790 } else {
1791 track = TimedTrack::create(this, client, streamType, sampleRate, format,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001792 channelMask, frameCount, sharedBuffer, sessionId, uid);
Eric Laurent81784c32012-11-19 14:55:58 -08001793 }
Glenn Kasten03003332013-08-06 15:40:54 -07001794
1795 // new Track always returns non-NULL,
1796 // but TimedTrack::create() is a factory that could fail by returning NULL
1797 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
1798 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08001799 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001800 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08001801 goto Exit;
1802 }
1803 mTracks.add(track);
1804
1805 sp<EffectChain> chain = getEffectChain_l(sessionId);
1806 if (chain != 0) {
1807 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1808 track->setMainBuffer(chain->inBuffer());
1809 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1810 chain->incTrackCnt();
1811 }
1812
1813 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1814 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1815 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1816 // so ask activity manager to do this on our behalf
1817 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1818 }
1819 }
1820
1821 lStatus = NO_ERROR;
1822
1823Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001824 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001825 return track;
1826}
1827
1828uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1829{
1830 return latency;
1831}
1832
1833uint32_t AudioFlinger::PlaybackThread::latency() const
1834{
1835 Mutex::Autolock _l(mLock);
1836 return latency_l();
1837}
1838uint32_t AudioFlinger::PlaybackThread::latency_l() const
1839{
1840 if (initCheck() == NO_ERROR) {
1841 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
1842 } else {
1843 return 0;
1844 }
1845}
1846
1847void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1848{
1849 Mutex::Autolock _l(mLock);
1850 // Don't apply master volume in SW if our HAL can do it for us.
1851 if (mOutput && mOutput->audioHwDev &&
1852 mOutput->audioHwDev->canSetMasterVolume()) {
1853 mMasterVolume = 1.0;
1854 } else {
1855 mMasterVolume = value;
1856 }
1857}
1858
1859void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1860{
1861 Mutex::Autolock _l(mLock);
1862 // Don't apply master mute in SW if our HAL can do it for us.
1863 if (mOutput && mOutput->audioHwDev &&
1864 mOutput->audioHwDev->canSetMasterMute()) {
1865 mMasterMute = false;
1866 } else {
1867 mMasterMute = muted;
1868 }
1869}
1870
1871void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
1872{
1873 Mutex::Autolock _l(mLock);
1874 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001875 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001876}
1877
1878void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
1879{
1880 Mutex::Autolock _l(mLock);
1881 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001882 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001883}
1884
1885float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
1886{
1887 Mutex::Autolock _l(mLock);
1888 return mStreamTypes[stream].volume;
1889}
1890
1891// addTrack_l() must be called with ThreadBase::mLock held
1892status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1893{
1894 status_t status = ALREADY_EXISTS;
1895
1896 // set retry count for buffer fill
1897 track->mRetryCount = kMaxTrackStartupRetries;
1898 if (mActiveTracks.indexOf(track) < 0) {
1899 // the track is newly added, make sure it fills up all its
1900 // buffers before playing. This is to ensure the client will
1901 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07001902 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001903 TrackBase::track_state state = track->mState;
1904 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08001905 status = AudioSystem::startOutput(mId, track->streamType(),
1906 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001907 mLock.lock();
1908 // abort track was stopped/paused while we released the lock
1909 if (state != track->mState) {
1910 if (status == NO_ERROR) {
1911 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08001912 AudioSystem::stopOutput(mId, track->streamType(),
1913 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001914 mLock.lock();
1915 }
1916 return INVALID_OPERATION;
1917 }
1918 // abort if start is rejected by audio policy manager
1919 if (status != NO_ERROR) {
1920 return PERMISSION_DENIED;
1921 }
1922#ifdef ADD_BATTERY_DATA
1923 // to track the speaker usage
1924 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
1925#endif
1926 }
1927
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001928 track->mFillingUpStatus = track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent81784c32012-11-19 14:55:58 -08001929 track->mResetDone = false;
1930 track->mPresentationCompleteFrames = 0;
1931 mActiveTracks.add(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001932 mWakeLockUids.add(track->uid());
1933 mActiveTracksGeneration++;
Eric Laurentfd477972013-10-25 18:10:40 -07001934 mLatestActiveTrack = track;
Eric Laurentd0107bc2013-06-11 14:38:48 -07001935 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1936 if (chain != 0) {
1937 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
1938 track->sessionId());
1939 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08001940 }
1941
1942 status = NO_ERROR;
1943 }
1944
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08001945 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001946 return status;
1947}
1948
Eric Laurentbfb1b832013-01-07 09:53:42 -08001949bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08001950{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001951 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08001952 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001953 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
1954 track->mState = TrackBase::STOPPED;
1955 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08001956 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07001957 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001958 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08001959 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001960
1961 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08001962}
1963
1964void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1965{
1966 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
1967 mTracks.remove(track);
1968 deleteTrackName_l(track->name());
1969 // redundant as track is about to be destroyed, for dumpsys only
1970 track->mName = -1;
1971 if (track->isFastTrack()) {
1972 int index = track->mFastIndex;
1973 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
1974 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1975 mFastTrackAvailMask |= 1 << index;
1976 // redundant as track is about to be destroyed, for dumpsys only
1977 track->mFastIndex = -1;
1978 }
1979 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1980 if (chain != 0) {
1981 chain->decTrackCnt();
1982 }
1983}
1984
Eric Laurentede6c3b2013-09-19 14:37:46 -07001985void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001986{
1987 // Thread could be blocked waiting for async
1988 // so signal it to handle state changes immediately
1989 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1990 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1991 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001992 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001993}
1994
Eric Laurent81784c32012-11-19 14:55:58 -08001995String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1996{
Eric Laurent81784c32012-11-19 14:55:58 -08001997 Mutex::Autolock _l(mLock);
1998 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07001999 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002000 }
2001
Glenn Kastend8ea6992013-07-16 14:17:15 -07002002 char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
2003 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08002004 free(s);
2005 return out_s8;
2006}
2007
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002008void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002009 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2010 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002011
Eric Laurent73e26b62015-04-27 16:55:58 -07002012 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002013
2014 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002015 case AUDIO_OUTPUT_OPENED:
2016 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002017 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002018 desc->mChannelMask = mChannelMask;
2019 desc->mSamplingRate = mSampleRate;
2020 desc->mFormat = mFormat;
2021 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002022 // AudioFlinger::frameCount(audio_io_handle_t)
Eric Laurent73e26b62015-04-27 16:55:58 -07002023 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002024 break;
2025
Eric Laurent73e26b62015-04-27 16:55:58 -07002026 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002027 default:
2028 break;
2029 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002030 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002031}
2032
Eric Laurentbfb1b832013-01-07 09:53:42 -08002033void AudioFlinger::PlaybackThread::writeCallback()
2034{
2035 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002036 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002037}
2038
2039void AudioFlinger::PlaybackThread::drainCallback()
2040{
2041 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002042 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002043}
2044
Eric Laurent3b4529e2013-09-05 18:09:19 -07002045void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002046{
2047 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002048 // reject out of sequence requests
2049 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2050 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002051 mWaitWorkCV.signal();
2052 }
2053}
2054
Eric Laurent3b4529e2013-09-05 18:09:19 -07002055void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002056{
2057 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002058 // reject out of sequence requests
2059 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
2060 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002061 mWaitWorkCV.signal();
2062 }
2063}
2064
2065// static
2066int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
Glenn Kasten0f11b512014-01-31 16:18:54 -08002067 void *param __unused,
Eric Laurentbfb1b832013-01-07 09:53:42 -08002068 void *cookie)
2069{
2070 AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
2071 ALOGV("asyncCallback() event %d", event);
2072 switch (event) {
2073 case STREAM_CBK_EVENT_WRITE_READY:
2074 me->writeCallback();
2075 break;
2076 case STREAM_CBK_EVENT_DRAIN_READY:
2077 me->drainCallback();
2078 break;
2079 default:
2080 ALOGW("asyncCallback() unknown event %d", event);
2081 break;
2082 }
2083 return 0;
2084}
2085
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002086void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002087{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002088 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Phil Burkca5e6142015-07-14 09:42:29 -07002089 mSampleRate = mOutput->getSampleRate();
2090 mChannelMask = mOutput->getChannelMask();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002091 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002092 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002093 }
Andy Hung9a592762014-07-21 21:56:01 -07002094 if ((mType == MIXER || mType == DUPLICATING)
2095 && !isValidPcmSinkChannelMask(mChannelMask)) {
2096 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2097 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002098 }
Andy Hunge5412692014-05-16 11:25:07 -07002099 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002100
2101 // Get actual HAL format.
Andy Hung463be252014-07-10 16:56:07 -07002102 mHALFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Phil Burkca5e6142015-07-14 09:42:29 -07002103 // Get format from the shim, which will be different than the HAL format
2104 // if playing compressed audio over HDMI passthrough.
2105 mFormat = mOutput->getFormat();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002106 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002107 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002108 }
Andy Hung6146c082014-03-18 11:56:15 -07002109 if ((mType == MIXER || mType == DUPLICATING)
2110 && !isValidPcmSinkFormat(mFormat)) {
2111 LOG_FATAL("HAL format %#x not supported for mixed output",
2112 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002113 }
Phil Burk062e67a2015-02-11 13:40:50 -08002114 mFrameSize = mOutput->getFrameSize();
Glenn Kasten70949c42013-08-06 07:40:12 -07002115 mBufferSize = mOutput->stream->common.get_buffer_size(&mOutput->stream->common);
2116 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002117 if (mFrameCount & 15) {
2118 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
2119 mFrameCount);
2120 }
2121
Eric Laurentbfb1b832013-01-07 09:53:42 -08002122 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
2123 (mOutput->stream->set_callback != NULL)) {
2124 if (mOutput->stream->set_callback(mOutput->stream,
2125 AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
2126 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002127 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002128 }
2129 }
2130
Eric Laurentd1f69b02014-12-15 14:33:13 -08002131 mHwSupportsPause = false;
2132 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
2133 if (mOutput->stream->pause != NULL) {
2134 if (mOutput->stream->resume != NULL) {
2135 mHwSupportsPause = true;
2136 } else {
2137 ALOGW("direct output implements pause but not resume");
2138 }
2139 } else if (mOutput->stream->resume != NULL) {
2140 ALOGW("direct output implements resume but not pause");
2141 }
2142 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002143 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2144 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2145 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002146
Andy Hungfbfc3952015-01-15 13:33:51 -08002147 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2148 // For best precision, we use float instead of the associated output
2149 // device format (typically PCM 16 bit).
2150
2151 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2152 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2153 mBufferSize = mFrameSize * mFrameCount;
2154
2155 // TODO: We currently use the associated output device channel mask and sample rate.
2156 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2157 // (if a valid mask) to avoid premature downmix.
2158 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2159 // instead of the output device sample rate to avoid loss of high frequency information.
2160 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2161 }
2162
Andy Hung09a50072014-02-27 14:30:47 -08002163 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002164 double multiplier = 1.0;
2165 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2166 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002167 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2168 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Eric Laurent81784c32012-11-19 14:55:58 -08002169 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2170 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2171 maxNormalFrameCount = maxNormalFrameCount & ~15;
2172 if (maxNormalFrameCount < minNormalFrameCount) {
2173 maxNormalFrameCount = minNormalFrameCount;
2174 }
2175 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2176 if (multiplier <= 1.0) {
2177 multiplier = 1.0;
2178 } else if (multiplier <= 2.0) {
2179 if (2 * mFrameCount <= maxNormalFrameCount) {
2180 multiplier = 2.0;
2181 } else {
2182 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2183 }
2184 } else {
2185 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
Andy Hung09a50072014-02-27 14:30:47 -08002186 // 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 -08002187 // track, but we sometimes have to do this to satisfy the maximum frame count
2188 // constraint)
2189 // FIXME this rounding up should not be done if no HAL SRC
2190 uint32_t truncMult = (uint32_t) multiplier;
2191 if ((truncMult & 1)) {
2192 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
2193 ++truncMult;
2194 }
2195 }
2196 multiplier = (double) truncMult;
2197 }
2198 }
2199 mNormalFrameCount = multiplier * mFrameCount;
2200 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002201 if (mType == MIXER || mType == DUPLICATING) {
2202 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2203 }
Andy Hung09a50072014-02-27 14:30:47 -08002204 ALOGI("HAL output buffer size %u frames, normal sink buffer size %u frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002205 mNormalFrameCount);
2206
Andy Hung08fb1742015-05-31 23:22:10 -07002207 // Check if we want to throttle the processing to no more than 2x normal rate
2208 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002209 mThreadThrottleTimeMs = 0;
2210 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002211 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2212
Andy Hung010a1a12014-03-13 13:57:33 -07002213 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2214 // Originally this was int16_t[] array, need to remove legacy implications.
2215 free(mSinkBuffer);
2216 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002217 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2218 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2219 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002220 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002221
Andy Hung69aed5f2014-02-25 17:24:40 -08002222 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2223 // drives the output.
2224 free(mMixerBuffer);
2225 mMixerBuffer = NULL;
2226 if (mMixerBufferEnabled) {
2227 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2228 mMixerBufferSize = mNormalFrameCount * mChannelCount
2229 * audio_bytes_per_sample(mMixerBufferFormat);
2230 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2231 }
Andy Hung98ef9782014-03-04 14:46:50 -08002232 free(mEffectBuffer);
2233 mEffectBuffer = NULL;
2234 if (mEffectBufferEnabled) {
2235 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
2236 mEffectBufferSize = mNormalFrameCount * mChannelCount
2237 * audio_bytes_per_sample(mEffectBufferFormat);
2238 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2239 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002240
Eric Laurent81784c32012-11-19 14:55:58 -08002241 // force reconfiguration of effect chains and engines to take new buffer size and audio
2242 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002243 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002244 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2245 // matter.
2246 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2247 Vector< sp<EffectChain> > effectChains = mEffectChains;
2248 for (size_t i = 0; i < effectChains.size(); i ++) {
2249 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2250 }
2251}
2252
2253
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002254status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002255{
2256 if (halFrames == NULL || dspFrames == NULL) {
2257 return BAD_VALUE;
2258 }
2259 Mutex::Autolock _l(mLock);
2260 if (initCheck() != NO_ERROR) {
2261 return INVALID_OPERATION;
2262 }
2263 size_t framesWritten = mBytesWritten / mFrameSize;
2264 *halFrames = framesWritten;
2265
2266 if (isSuspended()) {
2267 // return an estimation of rendered frames when the output is suspended
2268 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
2269 *dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0;
2270 return NO_ERROR;
2271 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002272 status_t status;
2273 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002274 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002275 *dspFrames = (size_t)frames;
2276 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002277 }
2278}
2279
2280uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
2281{
2282 Mutex::Autolock _l(mLock);
2283 uint32_t result = 0;
2284 if (getEffectChain_l(sessionId) != 0) {
2285 result = EFFECT_SESSION;
2286 }
2287
2288 for (size_t i = 0; i < mTracks.size(); ++i) {
2289 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002290 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002291 result |= TRACK_SESSION;
2292 break;
2293 }
2294 }
2295
2296 return result;
2297}
2298
2299uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
2300{
2301 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2302 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2303 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2304 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2305 }
2306 for (size_t i = 0; i < mTracks.size(); i++) {
2307 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002308 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002309 return AudioSystem::getStrategyForStream(track->streamType());
2310 }
2311 }
2312 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2313}
2314
2315
Phil Burk062e67a2015-02-11 13:40:50 -08002316AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002317{
2318 Mutex::Autolock _l(mLock);
2319 return mOutput;
2320}
2321
Phil Burk062e67a2015-02-11 13:40:50 -08002322AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002323{
2324 Mutex::Autolock _l(mLock);
2325 AudioStreamOut *output = mOutput;
2326 mOutput = NULL;
2327 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2328 // must push a NULL and wait for ack
2329 mOutputSink.clear();
2330 mPipeSink.clear();
2331 mNormalSink.clear();
2332 return output;
2333}
2334
2335// this method must always be called either with ThreadBase mLock held or inside the thread loop
2336audio_stream_t* AudioFlinger::PlaybackThread::stream() const
2337{
2338 if (mOutput == NULL) {
2339 return NULL;
2340 }
2341 return &mOutput->stream->common;
2342}
2343
2344uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2345{
2346 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2347}
2348
2349status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2350{
2351 if (!isValidSyncEvent(event)) {
2352 return BAD_VALUE;
2353 }
2354
2355 Mutex::Autolock _l(mLock);
2356
2357 for (size_t i = 0; i < mTracks.size(); ++i) {
2358 sp<Track> track = mTracks[i];
2359 if (event->triggerSession() == track->sessionId()) {
2360 (void) track->setSyncEvent(event);
2361 return NO_ERROR;
2362 }
2363 }
2364
2365 return NAME_NOT_FOUND;
2366}
2367
2368bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2369{
2370 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2371}
2372
2373void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2374 const Vector< sp<Track> >& tracksToRemove)
2375{
2376 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002377 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002378 for (size_t i = 0 ; i < count ; i++) {
2379 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002380 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002381 AudioSystem::stopOutput(mId, track->streamType(),
2382 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002383#ifdef ADD_BATTERY_DATA
2384 // to track the speaker usage
2385 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2386#endif
2387 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002388 AudioSystem::releaseOutput(mId, track->streamType(),
2389 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002390 }
Eric Laurent81784c32012-11-19 14:55:58 -08002391 }
2392 }
2393 }
Eric Laurent81784c32012-11-19 14:55:58 -08002394}
2395
2396void AudioFlinger::PlaybackThread::checkSilentMode_l()
2397{
2398 if (!mMasterMute) {
2399 char value[PROPERTY_VALUE_MAX];
2400 if (property_get("ro.audio.silent", value, "0") > 0) {
2401 char *endptr;
2402 unsigned long ul = strtoul(value, &endptr, 0);
2403 if (*endptr == '\0' && ul != 0) {
2404 ALOGD("Silence is golden");
2405 // The setprop command will not allow a property to be changed after
2406 // the first time it is set, so we don't have to worry about un-muting.
2407 setMasterMute_l(true);
2408 }
2409 }
2410 }
2411}
2412
2413// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002414ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002415{
2416 // FIXME rewrite to reduce number of system calls
2417 mLastWriteTime = systemTime();
2418 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002419 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002420 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002421
2422 // If an NBAIO sink is present, use it to write the normal mixer's submix
2423 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002424
Andy Hung010a1a12014-03-13 13:57:33 -07002425 const size_t count = mBytesRemaining / mFrameSize;
2426
Simon Wilson2d590962012-11-29 15:18:50 -08002427 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002428 // update the setpoint when AudioFlinger::mScreenState changes
2429 uint32_t screenState = AudioFlinger::mScreenState;
2430 if (screenState != mScreenState) {
2431 mScreenState = screenState;
2432 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2433 if (pipe != NULL) {
2434 pipe->setAvgFrames((mScreenState & 1) ?
2435 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2436 }
2437 }
Andy Hung010a1a12014-03-13 13:57:33 -07002438 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002439 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002440 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002441 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002442 } else {
2443 bytesWritten = framesWritten;
2444 }
Glenn Kastenefaa7ab2014-08-20 08:48:54 -07002445 mLatchDValid = false;
Glenn Kasten767094d2013-08-23 13:51:43 -07002446 status_t status = mNormalSink->getTimestamp(mLatchD.mTimestamp);
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002447 if (status == NO_ERROR) {
2448 size_t totalFramesWritten = mNormalSink->framesWritten();
2449 if (totalFramesWritten >= mLatchD.mTimestamp.mPosition) {
2450 mLatchD.mUnpresentedFrames = totalFramesWritten - mLatchD.mTimestamp.mPosition;
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002451 // mLatchD.mFramesReleased is set immediately before D is clocked into Q
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002452 mLatchDValid = true;
2453 }
2454 }
Eric Laurent81784c32012-11-19 14:55:58 -08002455 // otherwise use the HAL / AudioStreamOut directly
2456 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002457 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002458
Eric Laurentbfb1b832013-01-07 09:53:42 -08002459 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002460 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2461 mWriteAckSequence += 2;
2462 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002463 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002464 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002465 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002466 // FIXME We should have an implementation of timestamps for direct output threads.
2467 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002468 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002469 if (mUseAsyncWrite &&
2470 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2471 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002472 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002473 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002474 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002475 }
Eric Laurent81784c32012-11-19 14:55:58 -08002476 }
2477
Eric Laurent81784c32012-11-19 14:55:58 -08002478 mNumWrites++;
2479 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002480 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002481 return bytesWritten;
2482}
2483
2484void AudioFlinger::PlaybackThread::threadLoop_drain()
2485{
2486 if (mOutput->stream->drain) {
2487 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2488 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002489 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2490 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002491 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002492 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002493 }
2494 mOutput->stream->drain(mOutput->stream,
2495 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
2496 : AUDIO_DRAIN_ALL);
2497 }
2498}
2499
2500void AudioFlinger::PlaybackThread::threadLoop_exit()
2501{
Eric Laurent275e8e92014-11-30 15:14:47 -08002502 {
2503 Mutex::Autolock _l(mLock);
2504 for (size_t i = 0; i < mTracks.size(); i++) {
2505 sp<Track> track = mTracks[i];
2506 track->invalidate();
2507 }
2508 }
Eric Laurent81784c32012-11-19 14:55:58 -08002509}
2510
2511/*
2512The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002513 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002514 - mActiveSleepTimeUs from activeSleepTimeUs()
2515 - mIdleSleepTimeUs from idleSleepTimeUs()
2516 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only)
Eric Laurent81784c32012-11-19 14:55:58 -08002517 - maxPeriod from frame count and sample rate (MIXER only)
2518
2519The parameters that affect these derived values are:
2520 - frame count
2521 - frame size
2522 - sample rate
2523 - device type: A2DP or not
2524 - device latency
2525 - format: PCM or not
2526 - active sleep time
2527 - idle sleep time
2528*/
2529
2530void AudioFlinger::PlaybackThread::cacheParameters_l()
2531{
Andy Hung25c2dac2014-02-27 14:56:00 -08002532 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002533 mActiveSleepTimeUs = activeSleepTimeUs();
2534 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent81784c32012-11-19 14:55:58 -08002535}
2536
2537void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2538{
Glenn Kasten7c027242012-12-26 14:43:16 -08002539 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurent81784c32012-11-19 14:55:58 -08002540 this, streamType, mTracks.size());
2541 Mutex::Autolock _l(mLock);
2542
2543 size_t size = mTracks.size();
2544 for (size_t i = 0; i < size; i++) {
2545 sp<Track> t = mTracks[i];
2546 if (t->streamType() == streamType) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002547 t->invalidate();
Eric Laurent81784c32012-11-19 14:55:58 -08002548 }
2549 }
2550}
2551
2552status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2553{
2554 int session = chain->sessionId();
Andy Hung010a1a12014-03-13 13:57:33 -07002555 int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled
2556 ? mEffectBuffer : mSinkBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002557 bool ownsBuffer = false;
2558
2559 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
2560 if (session > 0) {
2561 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002562 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002563 if (mType != DIRECT) {
2564 size_t numSamples = mNormalFrameCount * mChannelCount;
2565 buffer = new int16_t[numSamples];
2566 memset(buffer, 0, numSamples * sizeof(int16_t));
2567 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2568 ownsBuffer = true;
2569 }
2570
2571 // Attach all tracks with same session ID to this chain.
2572 for (size_t i = 0; i < mTracks.size(); ++i) {
2573 sp<Track> track = mTracks[i];
2574 if (session == track->sessionId()) {
2575 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2576 buffer);
2577 track->setMainBuffer(buffer);
2578 chain->incTrackCnt();
2579 }
2580 }
2581
2582 // indicate all active tracks in the chain
2583 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2584 sp<Track> track = mActiveTracks[i].promote();
2585 if (track == 0) {
2586 continue;
2587 }
2588 if (session == track->sessionId()) {
2589 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2590 chain->incActiveTrackCnt();
2591 }
2592 }
2593 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002594 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08002595 chain->setInBuffer(buffer, ownsBuffer);
Andy Hung010a1a12014-03-13 13:57:33 -07002596 chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled
2597 ? mEffectBuffer : mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002598 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
2599 // chains list in order to be processed last as it contains output stage effects
2600 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2601 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
2602 // after track specific effects and before output stage
2603 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
2604 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
2605 // Effect chain for other sessions are inserted at beginning of effect
2606 // chains list to be processed before output mix effects. Relative order between other
2607 // sessions is not important
2608 size_t size = mEffectChains.size();
2609 size_t i = 0;
2610 for (i = 0; i < size; i++) {
2611 if (mEffectChains[i]->sessionId() < session) {
2612 break;
2613 }
2614 }
2615 mEffectChains.insertAt(chain, i);
2616 checkSuspendOnAddEffectChain_l(chain);
2617
2618 return NO_ERROR;
2619}
2620
2621size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2622{
2623 int session = chain->sessionId();
2624
2625 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2626
2627 for (size_t i = 0; i < mEffectChains.size(); i++) {
2628 if (chain == mEffectChains[i]) {
2629 mEffectChains.removeAt(i);
2630 // detach all active tracks from the chain
2631 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2632 sp<Track> track = mActiveTracks[i].promote();
2633 if (track == 0) {
2634 continue;
2635 }
2636 if (session == track->sessionId()) {
2637 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2638 chain.get(), session);
2639 chain->decActiveTrackCnt();
2640 }
2641 }
2642
2643 // detach all tracks with same session ID from this chain
2644 for (size_t i = 0; i < mTracks.size(); ++i) {
2645 sp<Track> track = mTracks[i];
2646 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002647 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002648 chain->decTrackCnt();
2649 }
2650 }
2651 break;
2652 }
2653 }
2654 return mEffectChains.size();
2655}
2656
2657status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2658 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2659{
2660 Mutex::Autolock _l(mLock);
2661 return attachAuxEffect_l(track, EffectId);
2662}
2663
2664status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2665 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2666{
2667 status_t status = NO_ERROR;
2668
2669 if (EffectId == 0) {
2670 track->setAuxBuffer(0, NULL);
2671 } else {
2672 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2673 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2674 if (effect != 0) {
2675 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2676 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2677 } else {
2678 status = INVALID_OPERATION;
2679 }
2680 } else {
2681 status = BAD_VALUE;
2682 }
2683 }
2684 return status;
2685}
2686
2687void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2688{
2689 for (size_t i = 0; i < mTracks.size(); ++i) {
2690 sp<Track> track = mTracks[i];
2691 if (track->auxEffectId() == effectId) {
2692 attachAuxEffect_l(track, 0);
2693 }
2694 }
2695}
2696
2697bool AudioFlinger::PlaybackThread::threadLoop()
2698{
2699 Vector< sp<Track> > tracksToRemove;
2700
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002701 mStandbyTimeNs = systemTime();
Eric Laurent81784c32012-11-19 14:55:58 -08002702
2703 // MIXER
2704 nsecs_t lastWarning = 0;
2705
2706 // DUPLICATING
2707 // FIXME could this be made local to while loop?
2708 writeFrames = 0;
2709
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002710 int lastGeneration = 0;
2711
Eric Laurent81784c32012-11-19 14:55:58 -08002712 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002713 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08002714
2715 if (mType == MIXER) {
2716 sleepTimeShift = 0;
2717 }
2718
2719 CpuStats cpuStats;
2720 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2721
2722 acquireWakeLock();
2723
Glenn Kasten9e58b552013-01-18 15:09:48 -08002724 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2725 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2726 // and then that string will be logged at the next convenient opportunity.
2727 const char *logString = NULL;
2728
Eric Laurent664539d2013-09-23 18:24:31 -07002729 checkSilentMode_l();
2730
Eric Laurent81784c32012-11-19 14:55:58 -08002731 while (!exitPending())
2732 {
2733 cpuStats.sample(myName);
2734
2735 Vector< sp<EffectChain> > effectChains;
2736
Eric Laurent81784c32012-11-19 14:55:58 -08002737 { // scope for mLock
2738
2739 Mutex::Autolock _l(mLock);
2740
Eric Laurent021cf962014-05-13 10:18:14 -07002741 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07002742
Glenn Kasten9e58b552013-01-18 15:09:48 -08002743 if (logString != NULL) {
2744 mNBLogWriter->logTimestamp();
2745 mNBLogWriter->log(logString);
2746 logString = NULL;
2747 }
2748
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002749 // Gather the framesReleased counters for all active tracks,
2750 // and latch them atomically with the timestamp.
2751 // FIXME We're using raw pointers as indices. A unique track ID would be a better index.
2752 mLatchD.mFramesReleased.clear();
2753 size_t size = mActiveTracks.size();
2754 for (size_t i = 0; i < size; i++) {
2755 sp<Track> t = mActiveTracks[i].promote();
2756 if (t != 0) {
2757 mLatchD.mFramesReleased.add(t.get(),
2758 t->mAudioTrackServerProxy->framesReleased());
2759 }
2760 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002761 if (mLatchDValid) {
2762 mLatchQ = mLatchD;
2763 mLatchDValid = false;
2764 mLatchQValid = true;
2765 }
2766
Eric Laurent81784c32012-11-19 14:55:58 -08002767 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002768 if (mSignalPending) {
2769 // A signal was raised while we were unlocked
2770 mSignalPending = false;
2771 } else if (waitingAsyncCallback_l()) {
2772 if (exitPending()) {
2773 break;
2774 }
Marco Nelissen078538c2015-05-12 09:17:57 -07002775 bool released = false;
2776 // The following works around a bug in the offload driver. Ideally we would release
2777 // the wake lock every time, but that causes the last offload buffer(s) to be
2778 // dropped while the device is on battery, so we need to hold a wake lock during
2779 // the drain phase.
2780 if (mBytesRemaining && !(mDrainSequence & 1)) {
2781 releaseWakeLock_l();
2782 released = true;
2783 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002784 mWakeLockUids.clear();
2785 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002786 ALOGV("wait async completion");
2787 mWaitWorkCV.wait(mLock);
2788 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07002789 if (released) {
2790 acquireWakeLock_l();
2791 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002792 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
2793 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002794
2795 continue;
2796 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002797 if ((!mActiveTracks.size() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08002798 isSuspended()) {
2799 // put audio hardware into standby after short delay
2800 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002801
2802 threadLoop_standby();
2803
2804 mStandby = true;
2805 }
2806
2807 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2808 // we're about to wait, flush the binder command buffer
2809 IPCThreadState::self()->flushCommands();
2810
2811 clearOutputTracks();
2812
2813 if (exitPending()) {
2814 break;
2815 }
2816
2817 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002818 mWakeLockUids.clear();
2819 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002820 // wait until we have something to do...
2821 ALOGV("%s going to sleep", myName.string());
2822 mWaitWorkCV.wait(mLock);
2823 ALOGV("%s waking up", myName.string());
2824 acquireWakeLock_l();
2825
2826 mMixerStatus = MIXER_IDLE;
2827 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2828 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002829 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002830 checkSilentMode_l();
2831
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002832 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
2833 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08002834 if (mType == MIXER) {
2835 sleepTimeShift = 0;
2836 }
2837
2838 continue;
2839 }
2840 }
Eric Laurent81784c32012-11-19 14:55:58 -08002841 // mMixerStatusIgnoringFastTracks is also updated internally
2842 mMixerStatus = prepareTracks_l(&tracksToRemove);
2843
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002844 // compare with previously applied list
2845 if (lastGeneration != mActiveTracksGeneration) {
2846 // update wakelock
2847 updateWakeLockUids_l(mWakeLockUids);
2848 lastGeneration = mActiveTracksGeneration;
2849 }
2850
Eric Laurent81784c32012-11-19 14:55:58 -08002851 // prevent any changes in effect chain list and in each effect chain
2852 // during mixing and effect process as the audio buffers could be deleted
2853 // or modified if an effect is created or deleted
2854 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002855 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08002856
Eric Laurentbfb1b832013-01-07 09:53:42 -08002857 if (mBytesRemaining == 0) {
2858 mCurrentWriteLength = 0;
2859 if (mMixerStatus == MIXER_TRACKS_READY) {
2860 // threadLoop_mix() sets mCurrentWriteLength
2861 threadLoop_mix();
2862 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
2863 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002864 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08002865 // must be written to HAL
2866 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002867 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08002868 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002869 }
2870 }
Andy Hung98ef9782014-03-04 14:46:50 -08002871 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002872 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08002873 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
2874 // or mSinkBuffer (if there are no effects).
2875 //
2876 // This is done pre-effects computation; if effects change to
2877 // support higher precision, this needs to move.
2878 //
2879 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002880 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08002881 if (mMixerBufferValid) {
2882 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
2883 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
2884
2885 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
2886 mNormalFrameCount * mChannelCount);
2887 }
2888
Eric Laurentbfb1b832013-01-07 09:53:42 -08002889 mBytesRemaining = mCurrentWriteLength;
2890 if (isSuspended()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002891 mSleepTimeUs = suspendSleepTimeUs();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002892 // simulate write to HAL when suspended
Andy Hung25c2dac2014-02-27 14:56:00 -08002893 mBytesWritten += mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002894 mBytesRemaining = 0;
2895 }
Eric Laurent81784c32012-11-19 14:55:58 -08002896
Eric Laurentbfb1b832013-01-07 09:53:42 -08002897 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002898 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002899 for (size_t i = 0; i < effectChains.size(); i ++) {
2900 effectChains[i]->process_l();
2901 }
Eric Laurent81784c32012-11-19 14:55:58 -08002902 }
2903 }
Eric Laurent59fe0102013-09-27 18:48:26 -07002904 // Process effect chains for offloaded thread even if no audio
2905 // was read from audio track: process only updates effect state
2906 // and thus does have to be synchronized with audio writes but may have
2907 // to be called while waiting for async write callback
2908 if (mType == OFFLOAD) {
2909 for (size_t i = 0; i < effectChains.size(); i ++) {
2910 effectChains[i]->process_l();
2911 }
2912 }
Eric Laurent81784c32012-11-19 14:55:58 -08002913
Andy Hung98ef9782014-03-04 14:46:50 -08002914 // Only if the Effects buffer is enabled and there is data in the
2915 // Effects buffer (buffer valid), we need to
2916 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002917 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08002918 if (mEffectBufferValid) {
2919 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
2920 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
2921 mNormalFrameCount * mChannelCount);
2922 }
2923
Eric Laurent81784c32012-11-19 14:55:58 -08002924 // enable changes in effect chain
2925 unlockEffectChains(effectChains);
2926
Eric Laurentbfb1b832013-01-07 09:53:42 -08002927 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002928 // mSleepTimeUs == 0 means we must write to audio hardware
2929 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07002930 ssize_t ret = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002931 if (mBytesRemaining) {
Andy Hung08fb1742015-05-31 23:22:10 -07002932 ret = threadLoop_write();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002933 if (ret < 0) {
2934 mBytesRemaining = 0;
2935 } else {
2936 mBytesWritten += ret;
2937 mBytesRemaining -= ret;
2938 }
2939 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
2940 (mMixerStatus == MIXER_DRAIN_ALL)) {
2941 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08002942 }
Andy Hung08fb1742015-05-31 23:22:10 -07002943 if (mType == MIXER && !mStandby) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07002944 // write blocked detection
2945 nsecs_t now = systemTime();
2946 nsecs_t delta = now - mLastWriteTime;
Andy Hung08fb1742015-05-31 23:22:10 -07002947 if (delta > maxPeriod) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07002948 mNumDelayedWrites++;
2949 if ((now - lastWarning) > kWarningThrottleNs) {
2950 ATRACE_NAME("underrun");
2951 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2952 ns2ms(delta), mNumDelayedWrites, this);
2953 lastWarning = now;
2954 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002955 }
Andy Hung08fb1742015-05-31 23:22:10 -07002956
2957 if (mThreadThrottle
2958 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
2959 && ret > 0) { // we wrote something
2960 // Limit MixerThread data processing to no more than twice the
2961 // expected processing rate.
2962 //
2963 // This helps prevent underruns with NuPlayer and other applications
2964 // which may set up buffers that are close to the minimum size, or use
2965 // deep buffers, and rely on a double-buffering sleep strategy to fill.
2966 //
2967 // The throttle smooths out sudden large data drains from the device,
2968 // e.g. when it comes out of standby, which often causes problems with
2969 // (1) mixer threads without a fast mixer (which has its own warm-up)
2970 // (2) minimum buffer sized tracks (even if the track is full,
2971 // the app won't fill fast enough to handle the sudden draw).
2972
2973 const int32_t deltaMs = delta / 1000000;
2974 const int32_t throttleMs = mHalfBufferMs - deltaMs;
2975 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
2976 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07002977 // notify of throttle start on verbose log
2978 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
2979 "mixer(%p) throttle begin:"
2980 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07002981 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07002982 mThreadThrottleTimeMs += throttleMs;
2983 } else {
2984 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
2985 if (diff > 0) {
2986 // notify of throttle end on debug log
2987 ALOGD("mixer(%p) throttle end: throttle time(%u)", this, diff);
2988 mThreadThrottleEndMs = mThreadThrottleTimeMs;
2989 }
Andy Hung08fb1742015-05-31 23:22:10 -07002990 }
2991 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002992 }
Eric Laurent81784c32012-11-19 14:55:58 -08002993
Eric Laurentbfb1b832013-01-07 09:53:42 -08002994 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07002995 ATRACE_BEGIN("sleep");
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002996 usleep(mSleepTimeUs);
Glenn Kastene7754022014-10-31 12:11:26 -07002997 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002998 }
Eric Laurent81784c32012-11-19 14:55:58 -08002999 }
3000
3001 // Finally let go of removed track(s), without the lock held
3002 // since we can't guarantee the destructors won't acquire that
3003 // same lock. This will also mutate and push a new fast mixer state.
3004 threadLoop_removeTracks(tracksToRemove);
3005 tracksToRemove.clear();
3006
3007 // FIXME I don't understand the need for this here;
3008 // it was in the original code but maybe the
3009 // assignment in saveOutputTracks() makes this unnecessary?
3010 clearOutputTracks();
3011
3012 // Effect chains will be actually deleted here if they were removed from
3013 // mEffectChains list during mixing or effects processing
3014 effectChains.clear();
3015
3016 // FIXME Note that the above .clear() is no longer necessary since effectChains
3017 // is now local to this block, but will keep it for now (at least until merge done).
3018 }
3019
Eric Laurentbfb1b832013-01-07 09:53:42 -08003020 threadLoop_exit();
3021
Eric Laurentcf817a22014-08-04 20:36:31 -07003022 if (!mStandby) {
3023 threadLoop_standby();
3024 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003025 }
3026
3027 releaseWakeLock();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003028 mWakeLockUids.clear();
3029 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08003030
3031 ALOGV("Thread %p type %d exiting", this, mType);
3032 return false;
3033}
3034
Eric Laurentbfb1b832013-01-07 09:53:42 -08003035// removeTracks_l() must be called with ThreadBase::mLock held
3036void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3037{
3038 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07003039 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003040 for (size_t i=0 ; i<count ; i++) {
3041 const sp<Track>& track = tracksToRemove.itemAt(i);
3042 mActiveTracks.remove(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003043 mWakeLockUids.remove(track->uid());
3044 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003045 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
3046 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3047 if (chain != 0) {
3048 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
3049 track->sessionId());
3050 chain->decActiveTrackCnt();
3051 }
3052 if (track->isTerminated()) {
3053 removeTrack_l(track);
3054 }
3055 }
3056 }
3057
3058}
Eric Laurent81784c32012-11-19 14:55:58 -08003059
Eric Laurentaccc1472013-09-20 09:36:34 -07003060status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3061{
3062 if (mNormalSink != 0) {
3063 return mNormalSink->getTimestamp(timestamp);
3064 }
Andy Hung9a1c8892014-12-03 11:37:42 -08003065 if ((mType == OFFLOAD || mType == DIRECT)
3066 && mOutput != NULL && mOutput->stream->get_presentation_position) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003067 uint64_t position64;
Phil Burk062e67a2015-02-11 13:40:50 -08003068 int ret = mOutput->getPresentationPosition(&position64, &timestamp.mTime);
Eric Laurentaccc1472013-09-20 09:36:34 -07003069 if (ret == 0) {
3070 timestamp.mPosition = (uint32_t)position64;
3071 return NO_ERROR;
3072 }
3073 }
3074 return INVALID_OPERATION;
3075}
Eric Laurent1c333e22014-05-20 10:48:17 -07003076
Eric Laurent054d9d32015-04-24 08:48:48 -07003077status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
3078 audio_patch_handle_t *handle)
3079{
3080 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3081 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3082 if (mFastMixer != 0) {
3083 FastMixerStateQueue *sq = mFastMixer->sq();
3084 FastMixerState *state = sq->begin();
3085 if (!(state->mCommand & FastMixerState::IDLE)) {
3086 previousCommand = state->mCommand;
3087 state->mCommand = FastMixerState::HOT_IDLE;
3088 sq->end();
3089 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3090 } else {
3091 sq->end(false /*didModify*/);
3092 }
3093 }
3094 status_t status = PlaybackThread::createAudioPatch_l(patch, handle);
3095
3096 if (!(previousCommand & FastMixerState::IDLE)) {
3097 ALOG_ASSERT(mFastMixer != 0);
3098 FastMixerStateQueue *sq = mFastMixer->sq();
3099 FastMixerState *state = sq->begin();
3100 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3101 state->mCommand = previousCommand;
3102 sq->end();
3103 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3104 }
3105
3106 return status;
3107}
3108
Eric Laurent1c333e22014-05-20 10:48:17 -07003109status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3110 audio_patch_handle_t *handle)
3111{
3112 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003113
3114 // store new device and send to effects
3115 audio_devices_t type = AUDIO_DEVICE_NONE;
3116 for (unsigned int i = 0; i < patch->num_sinks; i++) {
3117 type |= patch->sinks[i].ext.device.type;
3118 }
3119
3120#ifdef ADD_BATTERY_DATA
3121 // when changing the audio output device, call addBatteryData to notify
3122 // the change
3123 if (mOutDevice != type) {
3124 uint32_t params = 0;
3125 // check whether speaker is on
3126 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3127 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003128 }
3129
Eric Laurent054d9d32015-04-24 08:48:48 -07003130 audio_devices_t deviceWithoutSpeaker
3131 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3132 // check if any other device (except speaker) is on
3133 if (type & deviceWithoutSpeaker) {
3134 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3135 }
3136
3137 if (params != 0) {
3138 addBatteryData(params);
3139 }
3140 }
3141#endif
3142
3143 for (size_t i = 0; i < mEffectChains.size(); i++) {
3144 mEffectChains[i]->setDevice_l(type);
3145 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003146
3147 // mPrevOutDevice is the latest device set by createAudioPatch_l(). It is not set when
3148 // the thread is created so that the first patch creation triggers an ioConfigChanged callback
3149 bool configChanged = mPrevOutDevice != type;
Eric Laurent054d9d32015-04-24 08:48:48 -07003150 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003151 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003152
3153 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003154 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
3155 status = hwDevice->create_audio_patch(hwDevice,
3156 patch->num_sources,
3157 patch->sources,
3158 patch->num_sinks,
3159 patch->sinks,
3160 handle);
3161 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003162 char *address;
3163 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3164 //FIXME: we only support address on first sink with HAL version < 3.0
3165 address = audio_device_address_to_parameter(
3166 patch->sinks[0].ext.device.type,
3167 patch->sinks[0].ext.device.address);
3168 } else {
3169 address = (char *)calloc(1, 1);
3170 }
3171 AudioParameter param = AudioParameter(String8(address));
3172 free(address);
3173 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), (int)type);
3174 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3175 param.toString().string());
3176 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003177 }
Eric Laurente8726fe2015-06-26 09:39:24 -07003178 if (configChanged) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003179 mPrevOutDevice = type;
Eric Laurente8726fe2015-06-26 09:39:24 -07003180 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
3181 }
Eric Laurent1c333e22014-05-20 10:48:17 -07003182 return status;
3183}
3184
Eric Laurent054d9d32015-04-24 08:48:48 -07003185status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3186{
3187 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3188 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3189 if (mFastMixer != 0) {
3190 FastMixerStateQueue *sq = mFastMixer->sq();
3191 FastMixerState *state = sq->begin();
3192 if (!(state->mCommand & FastMixerState::IDLE)) {
3193 previousCommand = state->mCommand;
3194 state->mCommand = FastMixerState::HOT_IDLE;
3195 sq->end();
3196 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3197 } else {
3198 sq->end(false /*didModify*/);
3199 }
3200 }
3201
3202 status_t status = PlaybackThread::releaseAudioPatch_l(handle);
3203
3204 if (!(previousCommand & FastMixerState::IDLE)) {
3205 ALOG_ASSERT(mFastMixer != 0);
3206 FastMixerStateQueue *sq = mFastMixer->sq();
3207 FastMixerState *state = sq->begin();
3208 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3209 state->mCommand = previousCommand;
3210 sq->end();
3211 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3212 }
3213
3214 return status;
3215}
3216
Eric Laurent1c333e22014-05-20 10:48:17 -07003217status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3218{
3219 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003220
3221 mOutDevice = AUDIO_DEVICE_NONE;
3222
Eric Laurent1c333e22014-05-20 10:48:17 -07003223 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
3224 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
3225 status = hwDevice->release_audio_patch(hwDevice, handle);
3226 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003227 AudioParameter param;
3228 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
3229 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3230 param.toString().string());
Eric Laurent1c333e22014-05-20 10:48:17 -07003231 }
3232 return status;
3233}
3234
Eric Laurent83b88082014-06-20 18:31:16 -07003235void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3236{
3237 Mutex::Autolock _l(mLock);
3238 mTracks.add(track);
3239}
3240
3241void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3242{
3243 Mutex::Autolock _l(mLock);
3244 destroyTrack_l(track);
3245}
3246
3247void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
3248{
3249 ThreadBase::getAudioPortConfig(config);
3250 config->role = AUDIO_PORT_ROLE_SOURCE;
3251 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3252 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
3253}
3254
Eric Laurent81784c32012-11-19 14:55:58 -08003255// ----------------------------------------------------------------------------
3256
3257AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurent72e3f392015-05-20 14:43:50 -07003258 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
3259 : PlaybackThread(audioFlinger, output, id, device, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08003260 // mAudioMixer below
3261 // mFastMixer below
3262 mFastMixerFutex(0)
3263 // mOutputSink below
3264 // mPipeSink below
3265 // mNormalSink below
3266{
3267 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07003268 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, "
Eric Laurent81784c32012-11-19 14:55:58 -08003269 "mFrameCount=%d, mNormalFrameCount=%d",
3270 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3271 mNormalFrameCount);
3272 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3273
Andy Hungfbfc3952015-01-15 13:33:51 -08003274 if (type == DUPLICATING) {
3275 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3276 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3277 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3278 return;
3279 }
Eric Laurent81784c32012-11-19 14:55:58 -08003280 // create an NBAIO sink for the HAL output stream, and negotiate
3281 mOutputSink = new AudioStreamOutSink(output->stream);
3282 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003283 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Eric Laurent81784c32012-11-19 14:55:58 -08003284 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
3285 ALOG_ASSERT(index == 0);
3286
3287 // initialize fast mixer depending on configuration
3288 bool initFastMixer;
3289 switch (kUseFastMixer) {
3290 case FastMixer_Never:
3291 initFastMixer = false;
3292 break;
3293 case FastMixer_Always:
3294 initFastMixer = true;
3295 break;
3296 case FastMixer_Static:
3297 case FastMixer_Dynamic:
3298 initFastMixer = mFrameCount < mNormalFrameCount;
3299 break;
3300 }
3301 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003302 audio_format_t fastMixerFormat;
3303 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3304 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3305 } else {
3306 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3307 }
3308 if (mFormat != fastMixerFormat) {
3309 // change our Sink format to accept our intermediate precision
3310 mFormat = fastMixerFormat;
3311 free(mSinkBuffer);
3312 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3313 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3314 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3315 }
Eric Laurent81784c32012-11-19 14:55:58 -08003316
3317 // create a MonoPipe to connect our submix to FastMixer
3318 NBAIO_Format format = mOutputSink->format();
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003319 NBAIO_Format origformat = format;
Andy Hung1258c1a2014-05-23 21:22:17 -07003320 // adjust format to match that of the Fast Mixer
Glenn Kasten97b7b752014-09-28 13:04:24 -07003321 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003322 format.mFormat = fastMixerFormat;
3323 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3324
Eric Laurent81784c32012-11-19 14:55:58 -08003325 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3326 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3327 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3328 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3329 const NBAIO_Format offers[1] = {format};
3330 size_t numCounterOffers = 0;
3331 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
3332 ALOG_ASSERT(index == 0);
3333 monoPipe->setAvgFrames((mScreenState & 1) ?
3334 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3335 mPipeSink = monoPipe;
3336
Glenn Kasten46909e72013-02-26 09:20:22 -08003337#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08003338 if (mTeeSinkOutputEnabled) {
3339 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003340 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
3341 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08003342 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003343 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003344 ALOG_ASSERT(index == 0);
3345 mTeeSink = teeSink;
3346 PipeReader *teeSource = new PipeReader(*teeSink);
3347 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003348 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003349 ALOG_ASSERT(index == 0);
3350 mTeeSource = teeSource;
3351 }
Glenn Kasten46909e72013-02-26 09:20:22 -08003352#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003353
3354 // create fast mixer and configure it initially with just one fast track for our submix
3355 mFastMixer = new FastMixer();
3356 FastMixerStateQueue *sq = mFastMixer->sq();
3357#ifdef STATE_QUEUE_DUMP
3358 sq->setObserverDump(&mStateQueueObserverDump);
3359 sq->setMutatorDump(&mStateQueueMutatorDump);
3360#endif
3361 FastMixerState *state = sq->begin();
3362 FastTrack *fastTrack = &state->mFastTracks[0];
3363 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3364 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3365 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003366 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3367 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003368 fastTrack->mGeneration++;
3369 state->mFastTracksGen++;
3370 state->mTrackMask = 1;
3371 // fast mixer will use the HAL output sink
3372 state->mOutputSink = mOutputSink.get();
3373 state->mOutputSinkGen++;
3374 state->mFrameCount = mFrameCount;
3375 state->mCommand = FastMixerState::COLD_IDLE;
3376 // already done in constructor initialization list
3377 //mFastMixerFutex = 0;
3378 state->mColdFutexAddr = &mFastMixerFutex;
3379 state->mColdGen++;
3380 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08003381#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003382 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08003383#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08003384 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3385 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003386 sq->end();
3387 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3388
3389 // start the fast mixer
3390 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3391 pid_t tid = mFastMixer->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003392 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003393
3394#ifdef AUDIO_WATCHDOG
3395 // create and start the watchdog
3396 mAudioWatchdog = new AudioWatchdog();
3397 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3398 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3399 tid = mAudioWatchdog->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003400 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003401#endif
3402
Eric Laurent81784c32012-11-19 14:55:58 -08003403 }
3404
3405 switch (kUseFastMixer) {
3406 case FastMixer_Never:
3407 case FastMixer_Dynamic:
3408 mNormalSink = mOutputSink;
3409 break;
3410 case FastMixer_Always:
3411 mNormalSink = mPipeSink;
3412 break;
3413 case FastMixer_Static:
3414 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3415 break;
3416 }
3417}
3418
3419AudioFlinger::MixerThread::~MixerThread()
3420{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003421 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003422 FastMixerStateQueue *sq = mFastMixer->sq();
3423 FastMixerState *state = sq->begin();
3424 if (state->mCommand == FastMixerState::COLD_IDLE) {
3425 int32_t old = android_atomic_inc(&mFastMixerFutex);
3426 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003427 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003428 }
3429 }
3430 state->mCommand = FastMixerState::EXIT;
3431 sq->end();
3432 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3433 mFastMixer->join();
3434 // Though the fast mixer thread has exited, it's state queue is still valid.
3435 // We'll use that extract the final state which contains one remaining fast track
3436 // corresponding to our sub-mix.
3437 state = sq->begin();
3438 ALOG_ASSERT(state->mTrackMask == 1);
3439 FastTrack *fastTrack = &state->mFastTracks[0];
3440 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3441 delete fastTrack->mBufferProvider;
3442 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003443 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003444#ifdef AUDIO_WATCHDOG
3445 if (mAudioWatchdog != 0) {
3446 mAudioWatchdog->requestExit();
3447 mAudioWatchdog->requestExitAndWait();
3448 mAudioWatchdog.clear();
3449 }
3450#endif
3451 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003452 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003453 delete mAudioMixer;
3454}
3455
3456
3457uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3458{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003459 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003460 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3461 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3462 }
3463 return latency;
3464}
3465
3466
3467void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3468{
3469 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3470}
3471
Eric Laurentbfb1b832013-01-07 09:53:42 -08003472ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003473{
3474 // FIXME we should only do one push per cycle; confirm this is true
3475 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003476 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003477 FastMixerStateQueue *sq = mFastMixer->sq();
3478 FastMixerState *state = sq->begin();
3479 if (state->mCommand != FastMixerState::MIX_WRITE &&
3480 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3481 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07003482
3483 // FIXME workaround for first HAL write being CPU bound on some devices
3484 ATRACE_BEGIN("write");
3485 mOutput->write((char *)mSinkBuffer, 0);
3486 ATRACE_END();
3487
Eric Laurent81784c32012-11-19 14:55:58 -08003488 int32_t old = android_atomic_inc(&mFastMixerFutex);
3489 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003490 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003491 }
3492#ifdef AUDIO_WATCHDOG
3493 if (mAudioWatchdog != 0) {
3494 mAudioWatchdog->resume();
3495 }
3496#endif
3497 }
3498 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08003499#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003500 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08003501 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08003502#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003503 sq->end();
3504 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3505 if (kUseFastMixer == FastMixer_Dynamic) {
3506 mNormalSink = mPipeSink;
3507 }
3508 } else {
3509 sq->end(false /*didModify*/);
3510 }
3511 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003512 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003513}
3514
3515void AudioFlinger::MixerThread::threadLoop_standby()
3516{
3517 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003518 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003519 FastMixerStateQueue *sq = mFastMixer->sq();
3520 FastMixerState *state = sq->begin();
3521 if (!(state->mCommand & FastMixerState::IDLE)) {
3522 state->mCommand = FastMixerState::COLD_IDLE;
3523 state->mColdFutexAddr = &mFastMixerFutex;
3524 state->mColdGen++;
3525 mFastMixerFutex = 0;
3526 sq->end();
3527 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3528 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3529 if (kUseFastMixer == FastMixer_Dynamic) {
3530 mNormalSink = mOutputSink;
3531 }
3532#ifdef AUDIO_WATCHDOG
3533 if (mAudioWatchdog != 0) {
3534 mAudioWatchdog->pause();
3535 }
3536#endif
3537 } else {
3538 sq->end(false /*didModify*/);
3539 }
3540 }
3541 PlaybackThread::threadLoop_standby();
3542}
3543
Eric Laurentbfb1b832013-01-07 09:53:42 -08003544bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3545{
3546 return false;
3547}
3548
3549bool AudioFlinger::PlaybackThread::shouldStandby_l()
3550{
3551 return !mStandby;
3552}
3553
3554bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3555{
3556 Mutex::Autolock _l(mLock);
3557 return waitingAsyncCallback_l();
3558}
3559
Eric Laurent81784c32012-11-19 14:55:58 -08003560// shared by MIXER and DIRECT, overridden by DUPLICATING
3561void AudioFlinger::PlaybackThread::threadLoop_standby()
3562{
3563 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08003564 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003565 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003566 // discard any pending drain or write ack by incrementing sequence
3567 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3568 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003569 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003570 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3571 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003572 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003573 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003574}
3575
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003576void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3577{
3578 ALOGV("signal playback thread");
3579 broadcast_l();
3580}
3581
Eric Laurent81784c32012-11-19 14:55:58 -08003582void AudioFlinger::MixerThread::threadLoop_mix()
3583{
3584 // obtain the presentation timestamp of the next output buffer
3585 int64_t pts;
3586 status_t status = INVALID_OPERATION;
3587
3588 if (mNormalSink != 0) {
3589 status = mNormalSink->getNextWriteTimestamp(&pts);
3590 } else {
3591 status = mOutputSink->getNextWriteTimestamp(&pts);
3592 }
3593
3594 if (status != NO_ERROR) {
3595 pts = AudioBufferProvider::kInvalidPTS;
3596 }
3597
3598 // mix buffers...
3599 mAudioMixer->process(pts);
Andy Hung25c2dac2014-02-27 14:56:00 -08003600 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003601 // increase sleep time progressively when application underrun condition clears.
3602 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3603 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3604 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003605 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003606 sleepTimeShift--;
3607 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003608 mSleepTimeUs = 0;
3609 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08003610 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003611
Eric Laurent81784c32012-11-19 14:55:58 -08003612}
3613
3614void AudioFlinger::MixerThread::threadLoop_sleepTime()
3615{
3616 // If no tracks are ready, sleep once for the duration of an output
3617 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003618 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003619 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003620 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
3621 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
3622 mSleepTimeUs = kMinThreadSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003623 }
3624 // reduce sleep time in case of consecutive application underruns to avoid
3625 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3626 // duration we would end up writing less data than needed by the audio HAL if
3627 // the condition persists.
3628 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3629 sleepTimeShift++;
3630 }
3631 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003632 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003633 }
3634 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003635 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3636 // before effects processing or output.
3637 if (mMixerBufferValid) {
3638 memset(mMixerBuffer, 0, mMixerBufferSize);
3639 } else {
3640 memset(mSinkBuffer, 0, mSinkBufferSize);
3641 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003642 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003643 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3644 "anticipated start");
3645 }
3646 // TODO add standby time extension fct of effect tail
3647}
3648
3649// prepareTracks_l() must be called with ThreadBase::mLock held
3650AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3651 Vector< sp<Track> > *tracksToRemove)
3652{
3653
3654 mixer_state mixerStatus = MIXER_IDLE;
3655 // find out which tracks need to be processed
3656 size_t count = mActiveTracks.size();
3657 size_t mixedTracks = 0;
3658 size_t tracksWithEffect = 0;
3659 // counts only _active_ fast tracks
3660 size_t fastTracks = 0;
3661 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
3662
3663 float masterVolume = mMasterVolume;
3664 bool masterMute = mMasterMute;
3665
3666 if (masterMute) {
3667 masterVolume = 0;
3668 }
3669 // Delegate master volume control to effect in output mix effect chain if needed
3670 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3671 if (chain != 0) {
3672 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
3673 chain->setVolume_l(&v, &v);
3674 masterVolume = (float)((v + (1 << 23)) >> 24);
3675 chain.clear();
3676 }
3677
3678 // prepare a new state to push
3679 FastMixerStateQueue *sq = NULL;
3680 FastMixerState *state = NULL;
3681 bool didModify = false;
3682 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003683 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003684 sq = mFastMixer->sq();
3685 state = sq->begin();
3686 }
3687
Andy Hung69aed5f2014-02-25 17:24:40 -08003688 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08003689 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08003690
Eric Laurent81784c32012-11-19 14:55:58 -08003691 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003692 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003693 if (t == 0) {
3694 continue;
3695 }
3696
3697 // this const just means the local variable doesn't change
3698 Track* const track = t.get();
3699
3700 // process fast tracks
3701 if (track->isFastTrack()) {
3702
3703 // It's theoretically possible (though unlikely) for a fast track to be created
3704 // and then removed within the same normal mix cycle. This is not a problem, as
3705 // the track never becomes active so it's fast mixer slot is never touched.
3706 // The converse, of removing an (active) track and then creating a new track
3707 // at the identical fast mixer slot within the same normal mix cycle,
3708 // is impossible because the slot isn't marked available until the end of each cycle.
3709 int j = track->mFastIndex;
3710 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
3711 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
3712 FastTrack *fastTrack = &state->mFastTracks[j];
3713
3714 // Determine whether the track is currently in underrun condition,
3715 // and whether it had a recent underrun.
3716 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
3717 FastTrackUnderruns underruns = ftDump->mUnderruns;
3718 uint32_t recentFull = (underruns.mBitFields.mFull -
3719 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
3720 uint32_t recentPartial = (underruns.mBitFields.mPartial -
3721 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
3722 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
3723 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
3724 uint32_t recentUnderruns = recentPartial + recentEmpty;
3725 track->mObservedUnderruns = underruns;
3726 // don't count underruns that occur while stopping or pausing
3727 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07003728 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
3729 recentUnderruns > 0) {
3730 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
3731 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003732 }
3733
3734 // This is similar to the state machine for normal tracks,
3735 // with a few modifications for fast tracks.
3736 bool isActive = true;
3737 switch (track->mState) {
3738 case TrackBase::STOPPING_1:
3739 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08003740 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003741 track->mState = TrackBase::STOPPING_2;
3742 }
3743 break;
3744 case TrackBase::PAUSING:
3745 // ramp down is not yet implemented
3746 track->setPaused();
3747 break;
3748 case TrackBase::RESUMING:
3749 // ramp up is not yet implemented
3750 track->mState = TrackBase::ACTIVE;
3751 break;
3752 case TrackBase::ACTIVE:
3753 if (recentFull > 0 || recentPartial > 0) {
3754 // track has provided at least some frames recently: reset retry count
3755 track->mRetryCount = kMaxTrackRetries;
3756 }
3757 if (recentUnderruns == 0) {
3758 // no recent underruns: stay active
3759 break;
3760 }
3761 // there has recently been an underrun of some kind
3762 if (track->sharedBuffer() == 0) {
3763 // were any of the recent underruns "empty" (no frames available)?
3764 if (recentEmpty == 0) {
3765 // no, then ignore the partial underruns as they are allowed indefinitely
3766 break;
3767 }
3768 // there has recently been an "empty" underrun: decrement the retry counter
3769 if (--(track->mRetryCount) > 0) {
3770 break;
3771 }
3772 // indicate to client process that the track was disabled because of underrun;
3773 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003774 android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003775 // remove from active list, but state remains ACTIVE [confusing but true]
3776 isActive = false;
3777 break;
3778 }
3779 // fall through
3780 case TrackBase::STOPPING_2:
3781 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003782 case TrackBase::STOPPED:
3783 case TrackBase::FLUSHED: // flush() while active
3784 // Check for presentation complete if track is inactive
3785 // We have consumed all the buffers of this track.
3786 // This would be incomplete if we auto-paused on underrun
3787 {
3788 size_t audioHALFrames =
3789 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3790 size_t framesWritten = mBytesWritten / mFrameSize;
3791 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
3792 // track stays in active list until presentation is complete
3793 break;
3794 }
3795 }
3796 if (track->isStopping_2()) {
3797 track->mState = TrackBase::STOPPED;
3798 }
3799 if (track->isStopped()) {
3800 // Can't reset directly, as fast mixer is still polling this track
3801 // track->reset();
3802 // So instead mark this track as needing to be reset after push with ack
3803 resetMask |= 1 << i;
3804 }
3805 isActive = false;
3806 break;
3807 case TrackBase::IDLE:
3808 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08003809 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08003810 }
3811
3812 if (isActive) {
3813 // was it previously inactive?
3814 if (!(state->mTrackMask & (1 << j))) {
3815 ExtendedAudioBufferProvider *eabp = track;
3816 VolumeProvider *vp = track;
3817 fastTrack->mBufferProvider = eabp;
3818 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08003819 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003820 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08003821 fastTrack->mGeneration++;
3822 state->mTrackMask |= 1 << j;
3823 didModify = true;
3824 // no acknowledgement required for newly active tracks
3825 }
3826 // cache the combined master volume and stream type volume for fast mixer; this
3827 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08003828 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08003829 ++fastTracks;
3830 } else {
3831 // was it previously active?
3832 if (state->mTrackMask & (1 << j)) {
3833 fastTrack->mBufferProvider = NULL;
3834 fastTrack->mGeneration++;
3835 state->mTrackMask &= ~(1 << j);
3836 didModify = true;
3837 // If any fast tracks were removed, we must wait for acknowledgement
3838 // because we're about to decrement the last sp<> on those tracks.
3839 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3840 } else {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003841 LOG_ALWAYS_FATAL("fast track %d should have been active", j);
Eric Laurent81784c32012-11-19 14:55:58 -08003842 }
3843 tracksToRemove->add(track);
3844 // Avoids a misleading display in dumpsys
3845 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
3846 }
3847 continue;
3848 }
3849
3850 { // local variable scope to avoid goto warning
3851
3852 audio_track_cblk_t* cblk = track->cblk();
3853
3854 // The first time a track is added we wait
3855 // for all its buffers to be filled before processing it
3856 int name = track->name();
3857 // make sure that we have enough frames to mix one full buffer.
3858 // enforce this condition only once to enable draining the buffer in case the client
3859 // app does not call stop() and relies on underrun to stop:
3860 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
3861 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003862 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07003863 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07003864 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07003865
3866 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07003867 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07003868 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
3869 // add frames already consumed but not yet released by the resampler
3870 // because mAudioTrackServerProxy->framesReady() will include these frames
3871 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
3872
Eric Laurent81784c32012-11-19 14:55:58 -08003873 uint32_t minFrames = 1;
3874 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
3875 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003876 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08003877 }
Eric Laurent13e4c962013-12-20 17:36:01 -08003878
3879 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07003880 if (ATRACE_ENABLED()) {
3881 // I wish we had formatted trace names
3882 char traceName[16];
3883 strcpy(traceName, "nRdy");
3884 int name = track->name();
3885 if (AudioMixer::TRACK0 <= name &&
3886 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
3887 name -= AudioMixer::TRACK0;
3888 traceName[4] = (name / 10) + '0';
3889 traceName[5] = (name % 10) + '0';
3890 } else {
3891 traceName[4] = '?';
3892 traceName[5] = '?';
3893 }
3894 traceName[6] = '\0';
3895 ATRACE_INT(traceName, framesReady);
3896 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003897 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08003898 !track->isPaused() && !track->isTerminated())
3899 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003900 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003901
3902 mixedTracks++;
3903
Andy Hung69aed5f2014-02-25 17:24:40 -08003904 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
3905 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08003906 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08003907 if (track->mainBuffer() != mSinkBuffer &&
3908 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08003909 if (mEffectBufferEnabled) {
3910 mEffectBufferValid = true; // Later can set directly.
3911 }
Eric Laurent81784c32012-11-19 14:55:58 -08003912 chain = getEffectChain_l(track->sessionId());
3913 // Delegate volume control to effect in track effect chain if needed
3914 if (chain != 0) {
3915 tracksWithEffect++;
3916 } else {
3917 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
3918 "session %d",
3919 name, track->sessionId());
3920 }
3921 }
3922
3923
3924 int param = AudioMixer::VOLUME;
3925 if (track->mFillingUpStatus == Track::FS_FILLED) {
3926 // no ramp for the first volume setting
3927 track->mFillingUpStatus = Track::FS_ACTIVE;
3928 if (track->mState == TrackBase::RESUMING) {
3929 track->mState = TrackBase::ACTIVE;
3930 param = AudioMixer::RAMP_VOLUME;
3931 }
3932 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003933 // FIXME should not make a decision based on mServer
3934 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003935 // If the track is stopped before the first frame was mixed,
3936 // do not apply ramp
3937 param = AudioMixer::RAMP_VOLUME;
3938 }
3939
3940 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07003941 uint32_t vl, vr; // in U8.24 integer format
3942 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08003943 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07003944 vl = vr = 0;
3945 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08003946 if (track->isPausing()) {
3947 track->setPaused();
3948 }
3949 } else {
3950
3951 // read original volumes with volume control
3952 float typeVolume = mStreamTypes[track->streamType()].volume;
3953 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003954 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07003955 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07003956 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
3957 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08003958 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07003959 if (vlf > GAIN_FLOAT_UNITY) {
3960 ALOGV("Track left volume out of range: %.3g", vlf);
3961 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003962 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07003963 if (vrf > GAIN_FLOAT_UNITY) {
3964 ALOGV("Track right volume out of range: %.3g", vrf);
3965 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003966 }
3967 // now apply the master volume and stream type volume
Andy Hung6be49402014-05-30 10:42:03 -07003968 vlf *= v;
3969 vrf *= v;
Eric Laurent81784c32012-11-19 14:55:58 -08003970 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07003971 // then derive vl and vr as U8.24 versions for the effect chain
3972 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
3973 vl = (uint32_t) (scaleto8_24 * vlf);
3974 vr = (uint32_t) (scaleto8_24 * vrf);
3975 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08003976 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08003977 // send level comes from shared memory and so may be corrupt
3978 if (sendLevel > MAX_GAIN_INT) {
3979 ALOGV("Track send level out of range: %04X", sendLevel);
3980 sendLevel = MAX_GAIN_INT;
3981 }
Andy Hung6be49402014-05-30 10:42:03 -07003982 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
3983 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08003984 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003985
Eric Laurent81784c32012-11-19 14:55:58 -08003986 // Delegate volume control to effect in track effect chain if needed
3987 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3988 // Do not ramp volume if volume is controlled by effect
3989 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08003990 // Update remaining floating point volume levels
3991 vlf = (float)vl / (1 << 24);
3992 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08003993 track->mHasVolumeController = true;
3994 } else {
3995 // force no volume ramp when volume controller was just disabled or removed
3996 // from effect chain to avoid volume spike
3997 if (track->mHasVolumeController) {
3998 param = AudioMixer::VOLUME;
3999 }
4000 track->mHasVolumeController = false;
4001 }
4002
Eric Laurent81784c32012-11-19 14:55:58 -08004003 // XXX: these things DON'T need to be done each time
4004 mAudioMixer->setBufferProvider(name, track);
4005 mAudioMixer->enable(name);
4006
Andy Hung6be49402014-05-30 10:42:03 -07004007 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
4008 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
4009 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08004010 mAudioMixer->setParameter(
4011 name,
4012 AudioMixer::TRACK,
4013 AudioMixer::FORMAT, (void *)track->format());
4014 mAudioMixer->setParameter(
4015 name,
4016 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004017 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07004018 mAudioMixer->setParameter(
4019 name,
4020 AudioMixer::TRACK,
4021 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08004022 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07004023 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004024 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08004025 if (reqSampleRate == 0) {
4026 reqSampleRate = mSampleRate;
4027 } else if (reqSampleRate > maxSampleRate) {
4028 reqSampleRate = maxSampleRate;
4029 }
Eric Laurent81784c32012-11-19 14:55:58 -08004030 mAudioMixer->setParameter(
4031 name,
4032 AudioMixer::RESAMPLE,
4033 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004034 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004035
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004036 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004037 mAudioMixer->setParameter(
4038 name,
4039 AudioMixer::TIMESTRETCH,
4040 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004041 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004042
Andy Hung69aed5f2014-02-25 17:24:40 -08004043 /*
4044 * Select the appropriate output buffer for the track.
4045 *
Andy Hung98ef9782014-03-04 14:46:50 -08004046 * Tracks with effects go into their own effects chain buffer
4047 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08004048 *
4049 * Other tracks can use mMixerBuffer for higher precision
4050 * channel accumulation. If this buffer is enabled
4051 * (mMixerBufferEnabled true), then selected tracks will accumulate
4052 * into it.
4053 *
4054 */
4055 if (mMixerBufferEnabled
4056 && (track->mainBuffer() == mSinkBuffer
4057 || track->mainBuffer() == mMixerBuffer)) {
4058 mAudioMixer->setParameter(
4059 name,
4060 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004061 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08004062 mAudioMixer->setParameter(
4063 name,
4064 AudioMixer::TRACK,
4065 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
4066 // TODO: override track->mainBuffer()?
4067 mMixerBufferValid = true;
4068 } else {
4069 mAudioMixer->setParameter(
4070 name,
4071 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004072 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08004073 mAudioMixer->setParameter(
4074 name,
4075 AudioMixer::TRACK,
4076 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
4077 }
Eric Laurent81784c32012-11-19 14:55:58 -08004078 mAudioMixer->setParameter(
4079 name,
4080 AudioMixer::TRACK,
4081 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
4082
4083 // reset retry count
4084 track->mRetryCount = kMaxTrackRetries;
4085
4086 // If one track is ready, set the mixer ready if:
4087 // - the mixer was not ready during previous round OR
4088 // - no other track is not ready
4089 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
4090 mixerStatus != MIXER_TRACKS_ENABLED) {
4091 mixerStatus = MIXER_TRACKS_READY;
4092 }
4093 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004094 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hung08fb1742015-05-31 23:22:10 -07004095 ALOGV("track(%p) underrun, framesReady(%zu) < framesDesired(%zd)",
4096 track, framesReady, desiredFrames);
Glenn Kasten82aaf942013-07-17 16:05:07 -07004097 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004098 }
Eric Laurent81784c32012-11-19 14:55:58 -08004099 // clear effect chain input buffer if an active track underruns to avoid sending
4100 // previous audio buffer again to effects
4101 chain = getEffectChain_l(track->sessionId());
4102 if (chain != 0) {
4103 chain->clearInputBuffer();
4104 }
4105
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004106 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004107 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
4108 track->isStopped() || track->isPaused()) {
4109 // We have consumed all the buffers of this track.
4110 // Remove it from the list of active tracks.
4111 // TODO: use actual buffer filling status instead of latency when available from
4112 // audio HAL
4113 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
4114 size_t framesWritten = mBytesWritten / mFrameSize;
4115 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
4116 if (track->isStopped()) {
4117 track->reset();
4118 }
4119 tracksToRemove->add(track);
4120 }
4121 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08004122 // No buffers for this track. Give it a few chances to
4123 // fill a buffer, then remove it from active list.
4124 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004125 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004126 tracksToRemove->add(track);
4127 // indicate to client process that the track was disabled because of underrun;
4128 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07004129 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08004130 // If one track is not ready, mark the mixer also not ready if:
4131 // - the mixer was ready during previous round OR
4132 // - no other track is ready
4133 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
4134 mixerStatus != MIXER_TRACKS_READY) {
4135 mixerStatus = MIXER_TRACKS_ENABLED;
4136 }
4137 }
4138 mAudioMixer->disable(name);
4139 }
4140
4141 } // local variable scope to avoid goto warning
4142track_is_ready: ;
4143
4144 }
4145
4146 // Push the new FastMixer state if necessary
4147 bool pauseAudioWatchdog = false;
4148 if (didModify) {
4149 state->mFastTracksGen++;
4150 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4151 if (kUseFastMixer == FastMixer_Dynamic &&
4152 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4153 state->mCommand = FastMixerState::COLD_IDLE;
4154 state->mColdFutexAddr = &mFastMixerFutex;
4155 state->mColdGen++;
4156 mFastMixerFutex = 0;
4157 if (kUseFastMixer == FastMixer_Dynamic) {
4158 mNormalSink = mOutputSink;
4159 }
4160 // If we go into cold idle, need to wait for acknowledgement
4161 // so that fast mixer stops doing I/O.
4162 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4163 pauseAudioWatchdog = true;
4164 }
Eric Laurent81784c32012-11-19 14:55:58 -08004165 }
4166 if (sq != NULL) {
4167 sq->end(didModify);
4168 sq->push(block);
4169 }
4170#ifdef AUDIO_WATCHDOG
4171 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4172 mAudioWatchdog->pause();
4173 }
4174#endif
4175
4176 // Now perform the deferred reset on fast tracks that have stopped
4177 while (resetMask != 0) {
4178 size_t i = __builtin_ctz(resetMask);
4179 ALOG_ASSERT(i < count);
4180 resetMask &= ~(1 << i);
4181 sp<Track> t = mActiveTracks[i].promote();
4182 if (t == 0) {
4183 continue;
4184 }
4185 Track* track = t.get();
4186 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
4187 track->reset();
4188 }
4189
4190 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004191 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004192
Eric Laurent97d547d2014-09-02 14:45:53 -07004193 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
4194 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07004195 }
4196
4197 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07004198 // as long as there are effects we should clear the effects buffer, to avoid
4199 // passing a non-clean buffer to the effect chain
4200 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07004201 }
Andy Hung69aed5f2014-02-25 17:24:40 -08004202 // sink or mix buffer must be cleared if all tracks are connected to an
4203 // effect chain as in this case the mixer will not write to the sink or mix buffer
4204 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08004205 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4206 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08004207 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08004208 if (mMixerBufferValid) {
4209 memset(mMixerBuffer, 0, mMixerBufferSize);
4210 // TODO: In testing, mSinkBuffer below need not be cleared because
4211 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
4212 // after mixing.
4213 //
4214 // To enforce this guarantee:
4215 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4216 // (mixedTracks == 0 && fastTracks > 0))
4217 // must imply MIXER_TRACKS_READY.
4218 // Later, we may clear buffers regardless, and skip much of this logic.
4219 }
Andy Hung98ef9782014-03-04 14:46:50 -08004220 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07004221 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004222 }
4223
4224 // if any fast tracks, then status is ready
4225 mMixerStatusIgnoringFastTracks = mixerStatus;
4226 if (fastTracks > 0) {
4227 mixerStatus = MIXER_TRACKS_READY;
4228 }
4229 return mixerStatus;
4230}
4231
4232// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07004233int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
4234 audio_format_t format, int sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08004235{
Andy Hunge8a1ced2014-05-09 15:02:21 -07004236 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08004237}
4238
4239// deleteTrackName_l() must be called with ThreadBase::mLock held
4240void AudioFlinger::MixerThread::deleteTrackName_l(int name)
4241{
4242 ALOGV("remove track (%d) and delete from mixer", name);
4243 mAudioMixer->deleteTrackName(name);
4244}
4245
Eric Laurent10351942014-05-08 18:49:52 -07004246// checkForNewParameter_l() must be called with ThreadBase::mLock held
4247bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
4248 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004249{
Eric Laurent81784c32012-11-19 14:55:58 -08004250 bool reconfig = false;
4251
Eric Laurent10351942014-05-08 18:49:52 -07004252 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004253
Eric Laurent10351942014-05-08 18:49:52 -07004254 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
4255 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004256 if (mFastMixer != 0) {
Eric Laurent10351942014-05-08 18:49:52 -07004257 FastMixerStateQueue *sq = mFastMixer->sq();
4258 FastMixerState *state = sq->begin();
4259 if (!(state->mCommand & FastMixerState::IDLE)) {
4260 previousCommand = state->mCommand;
4261 state->mCommand = FastMixerState::HOT_IDLE;
4262 sq->end();
4263 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
4264 } else {
4265 sq->end(false /*didModify*/);
Eric Laurent81784c32012-11-19 14:55:58 -08004266 }
Eric Laurent10351942014-05-08 18:49:52 -07004267 }
Eric Laurent81784c32012-11-19 14:55:58 -08004268
Eric Laurent10351942014-05-08 18:49:52 -07004269 AudioParameter param = AudioParameter(keyValuePair);
4270 int value;
4271 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4272 reconfig = true;
4273 }
4274 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004275 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004276 status = BAD_VALUE;
4277 } else {
4278 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08004279 reconfig = true;
4280 }
Eric Laurent10351942014-05-08 18:49:52 -07004281 }
4282 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004283 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004284 status = BAD_VALUE;
4285 } else {
4286 // no need to save value, since it's constant
4287 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004288 }
Eric Laurent10351942014-05-08 18:49:52 -07004289 }
4290 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4291 // do not accept frame count changes if tracks are open as the track buffer
4292 // size depends on frame count and correct behavior would not be guaranteed
4293 // if frame count is changed after track creation
4294 if (!mTracks.isEmpty()) {
4295 status = INVALID_OPERATION;
4296 } else {
4297 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004298 }
Eric Laurent10351942014-05-08 18:49:52 -07004299 }
4300 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004301#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07004302 // when changing the audio output device, call addBatteryData to notify
4303 // the change
4304 if (mOutDevice != value) {
4305 uint32_t params = 0;
4306 // check whether speaker is on
4307 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
4308 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08004309 }
Eric Laurent10351942014-05-08 18:49:52 -07004310
4311 audio_devices_t deviceWithoutSpeaker
4312 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
4313 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07004314 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07004315 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4316 }
4317
4318 if (params != 0) {
4319 addBatteryData(params);
4320 }
4321 }
Eric Laurent81784c32012-11-19 14:55:58 -08004322#endif
4323
Eric Laurent10351942014-05-08 18:49:52 -07004324 // forward device change to effects that have requested to be
4325 // aware of attached audio device.
4326 if (value != AUDIO_DEVICE_NONE) {
4327 mOutDevice = value;
4328 for (size_t i = 0; i < mEffectChains.size(); i++) {
4329 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08004330 }
4331 }
Eric Laurent10351942014-05-08 18:49:52 -07004332 }
Eric Laurent81784c32012-11-19 14:55:58 -08004333
Eric Laurent10351942014-05-08 18:49:52 -07004334 if (status == NO_ERROR) {
4335 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4336 keyValuePair.string());
4337 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004338 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004339 mStandby = true;
4340 mBytesWritten = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004341 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Eric Laurent10351942014-05-08 18:49:52 -07004342 keyValuePair.string());
Eric Laurent81784c32012-11-19 14:55:58 -08004343 }
Eric Laurent10351942014-05-08 18:49:52 -07004344 if (status == NO_ERROR && reconfig) {
4345 readOutputParameters_l();
4346 delete mAudioMixer;
4347 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4348 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07004349 int name = getTrackName_l(mTracks[i]->mChannelMask,
4350 mTracks[i]->mFormat, mTracks[i]->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07004351 if (name < 0) {
4352 break;
4353 }
4354 mTracks[i]->mName = name;
4355 }
Eric Laurent73e26b62015-04-27 16:55:58 -07004356 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004357 }
Eric Laurent81784c32012-11-19 14:55:58 -08004358 }
4359
4360 if (!(previousCommand & FastMixerState::IDLE)) {
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004361 ALOG_ASSERT(mFastMixer != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08004362 FastMixerStateQueue *sq = mFastMixer->sq();
4363 FastMixerState *state = sq->begin();
4364 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
4365 state->mCommand = previousCommand;
4366 sq->end();
4367 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4368 }
4369
4370 return reconfig;
4371}
4372
4373
4374void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
4375{
4376 const size_t SIZE = 256;
4377 char buffer[SIZE];
4378 String8 result;
4379
4380 PlaybackThread::dumpInternals(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07004381 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Elliott Hughes87cebad2014-05-22 10:14:43 -07004382 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Eric Laurent81784c32012-11-19 14:55:58 -08004383
4384 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten4182c4e2013-07-15 14:45:07 -07004385 const FastMixerDumpState copy(mFastMixerDumpState);
Eric Laurent81784c32012-11-19 14:55:58 -08004386 copy.dump(fd);
4387
4388#ifdef STATE_QUEUE_DUMP
4389 // Similar for state queue
4390 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4391 observerCopy.dump(fd);
4392 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4393 mutatorCopy.dump(fd);
4394#endif
4395
Glenn Kasten46909e72013-02-26 09:20:22 -08004396#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08004397 // Write the tee output to a .wav file
4398 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08004399#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004400
4401#ifdef AUDIO_WATCHDOG
4402 if (mAudioWatchdog != 0) {
4403 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4404 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4405 wdCopy.dump(fd);
4406 }
4407#endif
4408}
4409
4410uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4411{
4412 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4413}
4414
4415uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4416{
4417 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4418}
4419
4420void AudioFlinger::MixerThread::cacheParameters_l()
4421{
4422 PlaybackThread::cacheParameters_l();
4423
4424 // FIXME: Relaxed timing because of a certain device that can't meet latency
4425 // Should be reduced to 2x after the vendor fixes the driver issue
4426 // increase threshold again due to low power audio mode. The way this warning
4427 // threshold is calculated and its usefulness should be reconsidered anyway.
4428 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4429}
4430
4431// ----------------------------------------------------------------------------
4432
4433AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07004434 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device, bool systemReady)
4435 : PlaybackThread(audioFlinger, output, id, device, DIRECT, systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08004436 // mLeftVolFloat, mRightVolFloat
4437{
4438}
4439
Eric Laurentbfb1b832013-01-07 09:53:42 -08004440AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4441 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07004442 ThreadBase::type_t type, bool systemReady)
4443 : PlaybackThread(audioFlinger, output, id, device, type, systemReady)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004444 // mLeftVolFloat, mRightVolFloat
4445{
4446}
4447
Eric Laurent81784c32012-11-19 14:55:58 -08004448AudioFlinger::DirectOutputThread::~DirectOutputThread()
4449{
4450}
4451
Eric Laurentbfb1b832013-01-07 09:53:42 -08004452void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
4453{
4454 audio_track_cblk_t* cblk = track->cblk();
4455 float left, right;
4456
4457 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4458 left = right = 0;
4459 } else {
4460 float typeVolume = mStreamTypes[track->streamType()].volume;
4461 float v = mMasterVolume * typeVolume;
4462 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004463 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4464 left = float_from_gain(gain_minifloat_unpack_left(vlr));
4465 if (left > GAIN_FLOAT_UNITY) {
4466 left = GAIN_FLOAT_UNITY;
4467 }
4468 left *= v;
4469 right = float_from_gain(gain_minifloat_unpack_right(vlr));
4470 if (right > GAIN_FLOAT_UNITY) {
4471 right = GAIN_FLOAT_UNITY;
4472 }
4473 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004474 }
4475
4476 if (lastTrack) {
4477 if (left != mLeftVolFloat || right != mRightVolFloat) {
4478 mLeftVolFloat = left;
4479 mRightVolFloat = right;
4480
4481 // Convert volumes from float to 8.24
4482 uint32_t vl = (uint32_t)(left * (1 << 24));
4483 uint32_t vr = (uint32_t)(right * (1 << 24));
4484
4485 // Delegate volume control to effect in track effect chain if needed
4486 // only one effect chain can be present on DirectOutputThread, so if
4487 // there is one, the track is connected to it
4488 if (!mEffectChains.isEmpty()) {
4489 mEffectChains[0]->setVolume_l(&vl, &vr);
4490 left = (float)vl / (1 << 24);
4491 right = (float)vr / (1 << 24);
4492 }
4493 if (mOutput->stream->set_volume) {
4494 mOutput->stream->set_volume(mOutput->stream, left, right);
4495 }
4496 }
4497 }
4498}
4499
Phil Burk43b4dcc2015-06-09 16:53:44 -07004500void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
4501{
4502 sp<Track> previousTrack = mPreviousTrack.promote();
4503 sp<Track> latestTrack = mLatestActiveTrack.promote();
4504
Eric Laurent0f0631e2015-07-06 18:01:25 -07004505 if (previousTrack != 0 && latestTrack != 0) {
4506 if (mType == DIRECT) {
4507 if (previousTrack.get() != latestTrack.get()) {
4508 mFlushPending = true;
4509 }
4510 } else /* mType == OFFLOAD */ {
4511 if (previousTrack->sessionId() != latestTrack->sessionId()) {
4512 mFlushPending = true;
4513 }
4514 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004515 }
4516 PlaybackThread::onAddNewTrack_l();
4517}
Eric Laurentbfb1b832013-01-07 09:53:42 -08004518
Eric Laurent81784c32012-11-19 14:55:58 -08004519AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4520 Vector< sp<Track> > *tracksToRemove
4521)
4522{
Eric Laurentd595b7c2013-04-03 17:27:56 -07004523 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08004524 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004525 bool doHwPause = false;
4526 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004527
4528 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07004529 for (size_t i = 0; i < count; i++) {
4530 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08004531 // The track died recently
4532 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004533 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08004534 }
4535
Phil Burk43b4dcc2015-06-09 16:53:44 -07004536 if (t->isInvalid()) {
4537 ALOGW("An invalidated track shouldn't be in active list");
4538 tracksToRemove->add(t);
4539 continue;
4540 }
4541
Eric Laurent81784c32012-11-19 14:55:58 -08004542 Track* const track = t.get();
4543 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07004544 // Only consider last track started for volume and mixer state control.
4545 // In theory an older track could underrun and restart after the new one starts
4546 // but as we only care about the transition phase between two tracks on a
4547 // direct output, it is not a problem to ignore the underrun case.
4548 sp<Track> l = mLatestActiveTrack.promote();
4549 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08004550
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004551 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004552 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004553 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004554 doHwPause = true;
4555 mHwPaused = true;
4556 }
4557 tracksToRemove->add(track);
4558 } else if (track->isFlushPending()) {
4559 track->flushAck();
4560 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004561 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004562 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004563 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004564 track->resumeAck();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004565 if (last && mHwPaused) {
4566 doHwResume = true;
4567 mHwPaused = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004568 }
4569 }
4570
Eric Laurent81784c32012-11-19 14:55:58 -08004571 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08004572 // for all its buffers to be filled before processing it.
4573 // Allow draining the buffer in case the client
4574 // app does not call stop() and relies on underrun to stop:
4575 // hence the test on (track->mRetryCount > 1).
4576 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07004577 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08004578 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08004579 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkca5e6142015-07-14 09:42:29 -07004580 && (track->mRetryCount > 1) && audio_is_linear_pcm(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004581 minFrames = mNormalFrameCount;
4582 } else {
4583 minFrames = 1;
4584 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004585
Eric Laurentab5cdba2014-06-09 17:22:27 -07004586 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4587 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08004588 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004589 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08004590
4591 if (track->mFillingUpStatus == Track::FS_FILLED) {
4592 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004593 // make sure processVolume_l() will apply new volume even if 0
4594 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004595 if (!mHwSupportsPause) {
4596 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08004597 }
4598 }
4599
4600 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004601 processVolume_l(track, last);
4602 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004603 sp<Track> previousTrack = mPreviousTrack.promote();
4604 if (previousTrack != 0) {
4605 if (track != previousTrack.get()) {
4606 // Flush any data still being written from last track
4607 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07004608 // Invalidate previous track to force a seek when resuming.
4609 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004610 }
4611 }
4612 mPreviousTrack = track;
4613
Eric Laurentd595b7c2013-04-03 17:27:56 -07004614 // reset retry count
4615 track->mRetryCount = kMaxTrackRetriesDirect;
4616 mActiveTrack = t;
4617 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07004618 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004619 doHwResume = true;
4620 mHwPaused = false;
4621 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004622 }
Eric Laurent81784c32012-11-19 14:55:58 -08004623 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004624 // clear effect chain input buffer if the last active track started underruns
4625 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07004626 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004627 mEffectChains[0]->clearInputBuffer();
4628 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004629 if (track->isStopping_1()) {
4630 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07004631 if (last && mHwPaused) {
4632 doHwResume = true;
4633 mHwPaused = false;
4634 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004635 }
4636 if ((track->sharedBuffer() != 0) || track->isStopped() ||
4637 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004638 // We have consumed all the buffers of this track.
4639 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07004640 size_t audioHALFrames;
4641 if (audio_is_linear_pcm(mFormat)) {
4642 audioHALFrames = (latency_l() * mSampleRate) / 1000;
4643 } else {
4644 audioHALFrames = 0;
4645 }
4646
Eric Laurent81784c32012-11-19 14:55:58 -08004647 size_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07004648 if (mStandby || !last ||
4649 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004650 if (track->isStopping_2()) {
4651 track->mState = TrackBase::STOPPED;
4652 }
Eric Laurent81784c32012-11-19 14:55:58 -08004653 if (track->isStopped()) {
4654 track->reset();
4655 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004656 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08004657 }
4658 } else {
4659 // No buffers for this track. Give it a few chances to
4660 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07004661 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08004662 if (--(track->mRetryCount) <= 0) {
4663 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07004664 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004665 // indicate to client process that the track was disabled because of underrun;
4666 // it will then automatically call start() when data is available
4667 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004668 } else if (last) {
Phil Burkca5e6142015-07-14 09:42:29 -07004669 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
4670 "minFrames = %u, mFormat = %#x",
4671 track->framesReady(), minFrames, mFormat);
Eric Laurent81784c32012-11-19 14:55:58 -08004672 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07004673 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004674 doHwPause = true;
4675 mHwPaused = true;
4676 }
Eric Laurent81784c32012-11-19 14:55:58 -08004677 }
4678 }
4679 }
4680 }
4681
Eric Laurentd1f69b02014-12-15 14:33:13 -08004682 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07004683 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004684 for (size_t i = 0; i < mTracks.size(); i++) {
4685 if (mTracks[i]->isFlushPending()) {
4686 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004687 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004688 }
4689 }
4690 }
4691
4692 // make sure the pause/flush/resume sequence is executed in the right order.
4693 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4694 // before flush and then resume HW. This can happen in case of pause/flush/resume
4695 // if resume is received before pause is executed.
4696 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07004697 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004698 mOutput->stream->pause(mOutput->stream);
4699 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004700 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004701 flushHw_l();
4702 }
4703 if (mHwSupportsPause && !mStandby && doHwResume) {
4704 mOutput->stream->resume(mOutput->stream);
4705 }
Eric Laurent81784c32012-11-19 14:55:58 -08004706 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004707 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004708
4709 return mixerStatus;
4710}
4711
4712void AudioFlinger::DirectOutputThread::threadLoop_mix()
4713{
Eric Laurent81784c32012-11-19 14:55:58 -08004714 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08004715 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004716 // output audio to hardware
4717 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07004718 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004719 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08004720 status_t status = mActiveTrack->getNextBuffer(&buffer);
4721 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08004722 memset(curBuf, 0, frameCount * mFrameSize);
4723 break;
4724 }
4725 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
4726 frameCount -= buffer.frameCount;
4727 curBuf += buffer.frameCount * mFrameSize;
4728 mActiveTrack->releaseBuffer(&buffer);
4729 }
Andy Hung2098f272014-02-27 14:00:06 -08004730 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004731 mSleepTimeUs = 0;
4732 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08004733 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004734}
4735
4736void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
4737{
Eric Laurentd1f69b02014-12-15 14:33:13 -08004738 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004739 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004740 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004741 return;
4742 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004743 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004744 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004745 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004746 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004747 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004748 }
4749 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08004750 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004751 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004752 }
4753}
4754
Eric Laurentd1f69b02014-12-15 14:33:13 -08004755void AudioFlinger::DirectOutputThread::threadLoop_exit()
4756{
4757 {
4758 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08004759 for (size_t i = 0; i < mTracks.size(); i++) {
4760 if (mTracks[i]->isFlushPending()) {
4761 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004762 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004763 }
4764 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004765 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004766 flushHw_l();
4767 }
4768 }
4769 PlaybackThread::threadLoop_exit();
4770}
4771
4772// must be called with thread mutex locked
4773bool AudioFlinger::DirectOutputThread::shouldStandby_l()
4774{
4775 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07004776 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004777
4778 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4779 // after a timeout and we will enter standby then.
4780 if (mTracks.size() > 0) {
4781 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07004782 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
4783 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004784 }
4785
Eric Laurent5cff4032015-05-26 13:49:58 -07004786 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08004787}
4788
Eric Laurent81784c32012-11-19 14:55:58 -08004789// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004790int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Andy Hunge8a1ced2014-05-09 15:02:21 -07004791 audio_format_t format __unused, int sessionId __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004792{
4793 return 0;
4794}
4795
4796// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004797void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004798{
4799}
4800
Eric Laurent10351942014-05-08 18:49:52 -07004801// checkForNewParameter_l() must be called with ThreadBase::mLock held
4802bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
4803 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004804{
4805 bool reconfig = false;
4806
Eric Laurent10351942014-05-08 18:49:52 -07004807 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004808
Eric Laurent10351942014-05-08 18:49:52 -07004809 AudioParameter param = AudioParameter(keyValuePair);
4810 int value;
4811 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4812 // forward device change to effects that have requested to be
4813 // aware of attached audio device.
4814 if (value != AUDIO_DEVICE_NONE) {
4815 mOutDevice = value;
4816 for (size_t i = 0; i < mEffectChains.size(); i++) {
4817 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07004818 }
4819 }
Eric Laurent81784c32012-11-19 14:55:58 -08004820 }
Eric Laurent10351942014-05-08 18:49:52 -07004821 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4822 // do not accept frame count changes if tracks are open as the track buffer
4823 // size depends on frame count and correct behavior would not be garantied
4824 // if frame count is changed after track creation
4825 if (!mTracks.isEmpty()) {
4826 status = INVALID_OPERATION;
4827 } else {
4828 reconfig = true;
4829 }
4830 }
4831 if (status == NO_ERROR) {
4832 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4833 keyValuePair.string());
4834 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004835 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004836 mStandby = true;
4837 mBytesWritten = 0;
4838 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4839 keyValuePair.string());
4840 }
4841 if (status == NO_ERROR && reconfig) {
4842 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07004843 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004844 }
4845 }
4846
Eric Laurent81784c32012-11-19 14:55:58 -08004847 return reconfig;
4848}
4849
4850uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
4851{
4852 uint32_t time;
4853 if (audio_is_linear_pcm(mFormat)) {
4854 time = PlaybackThread::activeSleepTimeUs();
4855 } else {
4856 time = 10000;
4857 }
4858 return time;
4859}
4860
4861uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
4862{
4863 uint32_t time;
4864 if (audio_is_linear_pcm(mFormat)) {
4865 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
4866 } else {
4867 time = 10000;
4868 }
4869 return time;
4870}
4871
4872uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
4873{
4874 uint32_t time;
4875 if (audio_is_linear_pcm(mFormat)) {
4876 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
4877 } else {
4878 time = 10000;
4879 }
4880 return time;
4881}
4882
4883void AudioFlinger::DirectOutputThread::cacheParameters_l()
4884{
4885 PlaybackThread::cacheParameters_l();
4886
4887 // use shorter standby delay as on normal output to release
4888 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07004889 // no delay on outputs with HW A/V sync
4890 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004891 mStandbyDelayNs = 0;
Eric Laurent5cff4032015-05-26 13:49:58 -07004892 } else if ((mType == OFFLOAD) && !audio_is_linear_pcm(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004893 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07004894 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004895 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07004896 }
Eric Laurent81784c32012-11-19 14:55:58 -08004897}
4898
Eric Laurente659ef42014-09-29 13:06:46 -07004899void AudioFlinger::DirectOutputThread::flushHw_l()
4900{
Phil Burk062e67a2015-02-11 13:40:50 -08004901 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08004902 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07004903 mFlushPending = false;
Eric Laurente659ef42014-09-29 13:06:46 -07004904}
4905
Eric Laurent81784c32012-11-19 14:55:58 -08004906// ----------------------------------------------------------------------------
4907
Eric Laurentbfb1b832013-01-07 09:53:42 -08004908AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07004909 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004910 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07004911 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07004912 mWriteAckSequence(0),
4913 mDrainSequence(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004914{
4915}
4916
4917AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
4918{
4919}
4920
4921void AudioFlinger::AsyncCallbackThread::onFirstRef()
4922{
4923 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
4924}
4925
4926bool AudioFlinger::AsyncCallbackThread::threadLoop()
4927{
4928 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004929 uint32_t writeAckSequence;
4930 uint32_t drainSequence;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004931
4932 {
4933 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08004934 while (!((mWriteAckSequence & 1) ||
4935 (mDrainSequence & 1) ||
4936 exitPending())) {
4937 mWaitWorkCV.wait(mLock);
4938 }
4939
Eric Laurentbfb1b832013-01-07 09:53:42 -08004940 if (exitPending()) {
4941 break;
4942 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004943 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
4944 mWriteAckSequence, mDrainSequence);
4945 writeAckSequence = mWriteAckSequence;
4946 mWriteAckSequence &= ~1;
4947 drainSequence = mDrainSequence;
4948 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004949 }
4950 {
Eric Laurent4de95592013-09-26 15:28:21 -07004951 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
4952 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004953 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004954 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004955 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004956 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004957 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004958 }
4959 }
4960 }
4961 }
4962 return false;
4963}
4964
4965void AudioFlinger::AsyncCallbackThread::exit()
4966{
4967 ALOGV("AsyncCallbackThread::exit");
4968 Mutex::Autolock _l(mLock);
4969 requestExit();
4970 mWaitWorkCV.broadcast();
4971}
4972
Eric Laurent3b4529e2013-09-05 18:09:19 -07004973void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004974{
4975 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004976 // bit 0 is cleared
4977 mWriteAckSequence = sequence << 1;
4978}
4979
4980void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
4981{
4982 Mutex::Autolock _l(mLock);
4983 // ignore unexpected callbacks
4984 if (mWriteAckSequence & 2) {
4985 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004986 mWaitWorkCV.signal();
4987 }
4988}
4989
Eric Laurent3b4529e2013-09-05 18:09:19 -07004990void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004991{
4992 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004993 // bit 0 is cleared
4994 mDrainSequence = sequence << 1;
4995}
4996
4997void AudioFlinger::AsyncCallbackThread::resetDraining()
4998{
4999 Mutex::Autolock _l(mLock);
5000 // ignore unexpected callbacks
5001 if (mDrainSequence & 2) {
5002 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005003 mWaitWorkCV.signal();
5004 }
5005}
5006
5007
5008// ----------------------------------------------------------------------------
5009AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07005010 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady)
5011 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady),
Eric Laurentd7e59222013-11-15 12:02:28 -08005012 mPausedBytesRemaining(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005013{
Eric Laurentfd477972013-10-25 18:10:40 -07005014 //FIXME: mStandby should be set to true by ThreadBase constructor
5015 mStandby = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005016}
5017
Eric Laurentbfb1b832013-01-07 09:53:42 -08005018void AudioFlinger::OffloadThread::threadLoop_exit()
5019{
5020 if (mFlushPending || mHwPaused) {
5021 // If a flush is pending or track was paused, just discard buffered data
5022 flushHw_l();
5023 } else {
5024 mMixerStatus = MIXER_DRAIN_ALL;
5025 threadLoop_drain();
5026 }
Uday Gupta56604aa2014-05-13 11:19:17 -07005027 if (mUseAsyncWrite) {
5028 ALOG_ASSERT(mCallbackThread != 0);
5029 mCallbackThread->exit();
5030 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005031 PlaybackThread::threadLoop_exit();
5032}
5033
5034AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
5035 Vector< sp<Track> > *tracksToRemove
5036)
5037{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005038 size_t count = mActiveTracks.size();
5039
5040 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07005041 bool doHwPause = false;
5042 bool doHwResume = false;
5043
Eric Laurentede6c3b2013-09-19 14:37:46 -07005044 ALOGV("OffloadThread::prepareTracks_l active tracks %d", count);
5045
Eric Laurentbfb1b832013-01-07 09:53:42 -08005046 // find out which tracks need to be processed
5047 for (size_t i = 0; i < count; i++) {
5048 sp<Track> t = mActiveTracks[i].promote();
5049 // The track died recently
5050 if (t == 0) {
5051 continue;
5052 }
5053 Track* const track = t.get();
5054 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07005055 // Only consider last track started for volume and mixer state control.
5056 // In theory an older track could underrun and restart after the new one starts
5057 // but as we only care about the transition phase between two tracks on a
5058 // direct output, it is not a problem to ignore the underrun case.
5059 sp<Track> l = mLatestActiveTrack.promote();
5060 bool last = l.get() == track;
5061
Haynes Mathew George7844f672014-01-15 12:32:55 -08005062 if (track->isInvalid()) {
5063 ALOGW("An invalidated track shouldn't be in active list");
5064 tracksToRemove->add(track);
5065 continue;
5066 }
5067
5068 if (track->mState == TrackBase::IDLE) {
5069 ALOGW("An idle track shouldn't be in active list");
5070 continue;
5071 }
5072
Eric Laurentbfb1b832013-01-07 09:53:42 -08005073 if (track->isPausing()) {
5074 track->setPaused();
5075 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07005076 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07005077 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005078 mHwPaused = true;
5079 }
5080 // If we were part way through writing the mixbuffer to
5081 // the HAL we must save this until we resume
5082 // BUG - this will be wrong if a different track is made active,
5083 // in that case we want to discard the pending data in the
5084 // mixbuffer and tell the client to present it again when the
5085 // track is resumed
5086 mPausedWriteLength = mCurrentWriteLength;
5087 mPausedBytesRemaining = mBytesRemaining;
5088 mBytesRemaining = 0; // stop writing
5089 }
5090 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08005091 } else if (track->isFlushPending()) {
5092 track->flushAck();
5093 if (last) {
5094 mFlushPending = true;
5095 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005096 } else if (track->isResumePending()){
5097 track->resumeAck();
5098 if (last) {
5099 if (mPausedBytesRemaining) {
5100 // Need to continue write that was interrupted
5101 mCurrentWriteLength = mPausedWriteLength;
5102 mBytesRemaining = mPausedBytesRemaining;
5103 mPausedBytesRemaining = 0;
5104 }
5105 if (mHwPaused) {
5106 doHwResume = true;
5107 mHwPaused = false;
5108 // threadLoop_mix() will handle the case that we need to
5109 // resume an interrupted write
5110 }
5111 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005112 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005113
5114 // Do not handle new data in this iteration even if track->framesReady()
5115 mixerStatus = MIXER_TRACKS_ENABLED;
5116 }
5117 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07005118 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005119 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005120 if (track->mFillingUpStatus == Track::FS_FILLED) {
5121 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07005122 // make sure processVolume_l() will apply new volume even if 0
5123 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005124 }
5125
5126 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08005127 sp<Track> previousTrack = mPreviousTrack.promote();
5128 if (previousTrack != 0) {
5129 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08005130 // Flush any data still being written from last track
5131 mBytesRemaining = 0;
5132 if (mPausedBytesRemaining) {
5133 // Last track was paused so we also need to flush saved
5134 // mixbuffer state and invalidate track so that it will
5135 // re-submit that unwritten data when it is next resumed
5136 mPausedBytesRemaining = 0;
5137 // Invalidate is a bit drastic - would be more efficient
5138 // to have a flag to tell client that some of the
5139 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08005140 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005141 }
5142 // flush data already sent to the DSP if changing audio session as audio
5143 // comes from a different source. Also invalidate previous track to force a
5144 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08005145 if (previousTrack->sessionId() != track->sessionId()) {
5146 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005147 }
5148 }
5149 }
5150 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005151 // reset retry count
5152 track->mRetryCount = kMaxTrackRetriesOffload;
5153 mActiveTrack = t;
5154 mixerStatus = MIXER_TRACKS_READY;
5155 }
5156 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005157 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005158 if (track->isStopping_1()) {
5159 // Hardware buffer can hold a large amount of audio so we must
5160 // wait for all current track's data to drain before we say
5161 // that the track is stopped.
5162 if (mBytesRemaining == 0) {
5163 // Only start draining when all data in mixbuffer
5164 // has been written
5165 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
5166 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005167 // do not drain if no data was ever sent to HAL (mStandby == true)
5168 if (last && !mStandby) {
Eric Laurent1b9f9b12013-11-12 19:10:17 -08005169 // do not modify drain sequence if we are already draining. This happens
5170 // when resuming from pause after drain.
5171 if ((mDrainSequence & 1) == 0) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005172 mSleepTimeUs = 0;
5173 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent1b9f9b12013-11-12 19:10:17 -08005174 mixerStatus = MIXER_DRAIN_TRACK;
5175 mDrainSequence += 2;
5176 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005177 if (mHwPaused) {
5178 // It is possible to move from PAUSED to STOPPING_1 without
5179 // a resume so we must ensure hardware is running
Eric Laurent1b9f9b12013-11-12 19:10:17 -08005180 doHwResume = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005181 mHwPaused = false;
5182 }
5183 }
5184 }
5185 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005186 // Drain has completed or we are in standby, signal presentation complete
5187 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005188 track->mState = TrackBase::STOPPED;
5189 size_t audioHALFrames =
5190 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
5191 size_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08005192 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005193 track->presentationComplete(framesWritten, audioHALFrames);
5194 track->reset();
5195 tracksToRemove->add(track);
5196 }
5197 } else {
5198 // No buffers for this track. Give it a few chances to
5199 // fill a buffer, then remove it from active list.
5200 if (--(track->mRetryCount) <= 0) {
5201 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
5202 track->name());
5203 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08005204 // indicate to client process that the track was disabled because of underrun;
5205 // it will then automatically call start() when data is available
5206 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005207 } else if (last){
5208 mixerStatus = MIXER_TRACKS_ENABLED;
5209 }
5210 }
5211 }
5212 // compute volume for this track
5213 processVolume_l(track, last);
5214 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005215
Eric Laurentea0fade2013-10-04 16:23:48 -07005216 // make sure the pause/flush/resume sequence is executed in the right order.
5217 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5218 // before flush and then resume HW. This can happen in case of pause/flush/resume
5219 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07005220 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurent972a1732013-09-04 09:42:59 -07005221 mOutput->stream->pause(mOutput->stream);
5222 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005223 if (mFlushPending) {
5224 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005225 }
Eric Laurentfd477972013-10-25 18:10:40 -07005226 if (!mStandby && doHwResume) {
Eric Laurent972a1732013-09-04 09:42:59 -07005227 mOutput->stream->resume(mOutput->stream);
5228 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005229
Eric Laurentbfb1b832013-01-07 09:53:42 -08005230 // remove all the tracks that need to be...
5231 removeTracks_l(*tracksToRemove);
5232
5233 return mixerStatus;
5234}
5235
Eric Laurentbfb1b832013-01-07 09:53:42 -08005236// must be called with thread mutex locked
5237bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
5238{
Eric Laurent3b4529e2013-09-05 18:09:19 -07005239 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
5240 mWriteAckSequence, mDrainSequence);
5241 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005242 return true;
5243 }
5244 return false;
5245}
5246
Eric Laurentbfb1b832013-01-07 09:53:42 -08005247bool AudioFlinger::OffloadThread::waitingAsyncCallback()
5248{
5249 Mutex::Autolock _l(mLock);
5250 return waitingAsyncCallback_l();
5251}
5252
5253void AudioFlinger::OffloadThread::flushHw_l()
5254{
Eric Laurente659ef42014-09-29 13:06:46 -07005255 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005256 // Flush anything still waiting in the mixbuffer
5257 mCurrentWriteLength = 0;
5258 mBytesRemaining = 0;
5259 mPausedWriteLength = 0;
5260 mPausedBytesRemaining = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08005261
Eric Laurentbfb1b832013-01-07 09:53:42 -08005262 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005263 // discard any pending drain or write ack by incrementing sequence
5264 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5265 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005266 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005267 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5268 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005269 }
5270}
5271
5272// ----------------------------------------------------------------------------
5273
Eric Laurent81784c32012-11-19 14:55:58 -08005274AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07005275 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08005276 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
Eric Laurent72e3f392015-05-20 14:43:50 -07005277 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08005278 mWaitTimeMs(UINT_MAX)
5279{
5280 addOutputTrack(mainThread);
5281}
5282
5283AudioFlinger::DuplicatingThread::~DuplicatingThread()
5284{
5285 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5286 mOutputTracks[i]->destroy();
5287 }
5288}
5289
5290void AudioFlinger::DuplicatingThread::threadLoop_mix()
5291{
5292 // mix buffers...
5293 if (outputsReady(outputTracks)) {
5294 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
5295 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08005296 if (mMixerBufferValid) {
5297 memset(mMixerBuffer, 0, mMixerBufferSize);
5298 } else {
5299 memset(mSinkBuffer, 0, mSinkBufferSize);
5300 }
Eric Laurent81784c32012-11-19 14:55:58 -08005301 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005302 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005303 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005304 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005305 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005306}
5307
5308void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
5309{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005310 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005311 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005312 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005313 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005314 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005315 }
5316 } else if (mBytesWritten != 0) {
5317 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5318 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005319 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005320 } else {
5321 // flush remaining overflow buffers in output tracks
5322 writeFrames = 0;
5323 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005324 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005325 }
5326}
5327
Eric Laurentbfb1b832013-01-07 09:53:42 -08005328ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005329{
5330 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08005331 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005332 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07005333 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08005334 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005335}
5336
5337void AudioFlinger::DuplicatingThread::threadLoop_standby()
5338{
5339 // DuplicatingThread implements standby by stopping all tracks
5340 for (size_t i = 0; i < outputTracks.size(); i++) {
5341 outputTracks[i]->stop();
5342 }
5343}
5344
5345void AudioFlinger::DuplicatingThread::saveOutputTracks()
5346{
5347 outputTracks = mOutputTracks;
5348}
5349
5350void AudioFlinger::DuplicatingThread::clearOutputTracks()
5351{
5352 outputTracks.clear();
5353}
5354
5355void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
5356{
5357 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08005358 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
5359 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
5360 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
5361 const size_t frameCount =
5362 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
5363 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
5364 // from different OutputTracks and their associated MixerThreads (e.g. one may
5365 // nearly empty and the other may be dropping data).
5366
5367 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08005368 this,
5369 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08005370 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08005371 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005372 frameCount,
5373 IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08005374 if (outputTrack->cblk() != NULL) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005375 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
Eric Laurent81784c32012-11-19 14:55:58 -08005376 mOutputTracks.add(outputTrack);
Andy Hungc25b84a2015-01-14 19:04:10 -08005377 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005378 updateWaitTime_l();
5379 }
5380}
5381
5382void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
5383{
5384 Mutex::Autolock _l(mLock);
5385 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5386 if (mOutputTracks[i]->thread() == thread) {
5387 mOutputTracks[i]->destroy();
5388 mOutputTracks.removeAt(i);
5389 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07005390 if (thread->getOutput() == mOutput) {
5391 mOutput = NULL;
5392 }
Eric Laurent81784c32012-11-19 14:55:58 -08005393 return;
5394 }
5395 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07005396 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005397}
5398
5399// caller must hold mLock
5400void AudioFlinger::DuplicatingThread::updateWaitTime_l()
5401{
5402 mWaitTimeMs = UINT_MAX;
5403 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5404 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
5405 if (strong != 0) {
5406 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
5407 if (waitTimeMs < mWaitTimeMs) {
5408 mWaitTimeMs = waitTimeMs;
5409 }
5410 }
5411 }
5412}
5413
5414
5415bool AudioFlinger::DuplicatingThread::outputsReady(
5416 const SortedVector< sp<OutputTrack> > &outputTracks)
5417{
5418 for (size_t i = 0; i < outputTracks.size(); i++) {
5419 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
5420 if (thread == 0) {
5421 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
5422 outputTracks[i].get());
5423 return false;
5424 }
5425 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5426 // see note at standby() declaration
5427 if (playbackThread->standby() && !playbackThread->isSuspended()) {
5428 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
5429 thread.get());
5430 return false;
5431 }
5432 }
5433 return true;
5434}
5435
5436uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
5437{
5438 return (mWaitTimeMs * 1000) / 2;
5439}
5440
5441void AudioFlinger::DuplicatingThread::cacheParameters_l()
5442{
5443 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
5444 updateWaitTime_l();
5445
5446 MixerThread::cacheParameters_l();
5447}
5448
5449// ----------------------------------------------------------------------------
5450// Record
5451// ----------------------------------------------------------------------------
5452
5453AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5454 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08005455 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08005456 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07005457 audio_devices_t inDevice,
5458 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08005459#ifdef TEE_SINK
5460 , const sp<NBAIO_Sink>& teeSink
5461#endif
5462 ) :
Eric Laurent72e3f392015-05-20 14:43:50 -07005463 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005464 mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005465 // mRsmpInFrames and mRsmpInFramesP2 are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005466 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08005467#ifdef TEE_SINK
5468 , mTeeSink(teeSink)
5469#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07005470 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
5471 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005472 // mFastCapture below
5473 , mFastCaptureFutex(0)
5474 // mInputSource
5475 // mPipeSink
5476 // mPipeSource
5477 , mPipeFramesP2(0)
5478 // mPipeMemory
5479 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005480 , mFastTrackAvail(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005481{
Glenn Kastend7dca052015-03-05 16:05:54 -08005482 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
5483 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08005484
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005485 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005486
5487 // create an NBAIO source for the HAL input stream, and negotiate
5488 mInputSource = new AudioStreamInSource(input->stream);
5489 size_t numCounterOffers = 0;
5490 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
5491 ssize_t index = mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
5492 ALOG_ASSERT(index == 0);
5493
5494 // initialize fast capture depending on configuration
5495 bool initFastCapture;
5496 switch (kUseFastCapture) {
5497 case FastCapture_Never:
5498 initFastCapture = false;
5499 break;
5500 case FastCapture_Always:
5501 initFastCapture = true;
5502 break;
5503 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07005504 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005505 break;
5506 // case FastCapture_Dynamic:
5507 }
5508
5509 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07005510 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005511 NBAIO_Format format = mInputSource->format();
Glenn Kasten49d00ad2014-07-21 11:22:03 -07005512 size_t pipeFramesP2 = roundup(mSampleRate / 25); // double-buffering of 20 ms each
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005513 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
5514 void *pipeBuffer;
5515 const sp<MemoryDealer> roHeap(readOnlyHeap());
5516 sp<IMemory> pipeMemory;
5517 if ((roHeap == 0) ||
5518 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
5519 (pipeBuffer = pipeMemory->pointer()) == NULL) {
5520 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
5521 goto failed;
5522 }
5523 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
5524 memset(pipeBuffer, 0, pipeSize);
5525 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
5526 const NBAIO_Format offers[1] = {format};
5527 size_t numCounterOffers = 0;
5528 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
5529 ALOG_ASSERT(index == 0);
5530 mPipeSink = pipe;
5531 PipeReader *pipeReader = new PipeReader(*pipe);
5532 numCounterOffers = 0;
5533 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
5534 ALOG_ASSERT(index == 0);
5535 mPipeSource = pipeReader;
5536 mPipeFramesP2 = pipeFramesP2;
5537 mPipeMemory = pipeMemory;
5538
5539 // create fast capture
5540 mFastCapture = new FastCapture();
5541 FastCaptureStateQueue *sq = mFastCapture->sq();
5542#ifdef STATE_QUEUE_DUMP
5543 // FIXME
5544#endif
5545 FastCaptureState *state = sq->begin();
5546 state->mCblk = NULL;
5547 state->mInputSource = mInputSource.get();
5548 state->mInputSourceGen++;
5549 state->mPipeSink = pipe;
5550 state->mPipeSinkGen++;
5551 state->mFrameCount = mFrameCount;
5552 state->mCommand = FastCaptureState::COLD_IDLE;
5553 // already done in constructor initialization list
5554 //mFastCaptureFutex = 0;
5555 state->mColdFutexAddr = &mFastCaptureFutex;
5556 state->mColdGen++;
5557 state->mDumpState = &mFastCaptureDumpState;
5558#ifdef TEE_SINK
5559 // FIXME
5560#endif
5561 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
5562 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
5563 sq->end();
5564 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5565
5566 // start the fast capture
5567 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
5568 pid_t tid = mFastCapture->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07005569 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005570#ifdef AUDIO_WATCHDOG
5571 // FIXME
5572#endif
5573
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005574 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005575 }
5576failed: ;
5577
5578 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08005579}
5580
Eric Laurent81784c32012-11-19 14:55:58 -08005581AudioFlinger::RecordThread::~RecordThread()
5582{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005583 if (mFastCapture != 0) {
5584 FastCaptureStateQueue *sq = mFastCapture->sq();
5585 FastCaptureState *state = sq->begin();
5586 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5587 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5588 if (old == -1) {
5589 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5590 }
5591 }
5592 state->mCommand = FastCaptureState::EXIT;
5593 sq->end();
5594 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5595 mFastCapture->join();
5596 mFastCapture.clear();
5597 }
5598 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07005599 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07005600 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08005601}
5602
5603void AudioFlinger::RecordThread::onFirstRef()
5604{
Glenn Kastend7dca052015-03-05 16:05:54 -08005605 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08005606}
5607
Eric Laurent81784c32012-11-19 14:55:58 -08005608bool AudioFlinger::RecordThread::threadLoop()
5609{
Eric Laurent81784c32012-11-19 14:55:58 -08005610 nsecs_t lastWarning = 0;
5611
5612 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08005613
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005614reacquire_wakelock:
5615 sp<RecordTrack> activeTrack;
Glenn Kasten2b806402013-11-20 16:37:38 -08005616 int activeTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005617 {
5618 Mutex::Autolock _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005619 size_t size = mActiveTracks.size();
5620 activeTracksGen = mActiveTracksGen;
5621 if (size > 0) {
5622 // FIXME an arbitrary choice
5623 activeTrack = mActiveTracks[0];
5624 acquireWakeLock_l(activeTrack->uid());
5625 if (size > 1) {
5626 SortedVector<int> tmp;
5627 for (size_t i = 0; i < size; i++) {
5628 tmp.add(mActiveTracks[i]->uid());
5629 }
5630 updateWakeLockUids_l(tmp);
5631 }
5632 } else {
5633 acquireWakeLock_l(-1);
5634 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005635 }
5636
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005637 // used to request a deferred sleep, to be executed later while mutex is unlocked
5638 uint32_t sleepUs = 0;
5639
5640 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005641 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005642 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07005643
Glenn Kasten5edadd42013-08-14 16:30:49 -07005644 // sleep with mutex unlocked
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005645 if (sleepUs > 0) {
Glenn Kastene7754022014-10-31 12:11:26 -07005646 ATRACE_BEGIN("sleep");
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005647 usleep(sleepUs);
Glenn Kastene7754022014-10-31 12:11:26 -07005648 ATRACE_END();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005649 sleepUs = 0;
Glenn Kasten5edadd42013-08-14 16:30:49 -07005650 }
5651
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005652 // activeTracks accumulates a copy of a subset of mActiveTracks
5653 Vector< sp<RecordTrack> > activeTracks;
5654
Glenn Kasten735f45f2014-08-18 15:51:59 -07005655 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005656 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07005657
Glenn Kasten735f45f2014-08-18 15:51:59 -07005658 // reference to a fast track which is about to be removed
5659 sp<RecordTrack> fastTrackToRemove;
5660
Eric Laurent81784c32012-11-19 14:55:58 -08005661 { // scope for mLock
5662 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08005663
Eric Laurent021cf962014-05-13 10:18:14 -07005664 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005665
Eric Laurent000a4192014-01-29 15:17:32 -08005666 // check exitPending here because checkForNewParameters_l() and
5667 // checkForNewParameters_l() can temporarily release mLock
5668 if (exitPending()) {
5669 break;
5670 }
5671
Glenn Kasten2b806402013-11-20 16:37:38 -08005672 // if no active track(s), then standby and release wakelock
5673 size_t size = mActiveTracks.size();
5674 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07005675 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005676 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08005677 releaseWakeLock_l();
5678 ALOGV("RecordThread: loop stopping");
5679 // go to sleep
5680 mWaitWorkCV.wait(mLock);
5681 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005682 goto reacquire_wakelock;
5683 }
5684
Glenn Kasten2b806402013-11-20 16:37:38 -08005685 if (mActiveTracksGen != activeTracksGen) {
5686 activeTracksGen = mActiveTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005687 SortedVector<int> tmp;
Glenn Kasten2b806402013-11-20 16:37:38 -08005688 for (size_t i = 0; i < size; i++) {
5689 tmp.add(mActiveTracks[i]->uid());
5690 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005691 updateWakeLockUids_l(tmp);
Eric Laurent81784c32012-11-19 14:55:58 -08005692 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005693
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005694 bool doBroadcast = false;
5695 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07005696
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005697 activeTrack = mActiveTracks[i];
5698 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07005699 if (activeTrack->isFastTrack()) {
5700 ALOG_ASSERT(fastTrackToRemove == 0);
5701 fastTrackToRemove = activeTrack;
5702 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005703 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08005704 mActiveTracks.remove(activeTrack);
5705 mActiveTracksGen++;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005706 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07005707 continue;
5708 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005709
5710 TrackBase::track_state activeTrackState = activeTrack->mState;
5711 switch (activeTrackState) {
5712
5713 case TrackBase::PAUSING:
5714 mActiveTracks.remove(activeTrack);
5715 mActiveTracksGen++;
5716 doBroadcast = true;
5717 size--;
5718 continue;
5719
5720 case TrackBase::STARTING_1:
5721 sleepUs = 10000;
5722 i++;
5723 continue;
5724
5725 case TrackBase::STARTING_2:
5726 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005727 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07005728 activeTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005729 break;
5730
5731 case TrackBase::ACTIVE:
5732 break;
5733
5734 case TrackBase::IDLE:
5735 i++;
5736 continue;
5737
5738 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08005739 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07005740 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005741
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005742 activeTracks.add(activeTrack);
5743 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07005744
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005745 if (activeTrack->isFastTrack()) {
5746 ALOG_ASSERT(!mFastTrackAvail);
5747 ALOG_ASSERT(fastTrack == 0);
5748 fastTrack = activeTrack;
5749 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005750 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005751 if (doBroadcast) {
5752 mStartStopCond.broadcast();
5753 }
5754
5755 // sleep if there are no active tracks to process
5756 if (activeTracks.size() == 0) {
5757 if (sleepUs == 0) {
5758 sleepUs = kRecordThreadSleepUs;
5759 }
5760 continue;
5761 }
5762 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07005763
Eric Laurent81784c32012-11-19 14:55:58 -08005764 lockEffectChains_l(effectChains);
5765 }
5766
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005767 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07005768
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005769 size_t size = effectChains.size();
5770 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005771 // thread mutex is not locked, but effect chain is locked
5772 effectChains[i]->process_l();
5773 }
5774
Glenn Kasten735f45f2014-08-18 15:51:59 -07005775 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005776 if (mFastCapture != 0) {
5777 FastCaptureStateQueue *sq = mFastCapture->sq();
5778 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07005779 bool didModify = false;
5780 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005781 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
5782 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
5783 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5784 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5785 if (old == -1) {
5786 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5787 }
5788 }
5789 state->mCommand = FastCaptureState::READ_WRITE;
5790#if 0 // FIXME
5791 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08005792 FastThreadDumpState::kSamplingNforLowRamDevice :
5793 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005794#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07005795 didModify = true;
5796 }
5797 audio_track_cblk_t *cblkOld = state->mCblk;
5798 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
5799 if (cblkNew != cblkOld) {
5800 state->mCblk = cblkNew;
5801 // block until acked if removing a fast track
5802 if (cblkOld != NULL) {
5803 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
5804 }
5805 didModify = true;
5806 }
5807 sq->end(didModify);
5808 if (didModify) {
5809 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005810#if 0
5811 if (kUseFastCapture == FastCapture_Dynamic) {
5812 mNormalSource = mPipeSource;
5813 }
5814#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005815 }
5816 }
5817
Glenn Kasten735f45f2014-08-18 15:51:59 -07005818 // now run the fast track destructor with thread mutex unlocked
5819 fastTrackToRemove.clear();
5820
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005821 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
5822 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
5823 // slow, then this RecordThread will overrun by not calling HAL read often enough.
5824 // If destination is non-contiguous, first read past the nominal end of buffer, then
5825 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005826
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005827 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005828 ssize_t framesRead;
5829
5830 // If an NBAIO source is present, use it to read the normal capture's data
5831 if (mPipeSource != 0) {
5832 size_t framesToRead = mBufferSize / mFrameSize;
Andy Hung57446612015-04-19 23:56:46 -07005833 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005834 framesToRead, AudioBufferProvider::kInvalidPTS);
5835 if (framesRead == 0) {
5836 // since pipe is non-blocking, simulate blocking input
5837 sleepUs = (framesToRead * 1000000LL) / mSampleRate;
5838 }
5839 // otherwise use the HAL / AudioStreamIn directly
5840 } else {
5841 ssize_t bytesRead = mInput->stream->read(mInput->stream,
Andy Hung57446612015-04-19 23:56:46 -07005842 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005843 if (bytesRead < 0) {
5844 framesRead = bytesRead;
5845 } else {
5846 framesRead = bytesRead / mFrameSize;
5847 }
5848 }
5849
5850 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
5851 ALOGE("read failed: framesRead=%d", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005852 // Force input into standby so that it tries to recover at next read attempt
5853 inputStandBy();
5854 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005855 }
5856 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005857 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005858 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005859 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005860
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005861 if (mTeeSink != 0) {
Andy Hung57446612015-04-19 23:56:46 -07005862 (void) mTeeSink->write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005863 }
5864 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005865 {
5866 size_t part1 = mRsmpInFramesP2 - rear;
5867 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07005868 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005869 (framesRead - part1) * mFrameSize);
5870 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005871 }
5872 rear = mRsmpInRear += framesRead;
5873
5874 size = activeTracks.size();
5875 // loop over each active track
5876 for (size_t i = 0; i < size; i++) {
5877 activeTrack = activeTracks[i];
5878
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005879 // skip fast tracks, as those are handled directly by FastCapture
5880 if (activeTrack->isFastTrack()) {
5881 continue;
5882 }
5883
Andy Hung73c02e42015-03-29 01:13:58 -07005884 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07005885 // TODO: Update the activeTrack buffer converter in case of reconfigure.
5886
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005887 enum {
5888 OVERRUN_UNKNOWN,
5889 OVERRUN_TRUE,
5890 OVERRUN_FALSE
5891 } overrun = OVERRUN_UNKNOWN;
5892
5893 // loop over getNextBuffer to handle circular sink
5894 for (;;) {
5895
5896 activeTrack->mSink.frameCount = ~0;
5897 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
5898 size_t framesOut = activeTrack->mSink.frameCount;
5899 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
5900
Andy Hung73c02e42015-03-29 01:13:58 -07005901 // check available frames and handle overrun conditions
5902 // if the record track isn't draining fast enough.
5903 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005904 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07005905 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
5906 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005907 overrun = OVERRUN_TRUE;
5908 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005909 if (framesOut == 0 || framesIn == 0) {
5910 break;
5911 }
5912
Andy Hung6770c6f2015-04-07 13:43:36 -07005913 // Don't allow framesOut to be larger than what is possible with resampling
5914 // from framesIn.
5915 // This isn't strictly necessary but helps limit buffer resizing in
5916 // RecordBufferConverter. TODO: remove when no longer needed.
5917 framesOut = min(framesOut,
5918 destinationFramesPossible(
5919 framesIn, mSampleRate, activeTrack->mSampleRate));
Andy Hung97a893e2015-03-29 01:03:07 -07005920 // process frames from the RecordThread buffer provider to the RecordTrack buffer
5921 framesOut = activeTrack->mRecordBufferConverter->convert(
5922 activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005923
5924 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
5925 overrun = OVERRUN_FALSE;
5926 }
5927
5928 if (activeTrack->mFramesToDrop == 0) {
5929 if (framesOut > 0) {
5930 activeTrack->mSink.frameCount = framesOut;
5931 activeTrack->releaseBuffer(&activeTrack->mSink);
5932 }
5933 } else {
5934 // FIXME could do a partial drop of framesOut
5935 if (activeTrack->mFramesToDrop > 0) {
5936 activeTrack->mFramesToDrop -= framesOut;
5937 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005938 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005939 }
5940 } else {
5941 activeTrack->mFramesToDrop += framesOut;
5942 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
5943 activeTrack->mSyncStartEvent->isCancelled()) {
5944 ALOGW("Synced record %s, session %d, trigger session %d",
5945 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
5946 activeTrack->sessionId(),
5947 (activeTrack->mSyncStartEvent != 0) ?
5948 activeTrack->mSyncStartEvent->triggerSession() : 0);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005949 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005950 }
5951 }
5952 }
5953
5954 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005955 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005956 }
5957 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005958
5959 switch (overrun) {
5960 case OVERRUN_TRUE:
5961 // client isn't retrieving buffers fast enough
5962 if (!activeTrack->setOverflow()) {
5963 nsecs_t now = systemTime();
5964 // FIXME should lastWarning per track?
5965 if ((now - lastWarning) > kWarningThrottleNs) {
5966 ALOGW("RecordThread: buffer overflow");
5967 lastWarning = now;
5968 }
5969 }
5970 break;
5971 case OVERRUN_FALSE:
5972 activeTrack->clearOverflow();
5973 break;
5974 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005975 break;
5976 }
5977
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005978 }
5979
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005980unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08005981 // enable changes in effect chain
5982 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005983 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08005984 }
5985
Glenn Kasten93e471f2013-08-19 08:40:07 -07005986 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08005987
5988 {
5989 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07005990 for (size_t i = 0; i < mTracks.size(); i++) {
5991 sp<RecordTrack> track = mTracks[i];
5992 track->invalidate();
5993 }
Glenn Kasten2b806402013-11-20 16:37:38 -08005994 mActiveTracks.clear();
5995 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08005996 mStartStopCond.broadcast();
5997 }
5998
5999 releaseWakeLock();
6000
6001 ALOGV("RecordThread %p exiting", this);
6002 return false;
6003}
6004
Glenn Kasten93e471f2013-08-19 08:40:07 -07006005void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08006006{
6007 if (!mStandby) {
6008 inputStandBy();
6009 mStandby = true;
6010 }
6011}
6012
6013void AudioFlinger::RecordThread::inputStandBy()
6014{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006015 // Idle the fast capture if it's currently running
6016 if (mFastCapture != 0) {
6017 FastCaptureStateQueue *sq = mFastCapture->sq();
6018 FastCaptureState *state = sq->begin();
6019 if (!(state->mCommand & FastCaptureState::IDLE)) {
6020 state->mCommand = FastCaptureState::COLD_IDLE;
6021 state->mColdFutexAddr = &mFastCaptureFutex;
6022 state->mColdGen++;
6023 mFastCaptureFutex = 0;
6024 sq->end();
6025 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
6026 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
6027#if 0
6028 if (kUseFastCapture == FastCapture_Dynamic) {
6029 // FIXME
6030 }
6031#endif
6032#ifdef AUDIO_WATCHDOG
6033 // FIXME
6034#endif
6035 } else {
6036 sq->end(false /*didModify*/);
6037 }
6038 }
Eric Laurent81784c32012-11-19 14:55:58 -08006039 mInput->stream->common.standby(&mInput->stream->common);
6040}
6041
Glenn Kasten05997e22014-03-13 15:08:33 -07006042// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07006043sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08006044 const sp<AudioFlinger::Client>& client,
6045 uint32_t sampleRate,
6046 audio_format_t format,
6047 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08006048 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08006049 int sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07006050 size_t *notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08006051 int uid,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07006052 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08006053 pid_t tid,
6054 status_t *status)
6055{
Glenn Kasten74935e42013-12-19 08:56:45 -08006056 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08006057 sp<RecordTrack> track;
6058 status_t lStatus;
6059
Glenn Kasten90e58b12013-07-31 16:16:02 -07006060 // client expresses a preference for FAST, but we get the final say
6061 if (*flags & IAudioFlinger::TRACK_FAST) {
6062 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07006063 // we formerly checked for a callback handler (non-0 tid),
6064 // but that is no longer required for TRANSFER_OBTAIN mode
6065 //
Glenn Kasten74105912014-07-03 12:28:53 -07006066 // frame count is not specified, or is exactly the pipe depth
6067 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006068 // PCM data
6069 audio_is_linear_pcm(format) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006070 // native format
6071 (format == mFormat) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006072 // native channel mask
6073 (channelMask == mChannelMask) &&
6074 // native hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07006075 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006076 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006077 hasFastCapture() &&
6078 // there are sufficient fast track slots available
6079 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07006080 ) {
Glenn Kasten74105912014-07-03 12:28:53 -07006081 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%u mFrameCount=%u",
Glenn Kasten90e58b12013-07-31 16:16:02 -07006082 frameCount, mFrameCount);
6083 } else {
Glenn Kasten74105912014-07-03 12:28:53 -07006084 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%u mFrameCount=%u mPipeFramesP2=%u "
6085 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006086 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Glenn Kasten74105912014-07-03 12:28:53 -07006087 frameCount, mFrameCount, mPipeFramesP2,
6088 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
6089 hasFastCapture(), tid, mFastTrackAvail);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006090 *flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kasten74105912014-07-03 12:28:53 -07006091 }
6092 }
6093
6094 // compute track buffer size in frames, and suggest the notification frame count
6095 if (*flags & IAudioFlinger::TRACK_FAST) {
6096 // fast track: frame count is exactly the pipe depth
6097 frameCount = mPipeFramesP2;
6098 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
6099 *notificationFrames = mFrameCount;
6100 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006101 // not fast track: max notification period is resampled equivalent of one HAL buffer time
6102 // or 20 ms if there is a fast capture
6103 // TODO This could be a roundupRatio inline, and const
6104 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
6105 * sampleRate + mSampleRate - 1) / mSampleRate;
6106 // minimum number of notification periods is at least kMinNotifications,
6107 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
6108 static const size_t kMinNotifications = 3;
6109 static const uint32_t kMinMs = 30;
6110 // TODO This could be a roundupRatio inline
6111 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
6112 // TODO This could be a roundupRatio inline
6113 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
6114 maxNotificationFrames;
6115 const size_t minFrameCount = maxNotificationFrames *
6116 max(kMinNotifications, minNotificationsByMs);
6117 frameCount = max(frameCount, minFrameCount);
6118 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
6119 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07006120 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07006121 }
Glenn Kasten74935e42013-12-19 08:56:45 -08006122 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07006123
Glenn Kasten15e57982013-09-24 11:52:37 -07006124 lStatus = initCheck();
6125 if (lStatus != NO_ERROR) {
6126 ALOGE("createRecordTrack_l() audio driver not initialized");
6127 goto Exit;
6128 }
Eric Laurent81784c32012-11-19 14:55:58 -08006129
6130 { // scope for mLock
6131 Mutex::Autolock _l(mLock);
6132
6133 track = new RecordTrack(this, client, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07006134 format, channelMask, frameCount, NULL, sessionId, uid,
6135 *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08006136
Glenn Kasten03003332013-08-06 15:40:54 -07006137 lStatus = track->initCheck();
6138 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07006139 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08006140 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08006141 goto Exit;
6142 }
6143 mTracks.add(track);
6144
6145 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6146 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6147 mAudioFlinger->btNrecIsOff();
6148 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6149 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006150
6151 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
6152 pid_t callingPid = IPCThreadState::self()->getCallingPid();
6153 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
6154 // so ask activity manager to do this on our behalf
6155 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
6156 }
Eric Laurent81784c32012-11-19 14:55:58 -08006157 }
Glenn Kasten05997e22014-03-13 15:08:33 -07006158
Eric Laurent81784c32012-11-19 14:55:58 -08006159 lStatus = NO_ERROR;
6160
6161Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07006162 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08006163 return track;
6164}
6165
6166status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
6167 AudioSystem::sync_event_t event,
6168 int triggerSession)
6169{
6170 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
6171 sp<ThreadBase> strongMe = this;
6172 status_t status = NO_ERROR;
6173
6174 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006175 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006176 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006177 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08006178 triggerSession,
6179 recordTrack->sessionId(),
6180 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006181 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08006182 // Sync event can be cancelled by the trigger session if the track is not in a
6183 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006184 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006185 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006186 } else {
6187 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006188 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006189 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08006190 }
6191 }
6192
6193 {
Glenn Kasten47c20702013-08-13 15:37:35 -07006194 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08006195 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006196 if (mActiveTracks.indexOf(recordTrack) >= 0) {
6197 if (recordTrack->mState == TrackBase::PAUSING) {
6198 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006199 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006200 } else {
6201 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08006202 }
6203 return status;
6204 }
6205
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006206 // TODO consider other ways of handling this, such as changing the state to :STARTING and
6207 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
6208 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006209 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08006210 mActiveTracks.add(recordTrack);
6211 mActiveTracksGen++;
Eric Laurent83b88082014-06-20 18:31:16 -07006212 status_t status = NO_ERROR;
6213 if (recordTrack->isExternalTrack()) {
6214 mLock.unlock();
Eric Laurent4dc68062014-07-28 17:26:49 -07006215 status = AudioSystem::startInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006216 mLock.lock();
6217 // FIXME should verify that recordTrack is still in mActiveTracks
6218 if (status != NO_ERROR) {
6219 mActiveTracks.remove(recordTrack);
6220 mActiveTracksGen++;
6221 recordTrack->clearSyncStartEvent();
6222 ALOGV("RecordThread::start error %d", status);
6223 return status;
6224 }
Eric Laurent81784c32012-11-19 14:55:58 -08006225 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006226 // Catch up with current buffer indices if thread is already running.
6227 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
6228 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
6229 // see previously buffered data before it called start(), but with greater risk of overrun.
6230
Andy Hung73c02e42015-03-29 01:13:58 -07006231 recordTrack->mResamplerBufferProvider->reset();
Andy Hung97a893e2015-03-29 01:03:07 -07006232 // clear any converter state as new data will be discontinuous
6233 recordTrack->mRecordBufferConverter->reset();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006234 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08006235 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08006236 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08006237 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006238 ALOGV("Record failed to start");
6239 status = BAD_VALUE;
6240 goto startError;
6241 }
Eric Laurent81784c32012-11-19 14:55:58 -08006242 return status;
6243 }
Glenn Kasten7c027242012-12-26 14:43:16 -08006244
Eric Laurent81784c32012-11-19 14:55:58 -08006245startError:
Eric Laurent83b88082014-06-20 18:31:16 -07006246 if (recordTrack->isExternalTrack()) {
Eric Laurent4dc68062014-07-28 17:26:49 -07006247 AudioSystem::stopInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006248 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006249 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006250 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08006251 return status;
6252}
6253
Eric Laurent81784c32012-11-19 14:55:58 -08006254void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6255{
6256 sp<SyncEvent> strongEvent = event.promote();
6257
6258 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08006259 sp<RefBase> ptr = strongEvent->cookie().promote();
6260 if (ptr != 0) {
6261 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
6262 recordTrack->handleSyncStartEvent(strongEvent);
6263 }
Eric Laurent81784c32012-11-19 14:55:58 -08006264 }
6265}
6266
Glenn Kastena8356f62013-07-25 14:37:52 -07006267bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08006268 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07006269 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006270 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08006271 return false;
6272 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006273 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08006274 recordTrack->mState = TrackBase::PAUSING;
6275 // do not wait for mStartStopCond if exiting
6276 if (exitPending()) {
6277 return true;
6278 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006279 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08006280 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006281 // if we have been restarted, recordTrack is in mActiveTracks here
6282 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006283 ALOGV("Record stopped OK");
6284 return true;
6285 }
6286 return false;
6287}
6288
Glenn Kasten0f11b512014-01-31 16:18:54 -08006289bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08006290{
6291 return false;
6292}
6293
Glenn Kasten0f11b512014-01-31 16:18:54 -08006294status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006295{
6296#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
6297 if (!isValidSyncEvent(event)) {
6298 return BAD_VALUE;
6299 }
6300
6301 int eventSession = event->triggerSession();
6302 status_t ret = NAME_NOT_FOUND;
6303
6304 Mutex::Autolock _l(mLock);
6305
6306 for (size_t i = 0; i < mTracks.size(); i++) {
6307 sp<RecordTrack> track = mTracks[i];
6308 if (eventSession == track->sessionId()) {
6309 (void) track->setSyncEvent(event);
6310 ret = NO_ERROR;
6311 }
6312 }
6313 return ret;
6314#else
6315 return BAD_VALUE;
6316#endif
6317}
6318
6319// destroyTrack_l() must be called with ThreadBase::mLock held
6320void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6321{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006322 track->terminate();
6323 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08006324 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08006325 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006326 removeTrack_l(track);
6327 }
6328}
6329
6330void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6331{
6332 mTracks.remove(track);
6333 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006334 if (track->isFastTrack()) {
6335 ALOG_ASSERT(!mFastTrackAvail);
6336 mFastTrackAvail = true;
6337 }
Eric Laurent81784c32012-11-19 14:55:58 -08006338}
6339
6340void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6341{
6342 dumpInternals(fd, args);
6343 dumpTracks(fd, args);
6344 dumpEffectChains(fd, args);
6345}
6346
6347void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6348{
Elliott Hughes87cebad2014-05-22 10:14:43 -07006349 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08006350
Glenn Kasten44182c22015-03-05 17:12:23 -08006351 dumpBase(fd, args);
6352
6353 if (mActiveTracks.size() == 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006354 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006355 }
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006356 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006357 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08006358
6359 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
6360 const FastCaptureDumpState copy(mFastCaptureDumpState);
6361 copy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006362}
6363
Glenn Kasten0f11b512014-01-31 16:18:54 -08006364void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006365{
6366 const size_t SIZE = 256;
6367 char buffer[SIZE];
6368 String8 result;
6369
Marco Nelissenb2208842014-02-07 14:00:50 -08006370 size_t numtracks = mTracks.size();
6371 size_t numactive = mActiveTracks.size();
6372 size_t numactiveseen = 0;
Elliott Hughes87cebad2014-05-22 10:14:43 -07006373 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08006374 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006375 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08006376 RecordTrack::appendDumpHeader(result);
6377 for (size_t i = 0; i < numtracks ; ++i) {
6378 sp<RecordTrack> track = mTracks[i];
6379 if (track != 0) {
6380 bool active = mActiveTracks.indexOf(track) >= 0;
6381 if (active) {
6382 numactiveseen++;
6383 }
6384 track->dump(buffer, SIZE, active);
6385 result.append(buffer);
6386 }
Eric Laurent81784c32012-11-19 14:55:58 -08006387 }
Marco Nelissenb2208842014-02-07 14:00:50 -08006388 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006389 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006390 }
6391
Marco Nelissenb2208842014-02-07 14:00:50 -08006392 if (numactiveseen != numactive) {
6393 snprintf(buffer, SIZE, " The following tracks are in the active list but"
6394 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006395 result.append(buffer);
6396 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08006397 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08006398 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08006399 if (mTracks.indexOf(track) < 0) {
6400 track->dump(buffer, SIZE, true);
6401 result.append(buffer);
6402 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006403 }
Eric Laurent81784c32012-11-19 14:55:58 -08006404
6405 }
6406 write(fd, result.string(), result.size());
6407}
6408
Andy Hung73c02e42015-03-29 01:13:58 -07006409
6410void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
6411{
6412 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6413 RecordThread *recordThread = (RecordThread *) threadBase.get();
6414 mRsmpInFront = recordThread->mRsmpInRear;
6415 mRsmpInUnrel = 0;
6416}
6417
6418void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
6419 size_t *framesAvailable, bool *hasOverrun)
6420{
6421 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6422 RecordThread *recordThread = (RecordThread *) threadBase.get();
6423 const int32_t rear = recordThread->mRsmpInRear;
6424 const int32_t front = mRsmpInFront;
6425 const ssize_t filled = rear - front;
6426
6427 size_t framesIn;
6428 bool overrun = false;
6429 if (filled < 0) {
6430 // should not happen, but treat like a massive overrun and re-sync
6431 framesIn = 0;
6432 mRsmpInFront = rear;
6433 overrun = true;
6434 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
6435 framesIn = (size_t) filled;
6436 } else {
6437 // client is not keeping up with server, but give it latest data
6438 framesIn = recordThread->mRsmpInFrames;
6439 mRsmpInFront = /* front = */ rear - framesIn;
6440 overrun = true;
6441 }
6442 if (framesAvailable != NULL) {
6443 *framesAvailable = framesIn;
6444 }
6445 if (hasOverrun != NULL) {
6446 *hasOverrun = overrun;
6447 }
6448}
6449
Eric Laurent81784c32012-11-19 14:55:58 -08006450// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006451status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
6452 AudioBufferProvider::Buffer* buffer, int64_t pts __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006453{
Andy Hung73c02e42015-03-29 01:13:58 -07006454 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006455 if (threadBase == 0) {
6456 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006457 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006458 return NOT_ENOUGH_DATA;
6459 }
6460 RecordThread *recordThread = (RecordThread *) threadBase.get();
6461 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07006462 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07006463 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006464 // FIXME should not be P2 (don't want to increase latency)
6465 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006466 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07006467 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006468 front &= recordThread->mRsmpInFramesP2 - 1;
6469 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07006470 if (part1 > (size_t) filled) {
6471 part1 = filled;
6472 }
6473 size_t ask = buffer->frameCount;
6474 ALOG_ASSERT(ask > 0);
6475 if (part1 > ask) {
6476 part1 = ask;
6477 }
6478 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07006479 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07006480 buffer->raw = NULL;
6481 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07006482 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07006483 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08006484 }
6485
Andy Hung57446612015-04-19 23:56:46 -07006486 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07006487 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07006488 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08006489 return NO_ERROR;
6490}
6491
6492// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006493void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
6494 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006495{
Glenn Kasten85948432013-08-19 12:09:05 -07006496 size_t stepCount = buffer->frameCount;
6497 if (stepCount == 0) {
6498 return;
6499 }
Andy Hung73c02e42015-03-29 01:13:58 -07006500 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
6501 mRsmpInUnrel -= stepCount;
6502 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07006503 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006504 buffer->frameCount = 0;
6505}
6506
Andy Hung97a893e2015-03-29 01:03:07 -07006507AudioFlinger::RecordThread::RecordBufferConverter::RecordBufferConverter(
6508 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6509 uint32_t srcSampleRate,
6510 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6511 uint32_t dstSampleRate) :
6512 mSrcChannelMask(AUDIO_CHANNEL_INVALID), // updateParameters will set following vars
6513 // mSrcFormat
6514 // mSrcSampleRate
6515 // mDstChannelMask
6516 // mDstFormat
6517 // mDstSampleRate
6518 // mSrcChannelCount
6519 // mDstChannelCount
6520 // mDstFrameSize
6521 mBuf(NULL), mBufFrames(0), mBufFrameSize(0),
Andy Hungd330ee42015-04-20 13:23:41 -07006522 mResampler(NULL),
6523 mIsLegacyDownmix(false),
6524 mIsLegacyUpmix(false),
6525 mRequiresFloat(false),
6526 mInputConverterProvider(NULL)
Andy Hung97a893e2015-03-29 01:03:07 -07006527{
6528 (void)updateParameters(srcChannelMask, srcFormat, srcSampleRate,
6529 dstChannelMask, dstFormat, dstSampleRate);
6530}
6531
6532AudioFlinger::RecordThread::RecordBufferConverter::~RecordBufferConverter() {
6533 free(mBuf);
6534 delete mResampler;
Andy Hungd330ee42015-04-20 13:23:41 -07006535 delete mInputConverterProvider;
Andy Hung97a893e2015-03-29 01:03:07 -07006536}
6537
6538size_t AudioFlinger::RecordThread::RecordBufferConverter::convert(void *dst,
6539 AudioBufferProvider *provider, size_t frames)
6540{
Andy Hungd330ee42015-04-20 13:23:41 -07006541 if (mInputConverterProvider != NULL) {
6542 mInputConverterProvider->setBufferProvider(provider);
6543 provider = mInputConverterProvider;
6544 }
6545
6546 if (mResampler == NULL) {
Andy Hung97a893e2015-03-29 01:03:07 -07006547 ALOGVV("NO RESAMPLING sampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6548 mSrcSampleRate, mSrcFormat, mDstFormat);
6549
6550 AudioBufferProvider::Buffer buffer;
6551 for (size_t i = frames; i > 0; ) {
6552 buffer.frameCount = i;
6553 status_t status = provider->getNextBuffer(&buffer, 0);
6554 if (status != OK || buffer.frameCount == 0) {
6555 frames -= i; // cannot fill request.
6556 break;
6557 }
Andy Hungd330ee42015-04-20 13:23:41 -07006558 // format convert to destination buffer
6559 convertNoResampler(dst, buffer.raw, buffer.frameCount);
Andy Hung97a893e2015-03-29 01:03:07 -07006560
6561 dst = (int8_t*)dst + buffer.frameCount * mDstFrameSize;
6562 i -= buffer.frameCount;
6563 provider->releaseBuffer(&buffer);
6564 }
6565 } else {
6566 ALOGVV("RESAMPLING mSrcSampleRate:%u mDstSampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6567 mSrcSampleRate, mDstSampleRate, mSrcFormat, mDstFormat);
6568
Andy Hungd330ee42015-04-20 13:23:41 -07006569 // reallocate buffer if needed
6570 if (mBufFrameSize != 0 && mBufFrames < frames) {
6571 free(mBuf);
6572 mBufFrames = frames;
6573 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
6574 }
Andy Hung97a893e2015-03-29 01:03:07 -07006575 // resampler accumulates, but we only have one source track
Andy Hungd330ee42015-04-20 13:23:41 -07006576 memset(mBuf, 0, frames * mBufFrameSize);
6577 frames = mResampler->resample((int32_t*)mBuf, frames, provider);
6578 // format convert to destination buffer
6579 convertResampler(dst, mBuf, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006580 }
6581 return frames;
6582}
6583
6584status_t AudioFlinger::RecordThread::RecordBufferConverter::updateParameters(
6585 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6586 uint32_t srcSampleRate,
6587 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6588 uint32_t dstSampleRate)
6589{
6590 // quick evaluation if there is any change.
6591 if (mSrcFormat == srcFormat
6592 && mSrcChannelMask == srcChannelMask
6593 && mSrcSampleRate == srcSampleRate
6594 && mDstFormat == dstFormat
6595 && mDstChannelMask == dstChannelMask
6596 && mDstSampleRate == dstSampleRate) {
6597 return NO_ERROR;
6598 }
6599
Andy Hungdb4c0312015-05-06 08:46:52 -07006600 ALOGV("RecordBufferConverter updateParameters srcMask:%#x dstMask:%#x"
6601 " srcFormat:%#x dstFormat:%#x srcRate:%u dstRate:%u",
6602 srcChannelMask, dstChannelMask, srcFormat, dstFormat, srcSampleRate, dstSampleRate);
Andy Hung97a893e2015-03-29 01:03:07 -07006603 const bool valid =
6604 audio_is_input_channel(srcChannelMask)
6605 && audio_is_input_channel(dstChannelMask)
6606 && audio_is_valid_format(srcFormat) && audio_is_linear_pcm(srcFormat)
6607 && audio_is_valid_format(dstFormat) && audio_is_linear_pcm(dstFormat)
6608 && (srcSampleRate <= dstSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX)
6609 ; // no upsampling checks for now
6610 if (!valid) {
6611 return BAD_VALUE;
6612 }
6613
6614 mSrcFormat = srcFormat;
6615 mSrcChannelMask = srcChannelMask;
6616 mSrcSampleRate = srcSampleRate;
6617 mDstFormat = dstFormat;
6618 mDstChannelMask = dstChannelMask;
6619 mDstSampleRate = dstSampleRate;
6620
6621 // compute derived parameters
6622 mSrcChannelCount = audio_channel_count_from_in_mask(srcChannelMask);
6623 mDstChannelCount = audio_channel_count_from_in_mask(dstChannelMask);
6624 mDstFrameSize = mDstChannelCount * audio_bytes_per_sample(mDstFormat);
6625
Andy Hungd330ee42015-04-20 13:23:41 -07006626 // do we need to resample?
6627 delete mResampler;
6628 mResampler = NULL;
6629 if (mSrcSampleRate != mDstSampleRate) {
6630 mResampler = AudioResampler::create(AUDIO_FORMAT_PCM_FLOAT,
6631 mSrcChannelCount, mDstSampleRate);
6632 mResampler->setSampleRate(mSrcSampleRate);
6633 mResampler->setVolume(AudioMixer::UNITY_GAIN_FLOAT, AudioMixer::UNITY_GAIN_FLOAT);
6634 }
6635
6636 // are we running legacy channel conversion modes?
6637 mIsLegacyDownmix = (mSrcChannelMask == AUDIO_CHANNEL_IN_STEREO
6638 || mSrcChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK)
6639 && mDstChannelMask == AUDIO_CHANNEL_IN_MONO;
6640 mIsLegacyUpmix = mSrcChannelMask == AUDIO_CHANNEL_IN_MONO
6641 && (mDstChannelMask == AUDIO_CHANNEL_IN_STEREO
6642 || mDstChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK);
6643
6644 // do we need to process in float?
6645 mRequiresFloat = mResampler != NULL || mIsLegacyDownmix || mIsLegacyUpmix;
6646
6647 // do we need a staging buffer to convert for destination (we can still optimize this)?
6648 // we use mBufFrameSize > 0 to indicate both frame size as well as buffer necessity
6649 if (mResampler != NULL) {
6650 mBufFrameSize = max(mSrcChannelCount, FCC_2)
6651 * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
Andy Hunga97630b2015-07-22 23:27:24 -07006652 } else if (mIsLegacyUpmix || mIsLegacyDownmix) { // legacy modes always float
Andy Hungd330ee42015-04-20 13:23:41 -07006653 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
6654 } else if (mSrcChannelMask != mDstChannelMask && mDstFormat != mSrcFormat) {
Andy Hung97a893e2015-03-29 01:03:07 -07006655 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(mSrcFormat);
6656 } else {
6657 mBufFrameSize = 0;
6658 }
6659 mBufFrames = 0; // force the buffer to be resized.
6660
Andy Hungd330ee42015-04-20 13:23:41 -07006661 // do we need an input converter buffer provider to give us float?
6662 delete mInputConverterProvider;
6663 mInputConverterProvider = NULL;
6664 if (mRequiresFloat && mSrcFormat != AUDIO_FORMAT_PCM_FLOAT) {
6665 mInputConverterProvider = new ReformatBufferProvider(
6666 audio_channel_count_from_in_mask(mSrcChannelMask),
6667 mSrcFormat,
6668 AUDIO_FORMAT_PCM_FLOAT,
6669 256 /* provider buffer frame count */);
6670 }
6671
6672 // do we need a remixer to do channel mask conversion
6673 if (!mIsLegacyDownmix && !mIsLegacyUpmix && mSrcChannelMask != mDstChannelMask) {
6674 (void) memcpy_by_index_array_initialization_from_channel_mask(
6675 mIdxAry, ARRAY_SIZE(mIdxAry), mDstChannelMask, mSrcChannelMask);
Andy Hung97a893e2015-03-29 01:03:07 -07006676 }
6677 return NO_ERROR;
6678}
6679
Andy Hungd330ee42015-04-20 13:23:41 -07006680void AudioFlinger::RecordThread::RecordBufferConverter::convertNoResampler(
6681 void *dst, const void *src, size_t frames)
Andy Hung97a893e2015-03-29 01:03:07 -07006682{
Andy Hungd330ee42015-04-20 13:23:41 -07006683 // src is native type unless there is legacy upmix or downmix, whereupon it is float.
Andy Hung97a893e2015-03-29 01:03:07 -07006684 if (mBufFrameSize != 0 && mBufFrames < frames) {
6685 free(mBuf);
6686 mBufFrames = frames;
6687 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
6688 }
Andy Hungd330ee42015-04-20 13:23:41 -07006689 // do we need to do legacy upmix and downmix?
6690 if (mIsLegacyUpmix || mIsLegacyDownmix) {
Andy Hung97a893e2015-03-29 01:03:07 -07006691 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07006692 if (mIsLegacyUpmix) {
6693 upmix_to_stereo_float_from_mono_float((float *)dstBuf,
6694 (const float *)src, frames);
6695 } else /*mIsLegacyDownmix */ {
6696 downmix_to_mono_float_from_stereo_float((float *)dstBuf,
6697 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006698 }
Andy Hungd330ee42015-04-20 13:23:41 -07006699 if (mBuf != NULL) {
6700 memcpy_by_audio_format(dst, mDstFormat, mBuf, AUDIO_FORMAT_PCM_FLOAT,
6701 frames * mDstChannelCount);
6702 }
6703 return;
6704 }
6705 // do we need to do channel mask conversion?
6706 if (mSrcChannelMask != mDstChannelMask) {
Andy Hung97a893e2015-03-29 01:03:07 -07006707 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07006708 memcpy_by_index_array(dstBuf, mDstChannelCount,
6709 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mSrcFormat), frames);
6710 if (dstBuf == dst) {
6711 return; // format is the same
6712 }
6713 }
6714 // convert to destination buffer
6715 const void *convertBuf = mBuf != NULL ? mBuf : src;
6716 memcpy_by_audio_format(dst, mDstFormat, convertBuf, mSrcFormat,
6717 frames * mDstChannelCount);
6718}
6719
6720void AudioFlinger::RecordThread::RecordBufferConverter::convertResampler(
6721 void *dst, /*not-a-const*/ void *src, size_t frames)
6722{
6723 // src buffer format is ALWAYS float when entering this routine
6724 if (mIsLegacyUpmix) {
6725 ; // mono to stereo already handled by resampler
6726 } else if (mIsLegacyDownmix
6727 || (mSrcChannelMask == mDstChannelMask && mSrcChannelCount == 1)) {
6728 // the resampler outputs stereo for mono input channel (a feature?)
6729 // must convert to mono
6730 downmix_to_mono_float_from_stereo_float((float *)src,
6731 (const float *)src, frames);
6732 } else if (mSrcChannelMask != mDstChannelMask) {
6733 // convert to mono channel again for channel mask conversion (could be skipped
6734 // with further optimization).
Andy Hung97a893e2015-03-29 01:03:07 -07006735 if (mSrcChannelCount == 1) {
Andy Hungd330ee42015-04-20 13:23:41 -07006736 downmix_to_mono_float_from_stereo_float((float *)src,
6737 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006738 }
Andy Hungd330ee42015-04-20 13:23:41 -07006739 // convert to destination format (in place, OK as float is larger than other types)
6740 if (mDstFormat != AUDIO_FORMAT_PCM_FLOAT) {
6741 memcpy_by_audio_format(src, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
6742 frames * mSrcChannelCount);
6743 }
6744 // channel convert and save to dst
6745 memcpy_by_index_array(dst, mDstChannelCount,
6746 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mDstFormat), frames);
6747 return;
Andy Hung97a893e2015-03-29 01:03:07 -07006748 }
Andy Hungd330ee42015-04-20 13:23:41 -07006749 // convert to destination format and save to dst
6750 memcpy_by_audio_format(dst, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
6751 frames * mDstChannelCount);
Andy Hung97a893e2015-03-29 01:03:07 -07006752}
6753
Eric Laurent10351942014-05-08 18:49:52 -07006754bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
6755 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006756{
6757 bool reconfig = false;
6758
Eric Laurent10351942014-05-08 18:49:52 -07006759 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006760
Eric Laurent10351942014-05-08 18:49:52 -07006761 audio_format_t reqFormat = mFormat;
6762 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07006763 // 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 -07006764 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
6765
6766 AudioParameter param = AudioParameter(keyValuePair);
6767 int value;
6768 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
6769 // channel count change can be requested. Do we mandate the first client defines the
6770 // HAL sampling rate and channel count or do we allow changes on the fly?
6771 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6772 samplingRate = value;
6773 reconfig = true;
6774 }
6775 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07006776 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07006777 status = BAD_VALUE;
6778 } else {
6779 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08006780 reconfig = true;
6781 }
Eric Laurent10351942014-05-08 18:49:52 -07006782 }
6783 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
6784 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07006785 if (!audio_is_input_channel(mask) ||
6786 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07006787 status = BAD_VALUE;
6788 } else {
6789 channelMask = mask;
6790 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006791 }
Eric Laurent10351942014-05-08 18:49:52 -07006792 }
6793 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6794 // do not accept frame count changes if tracks are open as the track buffer
6795 // size depends on frame count and correct behavior would not be guaranteed
6796 // if frame count is changed after track creation
6797 if (mActiveTracks.size() > 0) {
6798 status = INVALID_OPERATION;
6799 } else {
6800 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006801 }
Eric Laurent10351942014-05-08 18:49:52 -07006802 }
6803 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6804 // forward device change to effects that have requested to be
6805 // aware of attached audio device.
6806 for (size_t i = 0; i < mEffectChains.size(); i++) {
6807 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08006808 }
Eric Laurent81784c32012-11-19 14:55:58 -08006809
Eric Laurent10351942014-05-08 18:49:52 -07006810 // store input device and output device but do not forward output device to audio HAL.
6811 // Note that status is ignored by the caller for output device
6812 // (see AudioFlinger::setParameters()
6813 if (audio_is_output_devices(value)) {
6814 mOutDevice = value;
6815 status = BAD_VALUE;
6816 } else {
6817 mInDevice = value;
Eric Laurente8726fe2015-06-26 09:39:24 -07006818 if (value != AUDIO_DEVICE_NONE) {
6819 mPrevInDevice = value;
6820 }
Eric Laurent10351942014-05-08 18:49:52 -07006821 // disable AEC and NS if the device is a BT SCO headset supporting those
6822 // pre processings
6823 if (mTracks.size() > 0) {
6824 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6825 mAudioFlinger->btNrecIsOff();
6826 for (size_t i = 0; i < mTracks.size(); i++) {
6827 sp<RecordTrack> track = mTracks[i];
6828 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
6829 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08006830 }
6831 }
6832 }
Eric Laurent10351942014-05-08 18:49:52 -07006833 }
6834 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
6835 mAudioSource != (audio_source_t)value) {
6836 // forward device change to effects that have requested to be
6837 // aware of attached audio device.
6838 for (size_t i = 0; i < mEffectChains.size(); i++) {
6839 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08006840 }
Eric Laurent10351942014-05-08 18:49:52 -07006841 mAudioSource = (audio_source_t)value;
6842 }
Glenn Kastene198c362013-08-13 09:13:36 -07006843
Eric Laurent10351942014-05-08 18:49:52 -07006844 if (status == NO_ERROR) {
6845 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6846 keyValuePair.string());
6847 if (status == INVALID_OPERATION) {
6848 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006849 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6850 keyValuePair.string());
Eric Laurent10351942014-05-08 18:49:52 -07006851 }
6852 if (reconfig) {
6853 if (status == BAD_VALUE &&
Andy Hung97a893e2015-03-29 01:03:07 -07006854 audio_is_linear_pcm(mInput->stream->common.get_format(&mInput->stream->common)) &&
6855 audio_is_linear_pcm(reqFormat) &&
Eric Laurent10351942014-05-08 18:49:52 -07006856 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
Andy Hung97a893e2015-03-29 01:03:07 -07006857 <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate)) &&
Andy Hunge5412692014-05-16 11:25:07 -07006858 audio_channel_count_from_in_mask(
Andy Hungd1abb8f2015-05-05 23:42:34 -07006859 mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07006860 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006861 }
Eric Laurent10351942014-05-08 18:49:52 -07006862 if (status == NO_ERROR) {
6863 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07006864 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08006865 }
6866 }
Eric Laurent81784c32012-11-19 14:55:58 -08006867 }
Eric Laurent10351942014-05-08 18:49:52 -07006868
Eric Laurent81784c32012-11-19 14:55:58 -08006869 return reconfig;
6870}
6871
6872String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6873{
Eric Laurent81784c32012-11-19 14:55:58 -08006874 Mutex::Autolock _l(mLock);
6875 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07006876 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08006877 }
6878
Glenn Kastend8ea6992013-07-16 14:17:15 -07006879 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
6880 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08006881 free(s);
6882 return out_s8;
6883}
6884
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07006885void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07006886 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
6887
6888 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08006889
6890 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07006891 case AUDIO_INPUT_OPENED:
6892 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07006893 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07006894 desc->mChannelMask = mChannelMask;
6895 desc->mSamplingRate = mSampleRate;
6896 desc->mFormat = mFormat;
6897 desc->mFrameCount = mFrameCount;
6898 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006899 break;
6900
Eric Laurent73e26b62015-04-27 16:55:58 -07006901 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08006902 default:
6903 break;
6904 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07006905 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08006906}
6907
Glenn Kastendeca2ae2014-02-07 10:25:56 -08006908void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006909{
Eric Laurent81784c32012-11-19 14:55:58 -08006910 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
6911 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Andy Hunge5412692014-05-16 11:25:07 -07006912 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Andy Hungd330ee42015-04-20 13:23:41 -07006913 if (mChannelCount > FCC_8) {
6914 ALOGE("HAL channel count %d > %d", mChannelCount, FCC_8);
6915 }
Andy Hung463be252014-07-10 16:56:07 -07006916 mHALFormat = mInput->stream->common.get_format(&mInput->stream->common);
6917 mFormat = mHALFormat;
Andy Hungd330ee42015-04-20 13:23:41 -07006918 if (!audio_is_linear_pcm(mFormat)) {
6919 ALOGE("HAL format %#x is not linear pcm", mFormat);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07006920 }
Eric Laurent665470b2014-07-03 16:37:08 -07006921 mFrameSize = audio_stream_in_frame_size(mInput->stream);
Glenn Kasten548efc92012-11-29 08:48:51 -08006922 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
6923 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006924 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08006925 // 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 -07006926 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08006927 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006928 // A larger value should allow more old data to be read after a track calls start(),
6929 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07006930 //
6931 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08006932 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07006933 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07006934 free(mRsmpInBuffer);
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006935
6936 // TODO optimize audio capture buffer sizes ...
6937 // Here we calculate the size of the sliding buffer used as a source
6938 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
6939 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
6940 // be better to have it derived from the pipe depth in the long term.
6941 // The current value is higher than necessary. However it should not add to latency.
6942
Glenn Kasten85948432013-08-19 12:09:05 -07006943 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Andy Hung57446612015-04-19 23:56:46 -07006944 (void)posix_memalign(&mRsmpInBuffer, 32, (mRsmpInFramesP2 + mFrameCount - 1) * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006945
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006946 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
6947 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08006948}
6949
Glenn Kasten5f972c02014-01-13 09:59:31 -08006950uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08006951{
6952 Mutex::Autolock _l(mLock);
6953 if (initCheck() != NO_ERROR) {
6954 return 0;
6955 }
6956
6957 return mInput->stream->get_input_frames_lost(mInput->stream);
6958}
6959
6960uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
6961{
6962 Mutex::Autolock _l(mLock);
6963 uint32_t result = 0;
6964 if (getEffectChain_l(sessionId) != 0) {
6965 result = EFFECT_SESSION;
6966 }
6967
6968 for (size_t i = 0; i < mTracks.size(); ++i) {
6969 if (sessionId == mTracks[i]->sessionId()) {
6970 result |= TRACK_SESSION;
6971 break;
6972 }
6973 }
6974
6975 return result;
6976}
6977
6978KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
6979{
6980 KeyedVector<int, bool> ids;
6981 Mutex::Autolock _l(mLock);
6982 for (size_t j = 0; j < mTracks.size(); ++j) {
6983 sp<RecordThread::RecordTrack> track = mTracks[j];
6984 int sessionId = track->sessionId();
6985 if (ids.indexOfKey(sessionId) < 0) {
6986 ids.add(sessionId, true);
6987 }
6988 }
6989 return ids;
6990}
6991
6992AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
6993{
6994 Mutex::Autolock _l(mLock);
6995 AudioStreamIn *input = mInput;
6996 mInput = NULL;
6997 return input;
6998}
6999
7000// this method must always be called either with ThreadBase mLock held or inside the thread loop
7001audio_stream_t* AudioFlinger::RecordThread::stream() const
7002{
7003 if (mInput == NULL) {
7004 return NULL;
7005 }
7006 return &mInput->stream->common;
7007}
7008
7009status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7010{
7011 // only one chain per input thread
7012 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07007013 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08007014 return INVALID_OPERATION;
7015 }
7016 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07007017 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08007018 chain->setInBuffer(NULL);
7019 chain->setOutBuffer(NULL);
7020
7021 checkSuspendOnAddEffectChain_l(chain);
7022
Eric Laurent1b928682014-10-02 19:41:47 -07007023 // make sure enabled pre processing effects state is communicated to the HAL as we
7024 // just moved them to a new input stream.
7025 chain->syncHalEffectsState();
7026
Eric Laurent81784c32012-11-19 14:55:58 -08007027 mEffectChains.add(chain);
7028
7029 return NO_ERROR;
7030}
7031
7032size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7033{
7034 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
7035 ALOGW_IF(mEffectChains.size() != 1,
7036 "removeEffectChain_l() %p invalid chain size %d on thread %p",
7037 chain.get(), mEffectChains.size(), this);
7038 if (mEffectChains.size() == 1) {
7039 mEffectChains.removeAt(0);
7040 }
7041 return 0;
7042}
7043
Eric Laurent1c333e22014-05-20 10:48:17 -07007044status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
7045 audio_patch_handle_t *handle)
7046{
7047 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007048
7049 // store new device and send to effects
7050 mInDevice = patch->sources[0].ext.device.type;
Eric Laurent296fb132015-05-01 11:38:42 -07007051 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07007052 for (size_t i = 0; i < mEffectChains.size(); i++) {
7053 mEffectChains[i]->setDevice_l(mInDevice);
7054 }
7055
7056 // disable AEC and NS if the device is a BT SCO headset supporting those
7057 // pre processings
7058 if (mTracks.size() > 0) {
7059 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7060 mAudioFlinger->btNrecIsOff();
7061 for (size_t i = 0; i < mTracks.size(); i++) {
7062 sp<RecordTrack> track = mTracks[i];
7063 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7064 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
7065 }
7066 }
7067
7068 // store new source and send to effects
7069 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7070 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07007071 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07007072 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07007073 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007074 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007075
Eric Laurent054d9d32015-04-24 08:48:48 -07007076 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007077 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
7078 status = hwDevice->create_audio_patch(hwDevice,
7079 patch->num_sources,
7080 patch->sources,
7081 patch->num_sinks,
7082 patch->sinks,
7083 handle);
7084 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007085 char *address;
7086 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
7087 address = audio_device_address_to_parameter(
7088 patch->sources[0].ext.device.type,
7089 patch->sources[0].ext.device.address);
7090 } else {
7091 address = (char *)calloc(1, 1);
7092 }
7093 AudioParameter param = AudioParameter(String8(address));
7094 free(address);
7095 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING),
7096 (int)patch->sources[0].ext.device.type);
7097 param.addInt(String8(AUDIO_PARAMETER_STREAM_INPUT_SOURCE),
7098 (int)patch->sinks[0].ext.mix.usecase.source);
7099 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7100 param.toString().string());
7101 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07007102 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007103
Eric Laurente8726fe2015-06-26 09:39:24 -07007104 if (mInDevice != mPrevInDevice) {
7105 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
7106 mPrevInDevice = mInDevice;
7107 }
Eric Laurent296fb132015-05-01 11:38:42 -07007108
Eric Laurent1c333e22014-05-20 10:48:17 -07007109 return status;
7110}
7111
7112status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
7113{
7114 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007115
7116 mInDevice = AUDIO_DEVICE_NONE;
7117
Eric Laurent1c333e22014-05-20 10:48:17 -07007118 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
7119 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
7120 status = hwDevice->release_audio_patch(hwDevice, handle);
7121 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007122 AudioParameter param;
7123 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
7124 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7125 param.toString().string());
Eric Laurent1c333e22014-05-20 10:48:17 -07007126 }
7127 return status;
7128}
7129
Eric Laurent83b88082014-06-20 18:31:16 -07007130void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
7131{
7132 Mutex::Autolock _l(mLock);
7133 mTracks.add(record);
7134}
7135
7136void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
7137{
7138 Mutex::Autolock _l(mLock);
7139 destroyTrack_l(record);
7140}
7141
7142void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
7143{
7144 ThreadBase::getAudioPortConfig(config);
7145 config->role = AUDIO_PORT_ROLE_SINK;
7146 config->ext.mix.hw_module = mInput->audioHwDev->handle();
7147 config->ext.mix.usecase.source = mAudioSource;
7148}
Eric Laurent1c333e22014-05-20 10:48:17 -07007149
Glenn Kasten63238ef2015-03-02 15:50:29 -08007150} // namespace android