blob: 381ce921a584350877e37286593c223bfe1682c7 [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>
Wei Jia3f273d12015-11-24 09:06:49 -080051#include <mediautils/BatteryNotifier.h>
Eric Laurent81784c32012-11-19 14:55:58 -080052
53#include <powermanager/PowerManager.h>
54
55#include <common_time/cc_helper.h>
56#include <common_time/local_clock.h>
57
58#include "AudioFlinger.h"
59#include "AudioMixer.h"
Andy Hungd330ee42015-04-20 13:23:41 -070060#include "BufferProviders.h"
Eric Laurent81784c32012-11-19 14:55:58 -080061#include "FastMixer.h"
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070062#include "FastCapture.h"
Eric Laurent81784c32012-11-19 14:55:58 -080063#include "ServiceUtilities.h"
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -070064#include "mediautils/SchedulingPolicyService.h"
Eric Laurent81784c32012-11-19 14:55:58 -080065
Eric Laurent81784c32012-11-19 14:55:58 -080066#ifdef ADD_BATTERY_DATA
67#include <media/IMediaPlayerService.h>
68#include <media/IMediaDeathNotifier.h>
69#endif
70
Eric Laurent81784c32012-11-19 14:55:58 -080071#ifdef DEBUG_CPU_USAGE
72#include <cpustats/CentralTendencyStatistics.h>
73#include <cpustats/ThreadCpuUsage.h>
74#endif
75
76// ----------------------------------------------------------------------------
77
78// Note: the following macro is used for extremely verbose logging message. In
79// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
80// 0; but one side effect of this is to turn all LOGV's as well. Some messages
81// are so verbose that we want to suppress them even when we have ALOG_ASSERT
82// turned on. Do not uncomment the #def below unless you really know what you
83// are doing and want to see all of the extremely verbose messages.
84//#define VERY_VERY_VERBOSE_LOGGING
85#ifdef VERY_VERY_VERBOSE_LOGGING
86#define ALOGVV ALOGV
87#else
88#define ALOGVV(a...) do { } while(0)
89#endif
90
Andy Hung6770c6f2015-04-07 13:43:36 -070091// TODO: Move these macro/inlines to a header file.
Glenn Kasten49d00ad2014-07-21 11:22:03 -070092#define max(a, b) ((a) > (b) ? (a) : (b))
Andy Hung6770c6f2015-04-07 13:43:36 -070093template <typename T>
94static inline T min(const T& a, const T& b)
95{
96 return a < b ? a : b;
97}
Glenn Kasten49d00ad2014-07-21 11:22:03 -070098
Andy Hungd330ee42015-04-20 13:23:41 -070099#ifndef ARRAY_SIZE
100#define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
101#endif
102
Eric Laurent81784c32012-11-19 14:55:58 -0800103namespace android {
104
105// retry counts for buffer fill timeout
106// 50 * ~20msecs = 1 second
107static const int8_t kMaxTrackRetries = 50;
108static const int8_t kMaxTrackStartupRetries = 50;
109// allow less retry attempts on direct output thread.
110// direct outputs can be a scarce resource in audio hardware and should
111// be released as quickly as possible.
112static const int8_t kMaxTrackRetriesDirect = 2;
113
114// don't warn about blocked writes or record buffer overflows more often than this
115static const nsecs_t kWarningThrottleNs = seconds(5);
116
117// RecordThread loop sleep time upon application overrun or audio HAL read error
118static const int kRecordThreadSleepUs = 5000;
119
Eric Laurent10351942014-05-08 18:49:52 -0700120// maximum time to wait in sendConfigEvent_l() for a status to be received
121static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800122
123// minimum sleep time for the mixer thread loop when tracks are active but in underrun
124static const uint32_t kMinThreadSleepTimeUs = 5000;
125// maximum divider applied to the active sleep time in the mixer thread loop
126static const uint32_t kMaxThreadSleepTimeShift = 2;
127
Andy Hung09a50072014-02-27 14:30:47 -0800128// minimum normal sink buffer size, expressed in milliseconds rather than frames
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700129// FIXME This should be based on experimentally observed scheduling jitter
Andy Hung09a50072014-02-27 14:30:47 -0800130static const uint32_t kMinNormalSinkBufferSizeMs = 20;
131// maximum normal sink buffer size
132static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800133
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700134// minimum capture buffer size in milliseconds to _not_ need a fast capture thread
135// FIXME This should be based on experimentally observed scheduling jitter
136static const uint32_t kMinNormalCaptureBufferSizeMs = 12;
137
Eric Laurent972a1732013-09-04 09:42:59 -0700138// Offloaded output thread standby delay: allows track transition without going to standby
139static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
140
Eric Laurent81784c32012-11-19 14:55:58 -0800141// Whether to use fast mixer
142static const enum {
143 FastMixer_Never, // never initialize or use: for debugging only
144 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
145 // normal mixer multiplier is 1
146 FastMixer_Static, // initialize if needed, then use all the time if initialized,
147 // multiplier is calculated based on min & max normal mixer buffer size
148 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
149 // multiplier is calculated based on min & max normal mixer buffer size
150 // FIXME for FastMixer_Dynamic:
151 // Supporting this option will require fixing HALs that can't handle large writes.
152 // For example, one HAL implementation returns an error from a large write,
153 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
154 // We could either fix the HAL implementations, or provide a wrapper that breaks
155 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
156} kUseFastMixer = FastMixer_Static;
157
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700158// Whether to use fast capture
159static const enum {
160 FastCapture_Never, // never initialize or use: for debugging only
161 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
162 FastCapture_Static, // initialize if needed, then use all the time if initialized
163} kUseFastCapture = FastCapture_Static;
164
Eric Laurent81784c32012-11-19 14:55:58 -0800165// Priorities for requestPriority
166static const int kPriorityAudioApp = 2;
167static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700168static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800169
170// IAudioFlinger::createTrack() reports back to client the total size of shared memory area
171// for the track. The client then sub-divides this into smaller buffers for its use.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800172// Currently the client uses N-buffering by default, but doesn't tell us about the value of N.
173// So for now we just assume that client is double-buffered for fast tracks.
174// FIXME It would be better for client to tell AudioFlinger the value of N,
175// so AudioFlinger could allocate the right amount of memory.
Eric Laurent81784c32012-11-19 14:55:58 -0800176// See the client's minBufCount and mNotificationFramesAct calculations for details.
Glenn Kasten03490092014-05-27 12:30:54 -0700177
178// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800179static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800180
Glenn Kasten03490092014-05-27 12:30:54 -0700181// The minimum and maximum allowed values
182static const int kFastTrackMultiplierMin = 1;
183static const int kFastTrackMultiplierMax = 2;
184
185// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
186static int sFastTrackMultiplier = kFastTrackMultiplier;
187
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700188// See Thread::readOnlyHeap().
189// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
190// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
191// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Glenn Kasten9f81de32014-07-27 15:02:23 -0700192static const size_t kRecordThreadReadOnlyHeapSize = 0x2000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700193
Eric Laurent81784c32012-11-19 14:55:58 -0800194// ----------------------------------------------------------------------------
195
Glenn Kasten03490092014-05-27 12:30:54 -0700196static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
197
198static void sFastTrackMultiplierInit()
199{
200 char value[PROPERTY_VALUE_MAX];
201 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
202 char *endptr;
203 unsigned long ul = strtoul(value, &endptr, 0);
204 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
205 sFastTrackMultiplier = (int) ul;
206 }
207 }
208}
209
210// ----------------------------------------------------------------------------
211
Eric Laurent81784c32012-11-19 14:55:58 -0800212#ifdef ADD_BATTERY_DATA
213// To collect the amplifier usage
214static void addBatteryData(uint32_t params) {
215 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
216 if (service == NULL) {
217 // it already logged
218 return;
219 }
220
221 service->addBatteryData(params);
222}
223#endif
224
225
226// ----------------------------------------------------------------------------
227// CPU Stats
228// ----------------------------------------------------------------------------
229
230class CpuStats {
231public:
232 CpuStats();
233 void sample(const String8 &title);
234#ifdef DEBUG_CPU_USAGE
235private:
236 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
237 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
238
239 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
240
241 int mCpuNum; // thread's current CPU number
242 int mCpukHz; // frequency of thread's current CPU in kHz
243#endif
244};
245
246CpuStats::CpuStats()
247#ifdef DEBUG_CPU_USAGE
248 : mCpuNum(-1), mCpukHz(-1)
249#endif
250{
251}
252
Glenn Kasten0f11b512014-01-31 16:18:54 -0800253void CpuStats::sample(const String8 &title
254#ifndef DEBUG_CPU_USAGE
255 __unused
256#endif
257 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800258#ifdef DEBUG_CPU_USAGE
259 // get current thread's delta CPU time in wall clock ns
260 double wcNs;
261 bool valid = mCpuUsage.sampleAndEnable(wcNs);
262
263 // record sample for wall clock statistics
264 if (valid) {
265 mWcStats.sample(wcNs);
266 }
267
268 // get the current CPU number
269 int cpuNum = sched_getcpu();
270
271 // get the current CPU frequency in kHz
272 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
273
274 // check if either CPU number or frequency changed
275 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
276 mCpuNum = cpuNum;
277 mCpukHz = cpukHz;
278 // ignore sample for purposes of cycles
279 valid = false;
280 }
281
282 // if no change in CPU number or frequency, then record sample for cycle statistics
283 if (valid && mCpukHz > 0) {
284 double cycles = wcNs * cpukHz * 0.000001;
285 mHzStats.sample(cycles);
286 }
287
288 unsigned n = mWcStats.n();
289 // mCpuUsage.elapsed() is expensive, so don't call it every loop
290 if ((n & 127) == 1) {
291 long long elapsed = mCpuUsage.elapsed();
292 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
293 double perLoop = elapsed / (double) n;
294 double perLoop100 = perLoop * 0.01;
295 double perLoop1k = perLoop * 0.001;
296 double mean = mWcStats.mean();
297 double stddev = mWcStats.stddev();
298 double minimum = mWcStats.minimum();
299 double maximum = mWcStats.maximum();
300 double meanCycles = mHzStats.mean();
301 double stddevCycles = mHzStats.stddev();
302 double minCycles = mHzStats.minimum();
303 double maxCycles = mHzStats.maximum();
304 mCpuUsage.resetElapsed();
305 mWcStats.reset();
306 mHzStats.reset();
307 ALOGD("CPU usage for %s over past %.1f secs\n"
308 " (%u mixer loops at %.1f mean ms per loop):\n"
309 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
310 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
311 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
312 title.string(),
313 elapsed * .000000001, n, perLoop * .000001,
314 mean * .001,
315 stddev * .001,
316 minimum * .001,
317 maximum * .001,
318 mean / perLoop100,
319 stddev / perLoop100,
320 minimum / perLoop100,
321 maximum / perLoop100,
322 meanCycles / perLoop1k,
323 stddevCycles / perLoop1k,
324 minCycles / perLoop1k,
325 maxCycles / perLoop1k);
326
327 }
328 }
329#endif
330};
331
332// ----------------------------------------------------------------------------
333// ThreadBase
334// ----------------------------------------------------------------------------
335
Glenn Kasten97b7b752014-09-28 13:04:24 -0700336// static
337const char *AudioFlinger::ThreadBase::threadTypeToString(AudioFlinger::ThreadBase::type_t type)
338{
339 switch (type) {
340 case MIXER:
341 return "MIXER";
342 case DIRECT:
343 return "DIRECT";
344 case DUPLICATING:
345 return "DUPLICATING";
346 case RECORD:
347 return "RECORD";
348 case OFFLOAD:
349 return "OFFLOAD";
350 default:
351 return "unknown";
352 }
353}
354
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800355String8 devicesToString(audio_devices_t devices)
356{
357 static const struct mapping {
358 audio_devices_t mDevices;
359 const char * mString;
360 } mappingsOut[] = {
Glenn Kasten818da522015-12-02 13:53:26 -0800361 {AUDIO_DEVICE_OUT_EARPIECE, "EARPIECE"},
362 {AUDIO_DEVICE_OUT_SPEAKER, "SPEAKER"},
363 {AUDIO_DEVICE_OUT_WIRED_HEADSET, "WIRED_HEADSET"},
364 {AUDIO_DEVICE_OUT_WIRED_HEADPHONE, "WIRED_HEADPHONE"},
365 {AUDIO_DEVICE_OUT_BLUETOOTH_SCO, "BLUETOOTH_SCO"},
366 {AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET, "BLUETOOTH_SCO_HEADSET"},
367 {AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT, "BLUETOOTH_SCO_CARKIT"},
368 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, "BLUETOOTH_A2DP"},
369 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,"BLUETOOTH_A2DP_HEADPHONES"},
370 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER, "BLUETOOTH_A2DP_SPEAKER"},
371 {AUDIO_DEVICE_OUT_AUX_DIGITAL, "AUX_DIGITAL"},
372 {AUDIO_DEVICE_OUT_HDMI, "HDMI"},
373 {AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET,"ANLG_DOCK_HEADSET"},
374 {AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET,"DGTL_DOCK_HEADSET"},
375 {AUDIO_DEVICE_OUT_USB_ACCESSORY, "USB_ACCESSORY"},
376 {AUDIO_DEVICE_OUT_USB_DEVICE, "USB_DEVICE"},
377 {AUDIO_DEVICE_OUT_TELEPHONY_TX, "TELEPHONY_TX"},
378 {AUDIO_DEVICE_OUT_LINE, "LINE"},
379 {AUDIO_DEVICE_OUT_HDMI_ARC, "HDMI_ARC"},
380 {AUDIO_DEVICE_OUT_SPDIF, "SPDIF"},
381 {AUDIO_DEVICE_OUT_FM, "FM"},
382 {AUDIO_DEVICE_OUT_AUX_LINE, "AUX_LINE"},
383 {AUDIO_DEVICE_OUT_SPEAKER_SAFE, "SPEAKER_SAFE"},
384 {AUDIO_DEVICE_OUT_IP, "IP"},
385 {AUDIO_DEVICE_NONE, "NONE"}, // must be last
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800386 }, mappingsIn[] = {
Glenn Kasten818da522015-12-02 13:53:26 -0800387 {AUDIO_DEVICE_IN_COMMUNICATION, "COMMUNICATION"},
388 {AUDIO_DEVICE_IN_AMBIENT, "AMBIENT"},
389 {AUDIO_DEVICE_IN_BUILTIN_MIC, "BUILTIN_MIC"},
390 {AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET, "BLUETOOTH_SCO_HEADSET"},
391 {AUDIO_DEVICE_IN_WIRED_HEADSET, "WIRED_HEADSET"},
392 {AUDIO_DEVICE_IN_AUX_DIGITAL, "AUX_DIGITAL"},
393 {AUDIO_DEVICE_IN_VOICE_CALL, "VOICE_CALL"},
394 {AUDIO_DEVICE_IN_TELEPHONY_RX, "TELEPHONY_RX"},
395 {AUDIO_DEVICE_IN_BACK_MIC, "BACK_MIC"},
396 {AUDIO_DEVICE_IN_REMOTE_SUBMIX, "REMOTE_SUBMIX"},
397 {AUDIO_DEVICE_IN_ANLG_DOCK_HEADSET, "ANLG_DOCK_HEADSET"},
398 {AUDIO_DEVICE_IN_DGTL_DOCK_HEADSET, "DGTL_DOCK_HEADSET"},
399 {AUDIO_DEVICE_IN_USB_ACCESSORY, "USB_ACCESSORY"},
400 {AUDIO_DEVICE_IN_USB_DEVICE, "USB_DEVICE"},
401 {AUDIO_DEVICE_IN_FM_TUNER, "FM_TUNER"},
402 {AUDIO_DEVICE_IN_TV_TUNER, "TV_TUNER"},
403 {AUDIO_DEVICE_IN_LINE, "LINE"},
404 {AUDIO_DEVICE_IN_SPDIF, "SPDIF"},
405 {AUDIO_DEVICE_IN_BLUETOOTH_A2DP, "BLUETOOTH_A2DP"},
406 {AUDIO_DEVICE_IN_LOOPBACK, "LOOPBACK"},
407 {AUDIO_DEVICE_IN_IP, "IP"},
408 {AUDIO_DEVICE_NONE, "NONE"}, // must be last
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800409 };
410 String8 result;
411 audio_devices_t allDevices = AUDIO_DEVICE_NONE;
412 const mapping *entry;
413 if (devices & AUDIO_DEVICE_BIT_IN) {
414 devices &= ~AUDIO_DEVICE_BIT_IN;
415 entry = mappingsIn;
416 } else {
417 entry = mappingsOut;
418 }
419 for ( ; entry->mDevices != AUDIO_DEVICE_NONE; entry++) {
420 allDevices = (audio_devices_t) (allDevices | entry->mDevices);
421 if (devices & entry->mDevices) {
422 if (!result.isEmpty()) {
423 result.append("|");
424 }
425 result.append(entry->mString);
426 }
427 }
428 if (devices & ~allDevices) {
429 if (!result.isEmpty()) {
430 result.append("|");
431 }
432 result.appendFormat("0x%X", devices & ~allDevices);
433 }
434 if (result.isEmpty()) {
435 result.append(entry->mString);
436 }
437 return result;
438}
439
440String8 inputFlagsToString(audio_input_flags_t flags)
441{
442 static const struct mapping {
443 audio_input_flags_t mFlag;
444 const char * mString;
445 } mappings[] = {
Glenn Kasten818da522015-12-02 13:53:26 -0800446 {AUDIO_INPUT_FLAG_FAST, "FAST"},
447 {AUDIO_INPUT_FLAG_HW_HOTWORD, "HW_HOTWORD"},
448 {AUDIO_INPUT_FLAG_RAW, "RAW"},
449 {AUDIO_INPUT_FLAG_SYNC, "SYNC"},
450 {AUDIO_INPUT_FLAG_NONE, "NONE"}, // must be last
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800451 };
452 String8 result;
453 audio_input_flags_t allFlags = AUDIO_INPUT_FLAG_NONE;
454 const mapping *entry;
455 for (entry = mappings; entry->mFlag != AUDIO_INPUT_FLAG_NONE; entry++) {
456 allFlags = (audio_input_flags_t) (allFlags | entry->mFlag);
457 if (flags & entry->mFlag) {
458 if (!result.isEmpty()) {
459 result.append("|");
460 }
461 result.append(entry->mString);
462 }
463 }
464 if (flags & ~allFlags) {
465 if (!result.isEmpty()) {
466 result.append("|");
467 }
468 result.appendFormat("0x%X", flags & ~allFlags);
469 }
470 if (result.isEmpty()) {
471 result.append(entry->mString);
472 }
473 return result;
474}
475
476String8 outputFlagsToString(audio_output_flags_t flags)
Glenn Kasten97b7b752014-09-28 13:04:24 -0700477{
478 static const struct mapping {
479 audio_output_flags_t mFlag;
480 const char * mString;
481 } mappings[] = {
Glenn Kasten818da522015-12-02 13:53:26 -0800482 {AUDIO_OUTPUT_FLAG_DIRECT, "DIRECT"},
483 {AUDIO_OUTPUT_FLAG_PRIMARY, "PRIMARY"},
484 {AUDIO_OUTPUT_FLAG_FAST, "FAST"},
485 {AUDIO_OUTPUT_FLAG_DEEP_BUFFER, "DEEP_BUFFER"},
486 {AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,"COMPRESS_OFFLOAD"},
487 {AUDIO_OUTPUT_FLAG_NON_BLOCKING, "NON_BLOCKING"},
488 {AUDIO_OUTPUT_FLAG_HW_AV_SYNC, "HW_AV_SYNC"},
489 {AUDIO_OUTPUT_FLAG_RAW, "RAW"},
490 {AUDIO_OUTPUT_FLAG_SYNC, "SYNC"},
491 {AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO, "IEC958_NONAUDIO"},
492 {AUDIO_OUTPUT_FLAG_NONE, "NONE"}, // must be last
Glenn Kasten97b7b752014-09-28 13:04:24 -0700493 };
494 String8 result;
495 audio_output_flags_t allFlags = AUDIO_OUTPUT_FLAG_NONE;
496 const mapping *entry;
497 for (entry = mappings; entry->mFlag != AUDIO_OUTPUT_FLAG_NONE; entry++) {
498 allFlags = (audio_output_flags_t) (allFlags | entry->mFlag);
499 if (flags & entry->mFlag) {
500 if (!result.isEmpty()) {
501 result.append("|");
502 }
503 result.append(entry->mString);
504 }
505 }
506 if (flags & ~allFlags) {
507 if (!result.isEmpty()) {
508 result.append("|");
509 }
510 result.appendFormat("0x%X", flags & ~allFlags);
511 }
512 if (result.isEmpty()) {
513 result.append(entry->mString);
514 }
515 return result;
516}
517
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800518const char *sourceToString(audio_source_t source)
519{
520 switch (source) {
521 case AUDIO_SOURCE_DEFAULT: return "default";
522 case AUDIO_SOURCE_MIC: return "mic";
523 case AUDIO_SOURCE_VOICE_UPLINK: return "voice uplink";
524 case AUDIO_SOURCE_VOICE_DOWNLINK: return "voice downlink";
525 case AUDIO_SOURCE_VOICE_CALL: return "voice call";
526 case AUDIO_SOURCE_CAMCORDER: return "camcorder";
527 case AUDIO_SOURCE_VOICE_RECOGNITION: return "voice recognition";
528 case AUDIO_SOURCE_VOICE_COMMUNICATION: return "voice communication";
529 case AUDIO_SOURCE_REMOTE_SUBMIX: return "remote submix";
rago8a397d52015-12-02 11:27:57 -0800530 case AUDIO_SOURCE_UNPROCESSED: return "unprocessed";
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800531 case AUDIO_SOURCE_FM_TUNER: return "FM tuner";
532 case AUDIO_SOURCE_HOTWORD: return "hotword";
533 default: return "unknown";
534 }
535}
536
Eric Laurent81784c32012-11-19 14:55:58 -0800537AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -0700538 audio_devices_t outDevice, audio_devices_t inDevice, type_t type, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -0800539 : Thread(false /*canCallJava*/),
540 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700541 mAudioFlinger(audioFlinger),
Glenn Kasten70949c42013-08-06 07:40:12 -0700542 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800543 // are set by PlaybackThread::readOutputParameters_l() or
544 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700545 //FIXME: mStandby should be true here. Is this some kind of hack?
Eric Laurent81784c32012-11-19 14:55:58 -0800546 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700547 mPrevOutDevice(AUDIO_DEVICE_NONE), mPrevInDevice(AUDIO_DEVICE_NONE),
548 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Eric Laurent81784c32012-11-19 14:55:58 -0800549 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700550 mDeathRecipient(new PMDeathRecipient(this)),
Wei Jia3f273d12015-11-24 09:06:49 -0800551 mSystemReady(systemReady),
552 mNotifiedBatteryStart(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800553{
Eric Laurent296fb132015-05-01 11:38:42 -0700554 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800555}
556
557AudioFlinger::ThreadBase::~ThreadBase()
558{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700559 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700560 mConfigEvents.clear();
561
Eric Laurent81784c32012-11-19 14:55:58 -0800562 // do not lock the mutex in destructor
563 releaseWakeLock_l();
564 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800565 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800566 binder->unlinkToDeath(mDeathRecipient);
567 }
568}
569
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700570status_t AudioFlinger::ThreadBase::readyToRun()
571{
572 status_t status = initCheck();
573 if (status == NO_ERROR) {
574 ALOGI("AudioFlinger's thread %p ready to run", this);
575 } else {
576 ALOGE("No working audio driver found.");
577 }
578 return status;
579}
580
Eric Laurent81784c32012-11-19 14:55:58 -0800581void AudioFlinger::ThreadBase::exit()
582{
583 ALOGV("ThreadBase::exit");
584 // do any cleanup required for exit to succeed
585 preExit();
586 {
587 // This lock prevents the following race in thread (uniprocessor for illustration):
588 // if (!exitPending()) {
589 // // context switch from here to exit()
590 // // exit() calls requestExit(), what exitPending() observes
591 // // exit() calls signal(), which is dropped since no waiters
592 // // context switch back from exit() to here
593 // mWaitWorkCV.wait(...);
594 // // now thread is hung
595 // }
596 AutoMutex lock(mLock);
597 requestExit();
598 mWaitWorkCV.broadcast();
599 }
600 // When Thread::requestExitAndWait is made virtual and this method is renamed to
601 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
602 requestExitAndWait();
603}
604
605status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
606{
607 status_t status;
608
609 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
610 Mutex::Autolock _l(mLock);
611
Eric Laurent10351942014-05-08 18:49:52 -0700612 return sendSetParameterConfigEvent_l(keyValuePairs);
613}
614
615// sendConfigEvent_l() must be called with ThreadBase::mLock held
616// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
617status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
618{
619 status_t status = NO_ERROR;
620
Eric Laurent72e3f392015-05-20 14:43:50 -0700621 if (event->mRequiresSystemReady && !mSystemReady) {
622 event->mWaitStatus = false;
623 mPendingConfigEvents.add(event);
624 return status;
625 }
Eric Laurent10351942014-05-08 18:49:52 -0700626 mConfigEvents.add(event);
627 ALOGV("sendConfigEvent_l() num events %d event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800628 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700629 mLock.unlock();
630 {
631 Mutex::Autolock _l(event->mLock);
632 while (event->mWaitStatus) {
633 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
634 event->mStatus = TIMED_OUT;
635 event->mWaitStatus = false;
636 }
637 }
638 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800639 }
Eric Laurent10351942014-05-08 18:49:52 -0700640 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800641 return status;
642}
643
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700644void AudioFlinger::ThreadBase::sendIoConfigEvent(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800645{
646 Mutex::Autolock _l(mLock);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700647 sendIoConfigEvent_l(event, pid);
Eric Laurent81784c32012-11-19 14:55:58 -0800648}
649
650// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700651void AudioFlinger::ThreadBase::sendIoConfigEvent_l(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800652{
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700653 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid);
Eric Laurent10351942014-05-08 18:49:52 -0700654 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800655}
656
Eric Laurent72e3f392015-05-20 14:43:50 -0700657void AudioFlinger::ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio)
658{
659 Mutex::Autolock _l(mLock);
660 sendPrioConfigEvent_l(pid, tid, prio);
661}
662
Eric Laurent81784c32012-11-19 14:55:58 -0800663// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
664void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
665{
Eric Laurent10351942014-05-08 18:49:52 -0700666 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio);
667 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800668}
669
Eric Laurent10351942014-05-08 18:49:52 -0700670// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
671status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800672{
Eric Laurent10351942014-05-08 18:49:52 -0700673 sp<ConfigEvent> configEvent = (ConfigEvent *)new SetParameterConfigEvent(keyValuePair);
674 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700675}
676
Eric Laurent1c333e22014-05-20 10:48:17 -0700677status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
678 const struct audio_patch *patch,
679 audio_patch_handle_t *handle)
680{
681 Mutex::Autolock _l(mLock);
682 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
683 status_t status = sendConfigEvent_l(configEvent);
684 if (status == NO_ERROR) {
685 CreateAudioPatchConfigEventData *data =
686 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
687 *handle = data->mHandle;
688 }
689 return status;
690}
691
692status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
693 const audio_patch_handle_t handle)
694{
695 Mutex::Autolock _l(mLock);
696 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
697 return sendConfigEvent_l(configEvent);
698}
699
700
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700701// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700702void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700703{
Eric Laurent10351942014-05-08 18:49:52 -0700704 bool configChanged = false;
705
Eric Laurent81784c32012-11-19 14:55:58 -0800706 while (!mConfigEvents.isEmpty()) {
Eric Laurent10351942014-05-08 18:49:52 -0700707 ALOGV("processConfigEvents_l() remaining events %d", mConfigEvents.size());
708 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800709 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700710 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700711 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700712 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
713 // FIXME Need to understand why this has to be done asynchronously
714 int err = requestPriority(data->mPid, data->mTid, data->mPrio,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700715 true /*asynchronous*/);
716 if (err != 0) {
717 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700718 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700719 }
720 } break;
721 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700722 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700723 ioConfigChanged(data->mEvent, data->mPid);
Eric Laurent10351942014-05-08 18:49:52 -0700724 } break;
725 case CFG_EVENT_SET_PARAMETER: {
726 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
727 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
728 configChanged = true;
Glenn Kastend5418eb2013-08-14 13:11:06 -0700729 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700730 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700731 case CFG_EVENT_CREATE_AUDIO_PATCH: {
732 CreateAudioPatchConfigEventData *data =
733 (CreateAudioPatchConfigEventData *)event->mData.get();
734 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
735 } break;
736 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
737 ReleaseAudioPatchConfigEventData *data =
738 (ReleaseAudioPatchConfigEventData *)event->mData.get();
739 event->mStatus = releaseAudioPatch_l(data->mHandle);
740 } break;
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700741 default:
Eric Laurent10351942014-05-08 18:49:52 -0700742 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700743 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800744 }
Eric Laurent10351942014-05-08 18:49:52 -0700745 {
746 Mutex::Autolock _l(event->mLock);
747 if (event->mWaitStatus) {
748 event->mWaitStatus = false;
749 event->mCond.signal();
750 }
751 }
752 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
753 }
754
755 if (configChanged) {
756 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800757 }
Eric Laurent81784c32012-11-19 14:55:58 -0800758}
759
Marco Nelissenb2208842014-02-07 14:00:50 -0800760String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
761 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700762 const audio_channel_representation_t representation =
763 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700764
765 switch (representation) {
766 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
767 if (output) {
768 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
769 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
770 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
771 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
772 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
773 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
774 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
775 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
776 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
777 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
778 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
779 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
780 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
781 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
782 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
783 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
784 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
785 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
786 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
787 } else {
788 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
789 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
790 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
791 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
792 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
793 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
794 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
795 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
796 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
797 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
798 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
799 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
800 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
801 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
802 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
803 }
804 const int len = s.length();
805 if (len > 2) {
806 char *str = s.lockBuffer(len); // needed?
807 s.unlockBuffer(len - 2); // remove trailing ", "
808 }
809 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800810 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700811 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
812 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
813 return s;
814 default:
815 s.appendFormat("unknown mask, representation:%d bits:%#x",
816 representation, audio_channel_mask_get_bits(mask));
817 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800818 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800819}
820
Glenn Kasten0f11b512014-01-31 16:18:54 -0800821void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800822{
823 const size_t SIZE = 256;
824 char buffer[SIZE];
825 String8 result;
826
827 bool locked = AudioFlinger::dumpTryLock(mLock);
828 if (!locked) {
Glenn Kasten97b7b752014-09-28 13:04:24 -0700829 dprintf(fd, "thread %p may be deadlocked\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -0800830 }
831
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800832 dprintf(fd, " Thread name: %s\n", mThreadName);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700833 dprintf(fd, " I/O handle: %d\n", mId);
834 dprintf(fd, " TID: %d\n", getTid());
835 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700836 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700837 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700838 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat));
Elliott Hughes87cebad2014-05-22 10:14:43 -0700839 dprintf(fd, " HAL buffer size: %u bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700840 dprintf(fd, " Channel count: %u\n", mChannelCount);
841 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800842 channelMaskToString(mChannelMask, mType != RECORD).string());
Glenn Kastenf87c2f52015-08-21 08:03:57 -0700843 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat, formatToString(mFormat));
844 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700845 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800846 size_t numConfig = mConfigEvents.size();
847 if (numConfig) {
848 for (size_t i = 0; i < numConfig; i++) {
849 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700850 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800851 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700852 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800853 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700854 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800855 }
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800856 dprintf(fd, " Output device: %#x (%s)\n", mOutDevice, devicesToString(mOutDevice).string());
857 dprintf(fd, " Input device: %#x (%s)\n", mInDevice, devicesToString(mInDevice).string());
858 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, sourceToString(mAudioSource));
Eric Laurent81784c32012-11-19 14:55:58 -0800859
860 if (locked) {
861 mLock.unlock();
862 }
863}
864
865void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
866{
867 const size_t SIZE = 256;
868 char buffer[SIZE];
869 String8 result;
870
Marco Nelissenb2208842014-02-07 14:00:50 -0800871 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000872 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800873 write(fd, buffer, strlen(buffer));
874
Marco Nelissenb2208842014-02-07 14:00:50 -0800875 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800876 sp<EffectChain> chain = mEffectChains[i];
877 if (chain != 0) {
878 chain->dump(fd, args);
879 }
880 }
881}
882
Marco Nelissene14a5d62013-10-03 08:51:24 -0700883void AudioFlinger::ThreadBase::acquireWakeLock(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800884{
885 Mutex::Autolock _l(mLock);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700886 acquireWakeLock_l(uid);
Eric Laurent81784c32012-11-19 14:55:58 -0800887}
888
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100889String16 AudioFlinger::ThreadBase::getWakeLockTag()
890{
891 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -0800892 case MIXER:
893 return String16("AudioMix");
894 case DIRECT:
895 return String16("AudioDirectOut");
896 case DUPLICATING:
897 return String16("AudioDup");
898 case RECORD:
899 return String16("AudioIn");
900 case OFFLOAD:
901 return String16("AudioOffload");
902 default:
903 ALOG_ASSERT(false);
904 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100905 }
906}
907
Marco Nelissene14a5d62013-10-03 08:51:24 -0700908void AudioFlinger::ThreadBase::acquireWakeLock_l(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800909{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800910 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800911 if (mPowerManager != 0) {
912 sp<IBinder> binder = new BBinder();
Marco Nelissene14a5d62013-10-03 08:51:24 -0700913 status_t status;
914 if (uid >= 0) {
Eric Laurent547789d2013-10-04 11:46:55 -0700915 status = mPowerManager->acquireWakeLockWithUid(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700916 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100917 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -0700918 String16("audioserver"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700919 uid,
920 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700921 } else {
Eric Laurent547789d2013-10-04 11:46:55 -0700922 status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700923 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100924 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -0700925 String16("audioserver"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700926 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700927 }
Eric Laurent81784c32012-11-19 14:55:58 -0800928 if (status == NO_ERROR) {
929 mWakeLockToken = binder;
930 }
Glenn Kastend7dca052015-03-05 16:05:54 -0800931 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Eric Laurent81784c32012-11-19 14:55:58 -0800932 }
Wei Jia3f273d12015-11-24 09:06:49 -0800933
934 if (!mNotifiedBatteryStart) {
935 BatteryNotifier::getInstance().noteStartAudio();
936 mNotifiedBatteryStart = true;
937 }
Eric Laurent81784c32012-11-19 14:55:58 -0800938}
939
940void AudioFlinger::ThreadBase::releaseWakeLock()
941{
942 Mutex::Autolock _l(mLock);
943 releaseWakeLock_l();
944}
945
946void AudioFlinger::ThreadBase::releaseWakeLock_l()
947{
948 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800949 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -0800950 if (mPowerManager != 0) {
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700951 mPowerManager->releaseWakeLock(mWakeLockToken, 0,
952 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800953 }
954 mWakeLockToken.clear();
955 }
Wei Jia3f273d12015-11-24 09:06:49 -0800956
957 if (mNotifiedBatteryStart) {
958 BatteryNotifier::getInstance().noteStopAudio();
959 mNotifiedBatteryStart = false;
960 }
Eric Laurent81784c32012-11-19 14:55:58 -0800961}
962
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800963void AudioFlinger::ThreadBase::updateWakeLockUids(const SortedVector<int> &uids) {
964 Mutex::Autolock _l(mLock);
965 updateWakeLockUids_l(uids);
966}
967
968void AudioFlinger::ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -0700969 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800970 // use checkService() to avoid blocking if power service is not up yet
971 sp<IBinder> binder =
972 defaultServiceManager()->checkService(String16("power"));
973 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800974 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800975 } else {
976 mPowerManager = interface_cast<IPowerManager>(binder);
977 binder->linkToDeath(mDeathRecipient);
978 }
979 }
980}
981
982void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<int> &uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800983 getPowerManager_l();
Andy Hung438e7572015-12-14 15:51:17 -0800984 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
985 if (mSystemReady) {
986 ALOGE("no wake lock to update, but system ready!");
987 } else {
988 ALOGW("no wake lock to update, system not ready yet");
989 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800990 return;
991 }
992 if (mPowerManager != 0) {
993 sp<IBinder> binder = new BBinder();
994 status_t status;
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700995 status = mPowerManager->updateWakeLockUids(mWakeLockToken, uids.size(), uids.array(),
996 true /* FIXME force oneway contrary to .aidl */);
Glenn Kastend7dca052015-03-05 16:05:54 -0800997 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800998 }
999}
1000
Eric Laurent81784c32012-11-19 14:55:58 -08001001void AudioFlinger::ThreadBase::clearPowerManager()
1002{
1003 Mutex::Autolock _l(mLock);
1004 releaseWakeLock_l();
1005 mPowerManager.clear();
1006}
1007
Glenn Kasten0f11b512014-01-31 16:18:54 -08001008void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001009{
1010 sp<ThreadBase> thread = mThread.promote();
1011 if (thread != 0) {
1012 thread->clearPowerManager();
1013 }
1014 ALOGW("power manager service died !!!");
1015}
1016
1017void AudioFlinger::ThreadBase::setEffectSuspended(
1018 const effect_uuid_t *type, bool suspend, int sessionId)
1019{
1020 Mutex::Autolock _l(mLock);
1021 setEffectSuspended_l(type, suspend, sessionId);
1022}
1023
1024void AudioFlinger::ThreadBase::setEffectSuspended_l(
1025 const effect_uuid_t *type, bool suspend, int sessionId)
1026{
1027 sp<EffectChain> chain = getEffectChain_l(sessionId);
1028 if (chain != 0) {
1029 if (type != NULL) {
1030 chain->setEffectSuspended_l(type, suspend);
1031 } else {
1032 chain->setEffectSuspendedAll_l(suspend);
1033 }
1034 }
1035
1036 updateSuspendedSessions_l(type, suspend, sessionId);
1037}
1038
1039void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1040{
1041 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1042 if (index < 0) {
1043 return;
1044 }
1045
1046 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1047 mSuspendedSessions.valueAt(index);
1048
1049 for (size_t i = 0; i < sessionEffects.size(); i++) {
1050 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
1051 for (int j = 0; j < desc->mRefCount; j++) {
1052 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1053 chain->setEffectSuspendedAll_l(true);
1054 } else {
1055 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1056 desc->mType.timeLow);
1057 chain->setEffectSuspended_l(&desc->mType, true);
1058 }
1059 }
1060 }
1061}
1062
1063void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1064 bool suspend,
1065 int sessionId)
1066{
1067 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1068
1069 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1070
1071 if (suspend) {
1072 if (index >= 0) {
1073 sessionEffects = mSuspendedSessions.valueAt(index);
1074 } else {
1075 mSuspendedSessions.add(sessionId, sessionEffects);
1076 }
1077 } else {
1078 if (index < 0) {
1079 return;
1080 }
1081 sessionEffects = mSuspendedSessions.valueAt(index);
1082 }
1083
1084
1085 int key = EffectChain::kKeyForSuspendAll;
1086 if (type != NULL) {
1087 key = type->timeLow;
1088 }
1089 index = sessionEffects.indexOfKey(key);
1090
1091 sp<SuspendedSessionDesc> desc;
1092 if (suspend) {
1093 if (index >= 0) {
1094 desc = sessionEffects.valueAt(index);
1095 } else {
1096 desc = new SuspendedSessionDesc();
1097 if (type != NULL) {
1098 desc->mType = *type;
1099 }
1100 sessionEffects.add(key, desc);
1101 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1102 }
1103 desc->mRefCount++;
1104 } else {
1105 if (index < 0) {
1106 return;
1107 }
1108 desc = sessionEffects.valueAt(index);
1109 if (--desc->mRefCount == 0) {
1110 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1111 sessionEffects.removeItemsAt(index);
1112 if (sessionEffects.isEmpty()) {
1113 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1114 sessionId);
1115 mSuspendedSessions.removeItem(sessionId);
1116 }
1117 }
1118 }
1119 if (!sessionEffects.isEmpty()) {
1120 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1121 }
1122}
1123
1124void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1125 bool enabled,
1126 int sessionId)
1127{
1128 Mutex::Autolock _l(mLock);
1129 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1130}
1131
1132void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1133 bool enabled,
1134 int sessionId)
1135{
1136 if (mType != RECORD) {
1137 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1138 // another session. This gives the priority to well behaved effect control panels
1139 // and applications not using global effects.
1140 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1141 // global effects
1142 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
1143 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1144 }
1145 }
1146
1147 sp<EffectChain> chain = getEffectChain_l(sessionId);
1148 if (chain != 0) {
1149 chain->checkSuspendOnEffectEnabled(effect, enabled);
1150 }
1151}
1152
1153// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1154sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1155 const sp<AudioFlinger::Client>& client,
1156 const sp<IEffectClient>& effectClient,
1157 int32_t priority,
1158 int sessionId,
1159 effect_descriptor_t *desc,
1160 int *enabled,
Glenn Kasten9156ef32013-08-06 15:39:08 -07001161 status_t *status)
Eric Laurent81784c32012-11-19 14:55:58 -08001162{
1163 sp<EffectModule> effect;
1164 sp<EffectHandle> handle;
1165 status_t lStatus;
1166 sp<EffectChain> chain;
1167 bool chainCreated = false;
1168 bool effectCreated = false;
1169 bool effectRegistered = false;
1170
1171 lStatus = initCheck();
1172 if (lStatus != NO_ERROR) {
1173 ALOGW("createEffect_l() Audio driver not initialized.");
1174 goto Exit;
1175 }
1176
Andy Hung98ef9782014-03-04 14:46:50 -08001177 // Reject any effect on Direct output threads for now, since the format of
1178 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1179 if (mType == DIRECT) {
1180 ALOGW("createEffect_l() Cannot add effect %s on Direct output type thread %s",
Glenn Kastend7dca052015-03-05 16:05:54 -08001181 desc->name, mThreadName);
Andy Hung98ef9782014-03-04 14:46:50 -08001182 lStatus = BAD_VALUE;
1183 goto Exit;
1184 }
1185
Andy Hung389cfdb2014-08-07 17:49:53 -07001186 // Reject any effect on mixer or duplicating multichannel sinks.
Andy Hung9a592762014-07-21 21:56:01 -07001187 // TODO: fix both format and multichannel issues with effects.
Andy Hung389cfdb2014-08-07 17:49:53 -07001188 if ((mType == MIXER || mType == DUPLICATING) && mChannelCount != FCC_2) {
1189 ALOGW("createEffect_l() Cannot add effect %s for multichannel(%d) %s threads",
1190 desc->name, mChannelCount, mType == MIXER ? "MIXER" : "DUPLICATING");
Andy Hung9a592762014-07-21 21:56:01 -07001191 lStatus = BAD_VALUE;
1192 goto Exit;
1193 }
1194
Eric Laurent5baf2af2013-09-12 17:37:00 -07001195 // Allow global effects only on offloaded and mixer threads
1196 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1197 switch (mType) {
1198 case MIXER:
1199 case OFFLOAD:
1200 break;
1201 case DIRECT:
1202 case DUPLICATING:
1203 case RECORD:
1204 default:
Glenn Kastend7dca052015-03-05 16:05:54 -08001205 ALOGW("createEffect_l() Cannot add global effect %s on thread %s",
1206 desc->name, mThreadName);
Eric Laurent5baf2af2013-09-12 17:37:00 -07001207 lStatus = BAD_VALUE;
1208 goto Exit;
1209 }
Eric Laurent81784c32012-11-19 14:55:58 -08001210 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07001211
Eric Laurent81784c32012-11-19 14:55:58 -08001212 // Only Pre processor effects are allowed on input threads and only on input threads
1213 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
1214 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
1215 desc->name, desc->flags, mType);
1216 lStatus = BAD_VALUE;
1217 goto Exit;
1218 }
1219
1220 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1221
1222 { // scope for mLock
1223 Mutex::Autolock _l(mLock);
1224
1225 // check for existing effect chain with the requested audio session
1226 chain = getEffectChain_l(sessionId);
1227 if (chain == 0) {
1228 // create a new chain for this session
1229 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1230 chain = new EffectChain(this, sessionId);
1231 addEffectChain_l(chain);
1232 chain->setStrategy(getStrategyForSession_l(sessionId));
1233 chainCreated = true;
1234 } else {
1235 effect = chain->getEffectFromDesc_l(desc);
1236 }
1237
1238 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1239
1240 if (effect == 0) {
1241 int id = mAudioFlinger->nextUniqueId();
1242 // Check CPU and memory usage
1243 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
1244 if (lStatus != NO_ERROR) {
1245 goto Exit;
1246 }
1247 effectRegistered = true;
1248 // create a new effect module if none present in the chain
1249 effect = new EffectModule(this, chain, desc, id, sessionId);
1250 lStatus = effect->status();
1251 if (lStatus != NO_ERROR) {
1252 goto Exit;
1253 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07001254 effect->setOffloaded(mType == OFFLOAD, mId);
1255
Eric Laurent81784c32012-11-19 14:55:58 -08001256 lStatus = chain->addEffect_l(effect);
1257 if (lStatus != NO_ERROR) {
1258 goto Exit;
1259 }
1260 effectCreated = true;
1261
1262 effect->setDevice(mOutDevice);
1263 effect->setDevice(mInDevice);
1264 effect->setMode(mAudioFlinger->getMode());
1265 effect->setAudioSource(mAudioSource);
1266 }
1267 // create effect handle and connect it to effect module
1268 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001269 lStatus = handle->initCheck();
1270 if (lStatus == OK) {
1271 lStatus = effect->addHandle(handle.get());
1272 }
Eric Laurent81784c32012-11-19 14:55:58 -08001273 if (enabled != NULL) {
1274 *enabled = (int)effect->isEnabled();
1275 }
1276 }
1277
1278Exit:
1279 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1280 Mutex::Autolock _l(mLock);
1281 if (effectCreated) {
1282 chain->removeEffect_l(effect);
1283 }
1284 if (effectRegistered) {
1285 AudioSystem::unregisterEffect(effect->id());
1286 }
1287 if (chainCreated) {
1288 removeEffectChain_l(chain);
1289 }
1290 handle.clear();
1291 }
1292
Glenn Kasten9156ef32013-08-06 15:39:08 -07001293 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001294 return handle;
1295}
1296
1297sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
1298{
1299 Mutex::Autolock _l(mLock);
1300 return getEffect_l(sessionId, effectId);
1301}
1302
1303sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
1304{
1305 sp<EffectChain> chain = getEffectChain_l(sessionId);
1306 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1307}
1308
1309// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1310// PlaybackThread::mLock held
1311status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1312{
1313 // check for existing effect chain with the requested audio session
1314 int sessionId = effect->sessionId();
1315 sp<EffectChain> chain = getEffectChain_l(sessionId);
1316 bool chainCreated = false;
1317
Eric Laurent5baf2af2013-09-12 17:37:00 -07001318 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
1319 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
1320 this, effect->desc().name, effect->desc().flags);
1321
Eric Laurent81784c32012-11-19 14:55:58 -08001322 if (chain == 0) {
1323 // create a new chain for this session
1324 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1325 chain = new EffectChain(this, sessionId);
1326 addEffectChain_l(chain);
1327 chain->setStrategy(getStrategyForSession_l(sessionId));
1328 chainCreated = true;
1329 }
1330 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1331
1332 if (chain->getEffectFromId_l(effect->id()) != 0) {
1333 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1334 this, effect->desc().name, chain.get());
1335 return BAD_VALUE;
1336 }
1337
Eric Laurent5baf2af2013-09-12 17:37:00 -07001338 effect->setOffloaded(mType == OFFLOAD, mId);
1339
Eric Laurent81784c32012-11-19 14:55:58 -08001340 status_t status = chain->addEffect_l(effect);
1341 if (status != NO_ERROR) {
1342 if (chainCreated) {
1343 removeEffectChain_l(chain);
1344 }
1345 return status;
1346 }
1347
1348 effect->setDevice(mOutDevice);
1349 effect->setDevice(mInDevice);
1350 effect->setMode(mAudioFlinger->getMode());
1351 effect->setAudioSource(mAudioSource);
1352 return NO_ERROR;
1353}
1354
1355void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
1356
1357 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
1358 effect_descriptor_t desc = effect->desc();
1359 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1360 detachAuxEffect_l(effect->id());
1361 }
1362
1363 sp<EffectChain> chain = effect->chain().promote();
1364 if (chain != 0) {
1365 // remove effect chain if removing last effect
1366 if (chain->removeEffect_l(effect) == 0) {
1367 removeEffectChain_l(chain);
1368 }
1369 } else {
1370 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1371 }
1372}
1373
1374void AudioFlinger::ThreadBase::lockEffectChains_l(
1375 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1376{
1377 effectChains = mEffectChains;
1378 for (size_t i = 0; i < mEffectChains.size(); i++) {
1379 mEffectChains[i]->lock();
1380 }
1381}
1382
1383void AudioFlinger::ThreadBase::unlockEffectChains(
1384 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1385{
1386 for (size_t i = 0; i < effectChains.size(); i++) {
1387 effectChains[i]->unlock();
1388 }
1389}
1390
1391sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
1392{
1393 Mutex::Autolock _l(mLock);
1394 return getEffectChain_l(sessionId);
1395}
1396
1397sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const
1398{
1399 size_t size = mEffectChains.size();
1400 for (size_t i = 0; i < size; i++) {
1401 if (mEffectChains[i]->sessionId() == sessionId) {
1402 return mEffectChains[i];
1403 }
1404 }
1405 return 0;
1406}
1407
1408void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1409{
1410 Mutex::Autolock _l(mLock);
1411 size_t size = mEffectChains.size();
1412 for (size_t i = 0; i < size; i++) {
1413 mEffectChains[i]->setMode_l(mode);
1414 }
1415}
1416
Eric Laurent83b88082014-06-20 18:31:16 -07001417void AudioFlinger::ThreadBase::getAudioPortConfig(struct audio_port_config *config)
1418{
1419 config->type = AUDIO_PORT_TYPE_MIX;
1420 config->ext.mix.handle = mId;
1421 config->sample_rate = mSampleRate;
1422 config->format = mFormat;
1423 config->channel_mask = mChannelMask;
1424 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1425 AUDIO_PORT_CONFIG_FORMAT;
1426}
1427
Eric Laurent72e3f392015-05-20 14:43:50 -07001428void AudioFlinger::ThreadBase::systemReady()
1429{
1430 Mutex::Autolock _l(mLock);
1431 if (mSystemReady) {
1432 return;
1433 }
1434 mSystemReady = true;
1435
1436 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1437 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1438 }
1439 mPendingConfigEvents.clear();
1440}
1441
Eric Laurent83b88082014-06-20 18:31:16 -07001442
Eric Laurent81784c32012-11-19 14:55:58 -08001443// ----------------------------------------------------------------------------
1444// Playback
1445// ----------------------------------------------------------------------------
1446
1447AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1448 AudioStreamOut* output,
1449 audio_io_handle_t id,
1450 audio_devices_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07001451 type_t type,
1452 bool systemReady)
1453 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type, systemReady),
Andy Hung2098f272014-02-27 14:00:06 -08001454 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001455 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001456 mMixerBuffer(NULL),
1457 mMixerBufferSize(0),
1458 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1459 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001460 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001461 mEffectBuffer(NULL),
1462 mEffectBufferSize(0),
1463 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1464 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001465 mSuspended(0), mBytesWritten(0),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001466 mActiveTracksGeneration(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001467 // mStreamTypes[] initialized in constructor body
1468 mOutput(output),
1469 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
1470 mMixerStatus(MIXER_IDLE),
1471 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001472 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001473 mBytesRemaining(0),
1474 mCurrentWriteLength(0),
1475 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001476 mWriteAckSequence(0),
1477 mDrainSequence(0),
Eric Laurentede6c3b2013-09-19 14:37:46 -07001478 mSignalPending(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001479 mScreenState(AudioFlinger::mScreenState),
1480 // index 0 is reserved for normal mixer's submix
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001481 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1),
Eric Laurentd1f69b02014-12-15 14:33:13 -08001482 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001483 // mLatchD, mLatchQ,
1484 mLatchDValid(false), mLatchQValid(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001485{
Glenn Kastend7dca052015-03-05 16:05:54 -08001486 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1487 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001488
1489 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1490 // it would be safer to explicitly pass initial masterVolume/masterMute as
1491 // parameter.
1492 //
1493 // If the HAL we are using has support for master volume or master mute,
1494 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1495 // and the mute set to false).
1496 mMasterVolume = audioFlinger->masterVolume_l();
1497 mMasterMute = audioFlinger->masterMute_l();
1498 if (mOutput && mOutput->audioHwDev) {
1499 if (mOutput->audioHwDev->canSetMasterVolume()) {
1500 mMasterVolume = 1.0;
1501 }
1502
1503 if (mOutput->audioHwDev->canSetMasterMute()) {
1504 mMasterMute = false;
1505 }
1506 }
1507
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001508 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001509
Eric Laurent223fd5c2014-11-11 13:43:36 -08001510 // ++ operator does not compile
Glenn Kasten66e46352014-01-16 17:44:23 -08001511 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001512 stream = (audio_stream_type_t) (stream + 1)) {
1513 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1514 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1515 }
Eric Laurent81784c32012-11-19 14:55:58 -08001516}
1517
1518AudioFlinger::PlaybackThread::~PlaybackThread()
1519{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001520 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001521 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001522 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001523 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001524}
1525
1526void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1527{
1528 dumpInternals(fd, args);
1529 dumpTracks(fd, args);
1530 dumpEffectChains(fd, args);
1531}
1532
Glenn Kasten0f11b512014-01-31 16:18:54 -08001533void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001534{
1535 const size_t SIZE = 256;
1536 char buffer[SIZE];
1537 String8 result;
1538
Marco Nelissenb2208842014-02-07 14:00:50 -08001539 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001540 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1541 const stream_type_t *st = &mStreamTypes[i];
1542 if (i > 0) {
1543 result.appendFormat(", ");
1544 }
1545 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1546 if (st->mute) {
1547 result.append("M");
1548 }
1549 }
1550 result.append("\n");
1551 write(fd, result.string(), result.length());
1552 result.clear();
1553
Eric Laurent81784c32012-11-19 14:55:58 -08001554 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1555 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001556 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001557 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001558
1559 size_t numtracks = mTracks.size();
1560 size_t numactive = mActiveTracks.size();
Elliott Hughes87cebad2014-05-22 10:14:43 -07001561 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001562 size_t numactiveseen = 0;
1563 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07001564 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08001565 Track::appendDumpHeader(result);
1566 for (size_t i = 0; i < numtracks; ++i) {
1567 sp<Track> track = mTracks[i];
1568 if (track != 0) {
1569 bool active = mActiveTracks.indexOf(track) >= 0;
1570 if (active) {
1571 numactiveseen++;
1572 }
1573 track->dump(buffer, SIZE, active);
1574 result.append(buffer);
1575 }
1576 }
1577 } else {
1578 result.append("\n");
1579 }
1580 if (numactiveseen != numactive) {
1581 // some tracks in the active list were not in the tracks list
1582 snprintf(buffer, SIZE, " The following tracks are in the active list but"
1583 " not in the track list\n");
1584 result.append(buffer);
1585 Track::appendDumpHeader(result);
1586 for (size_t i = 0; i < numactive; ++i) {
1587 sp<Track> track = mActiveTracks[i].promote();
1588 if (track != 0 && mTracks.indexOf(track) < 0) {
1589 track->dump(buffer, SIZE, true);
1590 result.append(buffer);
1591 }
1592 }
1593 }
1594
1595 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001596}
1597
1598void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1599{
Glenn Kasten97b7b752014-09-28 13:04:24 -07001600 dprintf(fd, "\nOutput thread %p type %d (%s):\n", this, type(), threadTypeToString(type()));
Glenn Kasten44182c22015-03-05 17:12:23 -08001601
1602 dumpBase(fd, args);
1603
Elliott Hughes87cebad2014-05-22 10:14:43 -07001604 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
1605 dprintf(fd, " Last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1606 dprintf(fd, " Total writes: %d\n", mNumWrites);
1607 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1608 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1609 dprintf(fd, " Suspend count: %d\n", mSuspended);
1610 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1611 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1612 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1613 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001614 AudioStreamOut *output = mOutput;
1615 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
1616 String8 flagsAsString = outputFlagsToString(flags);
1617 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n", output, flags, flagsAsString.string());
Eric Laurent81784c32012-11-19 14:55:58 -08001618}
1619
1620// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001621
1622void AudioFlinger::PlaybackThread::onFirstRef()
1623{
Glenn Kastend7dca052015-03-05 16:05:54 -08001624 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001625}
1626
1627// ThreadBase virtuals
1628void AudioFlinger::PlaybackThread::preExit()
1629{
1630 ALOGV(" preExit()");
1631 // FIXME this is using hard-coded strings but in the future, this functionality will be
1632 // converted to use audio HAL extensions required to support tunneling
1633 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1634}
1635
1636// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1637sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1638 const sp<AudioFlinger::Client>& client,
1639 audio_stream_type_t streamType,
1640 uint32_t sampleRate,
1641 audio_format_t format,
1642 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001643 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001644 const sp<IMemory>& sharedBuffer,
1645 int sessionId,
1646 IAudioFlinger::track_flags_t *flags,
1647 pid_t tid,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001648 int uid,
Eric Laurent81784c32012-11-19 14:55:58 -08001649 status_t *status)
1650{
Glenn Kasten74935e42013-12-19 08:56:45 -08001651 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001652 sp<Track> track;
1653 status_t lStatus;
1654
1655 bool isTimed = (*flags & IAudioFlinger::TRACK_TIMED) != 0;
1656
1657 // client expresses a preference for FAST, but we get the final say
1658 if (*flags & IAudioFlinger::TRACK_FAST) {
1659 if (
1660 // not timed
1661 (!isTimed) &&
1662 // either of these use cases:
1663 (
1664 // use case 1: shared buffer with any frame count
1665 (
1666 (sharedBuffer != 0)
1667 ) ||
Glenn Kasten1dfe2f92015-03-09 12:03:14 -07001668 // use case 2: frame count is default or at least as large as HAL
Eric Laurent81784c32012-11-19 14:55:58 -08001669 (
Glenn Kasten1dfe2f92015-03-09 12:03:14 -07001670 // we formerly checked for a callback handler (non-0 tid),
1671 // but that is no longer required for TRANSFER_OBTAIN mode
Eric Laurent81784c32012-11-19 14:55:58 -08001672 ((frameCount == 0) ||
Glenn Kastenb5fed682013-12-03 09:06:43 -08001673 (frameCount >= mFrameCount))
Eric Laurent81784c32012-11-19 14:55:58 -08001674 )
1675 ) &&
1676 // PCM data
1677 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07001678 // TODO: extract as a data library function that checks that a computationally
1679 // expensive downmixer is not required: isFastOutputChannelConversion()
Andy Hung9a592762014-07-21 21:56:01 -07001680 (channelMask == mChannelMask ||
Andy Hung1f439e12015-05-19 12:57:41 -07001681 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
1682 (channelMask == AUDIO_CHANNEL_OUT_MONO
1683 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001684 // hardware sample rate
1685 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001686 // normal mixer has an associated fast mixer
1687 hasFastMixer() &&
1688 // there are sufficient fast track slots available
1689 (mFastTrackAvailMask != 0)
1690 // FIXME test that MixerThread for this fast track has a capable output HAL
1691 // FIXME add a permission test also?
1692 ) {
1693 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1694 if (frameCount == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001695 // read the fast track multiplier property the first time it is needed
1696 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1697 if (ok != 0) {
1698 ALOGE("%s pthread_once failed: %d", __func__, ok);
1699 }
1700 frameCount = mFrameCount * sFastTrackMultiplier;
Eric Laurent81784c32012-11-19 14:55:58 -08001701 }
1702 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
1703 frameCount, mFrameCount);
1704 } else {
1705 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
Andy Hung6146c082014-03-18 11:56:15 -07001706 "mFrameCount=%d format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
1707 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001708 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Andy Hung6146c082014-03-18 11:56:15 -07001709 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001710 audio_is_linear_pcm(format),
1711 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
1712 *flags &= ~IAudioFlinger::TRACK_FAST;
Andy Hung0e48d252015-01-26 11:43:15 -08001713 }
1714 }
1715 // For normal PCM streaming tracks, update minimum frame count.
1716 // For compatibility with AudioTrack calculation, buffer depth is forced
1717 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1718 // This is probably too conservative, but legacy application code may depend on it.
1719 // If you change this calculation, also review the start threshold which is related.
1720 if (!(*flags & IAudioFlinger::TRACK_FAST)
1721 && audio_is_linear_pcm(format) && sharedBuffer == 0) {
Andy Hung8edb8dc2015-03-26 19:13:55 -07001722 // this must match AudioTrack.cpp calculateMinFrameCount().
1723 // TODO: Move to a common library
Eric Laurent81784c32012-11-19 14:55:58 -08001724 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1725 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1726 if (minBufCount < 2) {
1727 minBufCount = 2;
1728 }
Andy Hung8edb8dc2015-03-26 19:13:55 -07001729 // For normal mixing tracks, if speed is > 1.0f (normal), AudioTrack
1730 // or the client should compute and pass in a larger buffer request.
Andy Hung0e48d252015-01-26 11:43:15 -08001731 size_t minFrameCount =
Andy Hung8edb8dc2015-03-26 19:13:55 -07001732 minBufCount * sourceFramesNeededWithTimestretch(
1733 sampleRate, mNormalFrameCount,
1734 mSampleRate, AUDIO_TIMESTRETCH_SPEED_NORMAL /*speed*/);
Andy Hung0e48d252015-01-26 11:43:15 -08001735 if (frameCount < minFrameCount) { // including frameCount == 0
Eric Laurent81784c32012-11-19 14:55:58 -08001736 frameCount = minFrameCount;
1737 }
Eric Laurent81784c32012-11-19 14:55:58 -08001738 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001739 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001740
Glenn Kastenc3df8382014-03-13 15:05:25 -07001741 switch (mType) {
1742
1743 case DIRECT:
Glenn Kasten993fa062014-05-02 11:14:34 -07001744 if (audio_is_linear_pcm(format)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001745 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001746 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1747 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001748 sampleRate, format, channelMask, mOutput, mFormat);
1749 lStatus = BAD_VALUE;
1750 goto Exit;
1751 }
1752 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001753 break;
1754
1755 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001756 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001757 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1758 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001759 sampleRate, format, channelMask, mOutput, mFormat);
1760 lStatus = BAD_VALUE;
1761 goto Exit;
1762 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001763 break;
1764
1765 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07001766 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001767 ALOGE("createTrack_l() Bad parameter: format %#x \""
1768 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001769 format, mOutput, mFormat);
1770 lStatus = BAD_VALUE;
1771 goto Exit;
1772 }
Andy Hungcd044842014-08-07 11:04:34 -07001773 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08001774 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1775 lStatus = BAD_VALUE;
1776 goto Exit;
1777 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001778 break;
1779
Eric Laurent81784c32012-11-19 14:55:58 -08001780 }
1781
1782 lStatus = initCheck();
1783 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07001784 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08001785 goto Exit;
1786 }
1787
1788 { // scope for mLock
1789 Mutex::Autolock _l(mLock);
1790
1791 // all tracks in same audio session must share the same routing strategy otherwise
1792 // conflicts will happen when tracks are moved from one output to another by audio policy
1793 // manager
1794 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1795 for (size_t i = 0; i < mTracks.size(); ++i) {
1796 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07001797 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001798 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1799 if (sessionId == t->sessionId() && strategy != actual) {
1800 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1801 strategy, actual);
1802 lStatus = BAD_VALUE;
1803 goto Exit;
1804 }
1805 }
1806 }
1807
1808 if (!isTimed) {
1809 track = new Track(this, client, streamType, sampleRate, format,
Eric Laurent83b88082014-06-20 18:31:16 -07001810 channelMask, frameCount, NULL, sharedBuffer,
1811 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08001812 } else {
1813 track = TimedTrack::create(this, client, streamType, sampleRate, format,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001814 channelMask, frameCount, sharedBuffer, sessionId, uid);
Eric Laurent81784c32012-11-19 14:55:58 -08001815 }
Glenn Kasten03003332013-08-06 15:40:54 -07001816
1817 // new Track always returns non-NULL,
1818 // but TimedTrack::create() is a factory that could fail by returning NULL
1819 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
1820 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08001821 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001822 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08001823 goto Exit;
1824 }
1825 mTracks.add(track);
1826
1827 sp<EffectChain> chain = getEffectChain_l(sessionId);
1828 if (chain != 0) {
1829 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1830 track->setMainBuffer(chain->inBuffer());
1831 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1832 chain->incTrackCnt();
1833 }
1834
1835 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1836 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1837 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1838 // so ask activity manager to do this on our behalf
1839 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1840 }
1841 }
1842
1843 lStatus = NO_ERROR;
1844
1845Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001846 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001847 return track;
1848}
1849
1850uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1851{
1852 return latency;
1853}
1854
1855uint32_t AudioFlinger::PlaybackThread::latency() const
1856{
1857 Mutex::Autolock _l(mLock);
1858 return latency_l();
1859}
1860uint32_t AudioFlinger::PlaybackThread::latency_l() const
1861{
1862 if (initCheck() == NO_ERROR) {
1863 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
1864 } else {
1865 return 0;
1866 }
1867}
1868
1869void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1870{
1871 Mutex::Autolock _l(mLock);
1872 // Don't apply master volume in SW if our HAL can do it for us.
1873 if (mOutput && mOutput->audioHwDev &&
1874 mOutput->audioHwDev->canSetMasterVolume()) {
1875 mMasterVolume = 1.0;
1876 } else {
1877 mMasterVolume = value;
1878 }
1879}
1880
1881void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1882{
1883 Mutex::Autolock _l(mLock);
1884 // Don't apply master mute in SW if our HAL can do it for us.
1885 if (mOutput && mOutput->audioHwDev &&
1886 mOutput->audioHwDev->canSetMasterMute()) {
1887 mMasterMute = false;
1888 } else {
1889 mMasterMute = muted;
1890 }
1891}
1892
1893void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
1894{
1895 Mutex::Autolock _l(mLock);
1896 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001897 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001898}
1899
1900void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
1901{
1902 Mutex::Autolock _l(mLock);
1903 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001904 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001905}
1906
1907float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
1908{
1909 Mutex::Autolock _l(mLock);
1910 return mStreamTypes[stream].volume;
1911}
1912
1913// addTrack_l() must be called with ThreadBase::mLock held
1914status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1915{
1916 status_t status = ALREADY_EXISTS;
1917
1918 // set retry count for buffer fill
1919 track->mRetryCount = kMaxTrackStartupRetries;
1920 if (mActiveTracks.indexOf(track) < 0) {
1921 // the track is newly added, make sure it fills up all its
1922 // buffers before playing. This is to ensure the client will
1923 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07001924 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001925 TrackBase::track_state state = track->mState;
1926 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08001927 status = AudioSystem::startOutput(mId, track->streamType(),
1928 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001929 mLock.lock();
1930 // abort track was stopped/paused while we released the lock
1931 if (state != track->mState) {
1932 if (status == NO_ERROR) {
1933 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08001934 AudioSystem::stopOutput(mId, track->streamType(),
1935 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001936 mLock.lock();
1937 }
1938 return INVALID_OPERATION;
1939 }
1940 // abort if start is rejected by audio policy manager
1941 if (status != NO_ERROR) {
1942 return PERMISSION_DENIED;
1943 }
1944#ifdef ADD_BATTERY_DATA
1945 // to track the speaker usage
1946 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
1947#endif
1948 }
1949
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001950 track->mFillingUpStatus = track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent81784c32012-11-19 14:55:58 -08001951 track->mResetDone = false;
1952 track->mPresentationCompleteFrames = 0;
1953 mActiveTracks.add(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001954 mWakeLockUids.add(track->uid());
1955 mActiveTracksGeneration++;
Eric Laurentfd477972013-10-25 18:10:40 -07001956 mLatestActiveTrack = track;
Eric Laurentd0107bc2013-06-11 14:38:48 -07001957 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1958 if (chain != 0) {
1959 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
1960 track->sessionId());
1961 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08001962 }
1963
1964 status = NO_ERROR;
1965 }
1966
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08001967 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001968 return status;
1969}
1970
Eric Laurentbfb1b832013-01-07 09:53:42 -08001971bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08001972{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001973 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08001974 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001975 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
1976 track->mState = TrackBase::STOPPED;
1977 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08001978 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07001979 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001980 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08001981 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001982
1983 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08001984}
1985
1986void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1987{
1988 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
1989 mTracks.remove(track);
1990 deleteTrackName_l(track->name());
1991 // redundant as track is about to be destroyed, for dumpsys only
1992 track->mName = -1;
1993 if (track->isFastTrack()) {
1994 int index = track->mFastIndex;
1995 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
1996 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1997 mFastTrackAvailMask |= 1 << index;
1998 // redundant as track is about to be destroyed, for dumpsys only
1999 track->mFastIndex = -1;
2000 }
2001 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2002 if (chain != 0) {
2003 chain->decTrackCnt();
2004 }
2005}
2006
Eric Laurentede6c3b2013-09-19 14:37:46 -07002007void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002008{
2009 // Thread could be blocked waiting for async
2010 // so signal it to handle state changes immediately
2011 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
2012 // be lost so we also flag to prevent it blocking on mWaitWorkCV
2013 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002014 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002015}
2016
Eric Laurent81784c32012-11-19 14:55:58 -08002017String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2018{
Eric Laurent81784c32012-11-19 14:55:58 -08002019 Mutex::Autolock _l(mLock);
2020 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07002021 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002022 }
2023
Glenn Kastend8ea6992013-07-16 14:17:15 -07002024 char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
2025 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08002026 free(s);
2027 return out_s8;
2028}
2029
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002030void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002031 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2032 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002033
Eric Laurent73e26b62015-04-27 16:55:58 -07002034 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002035
2036 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002037 case AUDIO_OUTPUT_OPENED:
2038 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002039 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002040 desc->mChannelMask = mChannelMask;
2041 desc->mSamplingRate = mSampleRate;
2042 desc->mFormat = mFormat;
2043 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002044 // AudioFlinger::frameCount(audio_io_handle_t)
Eric Laurent73e26b62015-04-27 16:55:58 -07002045 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002046 break;
2047
Eric Laurent73e26b62015-04-27 16:55:58 -07002048 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002049 default:
2050 break;
2051 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002052 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002053}
2054
Eric Laurentbfb1b832013-01-07 09:53:42 -08002055void AudioFlinger::PlaybackThread::writeCallback()
2056{
2057 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002058 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002059}
2060
2061void AudioFlinger::PlaybackThread::drainCallback()
2062{
2063 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002064 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002065}
2066
Eric Laurent3b4529e2013-09-05 18:09:19 -07002067void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002068{
2069 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002070 // reject out of sequence requests
2071 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2072 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002073 mWaitWorkCV.signal();
2074 }
2075}
2076
Eric Laurent3b4529e2013-09-05 18:09:19 -07002077void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002078{
2079 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002080 // reject out of sequence requests
2081 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
2082 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002083 mWaitWorkCV.signal();
2084 }
2085}
2086
2087// static
2088int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
Glenn Kasten0f11b512014-01-31 16:18:54 -08002089 void *param __unused,
Eric Laurentbfb1b832013-01-07 09:53:42 -08002090 void *cookie)
2091{
2092 AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
2093 ALOGV("asyncCallback() event %d", event);
2094 switch (event) {
2095 case STREAM_CBK_EVENT_WRITE_READY:
2096 me->writeCallback();
2097 break;
2098 case STREAM_CBK_EVENT_DRAIN_READY:
2099 me->drainCallback();
2100 break;
2101 default:
2102 ALOGW("asyncCallback() unknown event %d", event);
2103 break;
2104 }
2105 return 0;
2106}
2107
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002108void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002109{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002110 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Phil Burkca5e6142015-07-14 09:42:29 -07002111 mSampleRate = mOutput->getSampleRate();
2112 mChannelMask = mOutput->getChannelMask();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002113 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002114 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002115 }
Andy Hung9a592762014-07-21 21:56:01 -07002116 if ((mType == MIXER || mType == DUPLICATING)
2117 && !isValidPcmSinkChannelMask(mChannelMask)) {
2118 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2119 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002120 }
Andy Hunge5412692014-05-16 11:25:07 -07002121 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002122
2123 // Get actual HAL format.
Andy Hung463be252014-07-10 16:56:07 -07002124 mHALFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Phil Burkca5e6142015-07-14 09:42:29 -07002125 // Get format from the shim, which will be different than the HAL format
2126 // if playing compressed audio over HDMI passthrough.
2127 mFormat = mOutput->getFormat();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002128 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002129 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002130 }
Andy Hung6146c082014-03-18 11:56:15 -07002131 if ((mType == MIXER || mType == DUPLICATING)
2132 && !isValidPcmSinkFormat(mFormat)) {
2133 LOG_FATAL("HAL format %#x not supported for mixed output",
2134 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002135 }
Phil Burk062e67a2015-02-11 13:40:50 -08002136 mFrameSize = mOutput->getFrameSize();
Glenn Kasten70949c42013-08-06 07:40:12 -07002137 mBufferSize = mOutput->stream->common.get_buffer_size(&mOutput->stream->common);
2138 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002139 if (mFrameCount & 15) {
2140 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
2141 mFrameCount);
2142 }
2143
Eric Laurentbfb1b832013-01-07 09:53:42 -08002144 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
2145 (mOutput->stream->set_callback != NULL)) {
2146 if (mOutput->stream->set_callback(mOutput->stream,
2147 AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
2148 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002149 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002150 }
2151 }
2152
Eric Laurentd1f69b02014-12-15 14:33:13 -08002153 mHwSupportsPause = false;
2154 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
2155 if (mOutput->stream->pause != NULL) {
2156 if (mOutput->stream->resume != NULL) {
2157 mHwSupportsPause = true;
2158 } else {
2159 ALOGW("direct output implements pause but not resume");
2160 }
2161 } else if (mOutput->stream->resume != NULL) {
2162 ALOGW("direct output implements resume but not pause");
2163 }
2164 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002165 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2166 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2167 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002168
Andy Hungfbfc3952015-01-15 13:33:51 -08002169 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2170 // For best precision, we use float instead of the associated output
2171 // device format (typically PCM 16 bit).
2172
2173 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2174 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2175 mBufferSize = mFrameSize * mFrameCount;
2176
2177 // TODO: We currently use the associated output device channel mask and sample rate.
2178 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2179 // (if a valid mask) to avoid premature downmix.
2180 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2181 // instead of the output device sample rate to avoid loss of high frequency information.
2182 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2183 }
2184
Andy Hung09a50072014-02-27 14:30:47 -08002185 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002186 double multiplier = 1.0;
2187 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2188 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002189 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2190 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Eric Laurent81784c32012-11-19 14:55:58 -08002191 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2192 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2193 maxNormalFrameCount = maxNormalFrameCount & ~15;
2194 if (maxNormalFrameCount < minNormalFrameCount) {
2195 maxNormalFrameCount = minNormalFrameCount;
2196 }
2197 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2198 if (multiplier <= 1.0) {
2199 multiplier = 1.0;
2200 } else if (multiplier <= 2.0) {
2201 if (2 * mFrameCount <= maxNormalFrameCount) {
2202 multiplier = 2.0;
2203 } else {
2204 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2205 }
2206 } else {
2207 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
Andy Hung09a50072014-02-27 14:30:47 -08002208 // 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 -08002209 // track, but we sometimes have to do this to satisfy the maximum frame count
2210 // constraint)
2211 // FIXME this rounding up should not be done if no HAL SRC
2212 uint32_t truncMult = (uint32_t) multiplier;
2213 if ((truncMult & 1)) {
2214 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
2215 ++truncMult;
2216 }
2217 }
2218 multiplier = (double) truncMult;
2219 }
2220 }
2221 mNormalFrameCount = multiplier * mFrameCount;
2222 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002223 if (mType == MIXER || mType == DUPLICATING) {
2224 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2225 }
Andy Hung09a50072014-02-27 14:30:47 -08002226 ALOGI("HAL output buffer size %u frames, normal sink buffer size %u frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002227 mNormalFrameCount);
2228
Andy Hung08fb1742015-05-31 23:22:10 -07002229 // Check if we want to throttle the processing to no more than 2x normal rate
2230 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002231 mThreadThrottleTimeMs = 0;
2232 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002233 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2234
Andy Hung010a1a12014-03-13 13:57:33 -07002235 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2236 // Originally this was int16_t[] array, need to remove legacy implications.
2237 free(mSinkBuffer);
2238 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002239 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2240 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2241 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002242 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002243
Andy Hung69aed5f2014-02-25 17:24:40 -08002244 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2245 // drives the output.
2246 free(mMixerBuffer);
2247 mMixerBuffer = NULL;
2248 if (mMixerBufferEnabled) {
2249 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2250 mMixerBufferSize = mNormalFrameCount * mChannelCount
2251 * audio_bytes_per_sample(mMixerBufferFormat);
2252 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2253 }
Andy Hung98ef9782014-03-04 14:46:50 -08002254 free(mEffectBuffer);
2255 mEffectBuffer = NULL;
2256 if (mEffectBufferEnabled) {
2257 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
2258 mEffectBufferSize = mNormalFrameCount * mChannelCount
2259 * audio_bytes_per_sample(mEffectBufferFormat);
2260 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2261 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002262
Eric Laurent81784c32012-11-19 14:55:58 -08002263 // force reconfiguration of effect chains and engines to take new buffer size and audio
2264 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002265 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002266 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2267 // matter.
2268 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2269 Vector< sp<EffectChain> > effectChains = mEffectChains;
2270 for (size_t i = 0; i < effectChains.size(); i ++) {
2271 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2272 }
2273}
2274
2275
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002276status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002277{
2278 if (halFrames == NULL || dspFrames == NULL) {
2279 return BAD_VALUE;
2280 }
2281 Mutex::Autolock _l(mLock);
2282 if (initCheck() != NO_ERROR) {
2283 return INVALID_OPERATION;
2284 }
2285 size_t framesWritten = mBytesWritten / mFrameSize;
2286 *halFrames = framesWritten;
2287
2288 if (isSuspended()) {
2289 // return an estimation of rendered frames when the output is suspended
2290 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
2291 *dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0;
2292 return NO_ERROR;
2293 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002294 status_t status;
2295 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002296 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002297 *dspFrames = (size_t)frames;
2298 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002299 }
2300}
2301
2302uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
2303{
2304 Mutex::Autolock _l(mLock);
2305 uint32_t result = 0;
2306 if (getEffectChain_l(sessionId) != 0) {
2307 result = EFFECT_SESSION;
2308 }
2309
2310 for (size_t i = 0; i < mTracks.size(); ++i) {
2311 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002312 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002313 result |= TRACK_SESSION;
2314 break;
2315 }
2316 }
2317
2318 return result;
2319}
2320
2321uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
2322{
2323 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2324 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2325 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2326 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2327 }
2328 for (size_t i = 0; i < mTracks.size(); i++) {
2329 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002330 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002331 return AudioSystem::getStrategyForStream(track->streamType());
2332 }
2333 }
2334 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2335}
2336
2337
Phil Burk062e67a2015-02-11 13:40:50 -08002338AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002339{
2340 Mutex::Autolock _l(mLock);
2341 return mOutput;
2342}
2343
Phil Burk062e67a2015-02-11 13:40:50 -08002344AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002345{
2346 Mutex::Autolock _l(mLock);
2347 AudioStreamOut *output = mOutput;
2348 mOutput = NULL;
2349 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2350 // must push a NULL and wait for ack
2351 mOutputSink.clear();
2352 mPipeSink.clear();
2353 mNormalSink.clear();
2354 return output;
2355}
2356
2357// this method must always be called either with ThreadBase mLock held or inside the thread loop
2358audio_stream_t* AudioFlinger::PlaybackThread::stream() const
2359{
2360 if (mOutput == NULL) {
2361 return NULL;
2362 }
2363 return &mOutput->stream->common;
2364}
2365
2366uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2367{
2368 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2369}
2370
2371status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2372{
2373 if (!isValidSyncEvent(event)) {
2374 return BAD_VALUE;
2375 }
2376
2377 Mutex::Autolock _l(mLock);
2378
2379 for (size_t i = 0; i < mTracks.size(); ++i) {
2380 sp<Track> track = mTracks[i];
2381 if (event->triggerSession() == track->sessionId()) {
2382 (void) track->setSyncEvent(event);
2383 return NO_ERROR;
2384 }
2385 }
2386
2387 return NAME_NOT_FOUND;
2388}
2389
2390bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2391{
2392 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2393}
2394
2395void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2396 const Vector< sp<Track> >& tracksToRemove)
2397{
2398 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002399 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002400 for (size_t i = 0 ; i < count ; i++) {
2401 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002402 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002403 AudioSystem::stopOutput(mId, track->streamType(),
2404 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002405#ifdef ADD_BATTERY_DATA
2406 // to track the speaker usage
2407 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2408#endif
2409 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002410 AudioSystem::releaseOutput(mId, track->streamType(),
2411 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002412 }
Eric Laurent81784c32012-11-19 14:55:58 -08002413 }
2414 }
2415 }
Eric Laurent81784c32012-11-19 14:55:58 -08002416}
2417
2418void AudioFlinger::PlaybackThread::checkSilentMode_l()
2419{
2420 if (!mMasterMute) {
2421 char value[PROPERTY_VALUE_MAX];
2422 if (property_get("ro.audio.silent", value, "0") > 0) {
2423 char *endptr;
2424 unsigned long ul = strtoul(value, &endptr, 0);
2425 if (*endptr == '\0' && ul != 0) {
2426 ALOGD("Silence is golden");
2427 // The setprop command will not allow a property to be changed after
2428 // the first time it is set, so we don't have to worry about un-muting.
2429 setMasterMute_l(true);
2430 }
2431 }
2432 }
2433}
2434
2435// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002436ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002437{
2438 // FIXME rewrite to reduce number of system calls
2439 mLastWriteTime = systemTime();
2440 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002441 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002442 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002443
2444 // If an NBAIO sink is present, use it to write the normal mixer's submix
2445 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002446
Andy Hung010a1a12014-03-13 13:57:33 -07002447 const size_t count = mBytesRemaining / mFrameSize;
2448
Simon Wilson2d590962012-11-29 15:18:50 -08002449 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002450 // update the setpoint when AudioFlinger::mScreenState changes
2451 uint32_t screenState = AudioFlinger::mScreenState;
2452 if (screenState != mScreenState) {
2453 mScreenState = screenState;
2454 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2455 if (pipe != NULL) {
2456 pipe->setAvgFrames((mScreenState & 1) ?
2457 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2458 }
2459 }
Andy Hung010a1a12014-03-13 13:57:33 -07002460 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002461 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002462 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002463 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002464 } else {
2465 bytesWritten = framesWritten;
2466 }
Glenn Kastenefaa7ab2014-08-20 08:48:54 -07002467 mLatchDValid = false;
Glenn Kasten767094d2013-08-23 13:51:43 -07002468 status_t status = mNormalSink->getTimestamp(mLatchD.mTimestamp);
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002469 if (status == NO_ERROR) {
2470 size_t totalFramesWritten = mNormalSink->framesWritten();
2471 if (totalFramesWritten >= mLatchD.mTimestamp.mPosition) {
2472 mLatchD.mUnpresentedFrames = totalFramesWritten - mLatchD.mTimestamp.mPosition;
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002473 // mLatchD.mFramesReleased is set immediately before D is clocked into Q
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002474 mLatchDValid = true;
2475 }
2476 }
Eric Laurent81784c32012-11-19 14:55:58 -08002477 // otherwise use the HAL / AudioStreamOut directly
2478 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002479 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002480
Eric Laurentbfb1b832013-01-07 09:53:42 -08002481 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002482 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2483 mWriteAckSequence += 2;
2484 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002485 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002486 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002487 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002488 // FIXME We should have an implementation of timestamps for direct output threads.
2489 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002490 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002491 if (mUseAsyncWrite &&
2492 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2493 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002494 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002495 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002496 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002497 }
Eric Laurent81784c32012-11-19 14:55:58 -08002498 }
2499
Eric Laurent81784c32012-11-19 14:55:58 -08002500 mNumWrites++;
2501 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002502 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002503 return bytesWritten;
2504}
2505
2506void AudioFlinger::PlaybackThread::threadLoop_drain()
2507{
2508 if (mOutput->stream->drain) {
2509 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2510 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002511 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2512 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002513 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002514 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002515 }
2516 mOutput->stream->drain(mOutput->stream,
2517 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
2518 : AUDIO_DRAIN_ALL);
2519 }
2520}
2521
2522void AudioFlinger::PlaybackThread::threadLoop_exit()
2523{
Eric Laurent275e8e92014-11-30 15:14:47 -08002524 {
2525 Mutex::Autolock _l(mLock);
2526 for (size_t i = 0; i < mTracks.size(); i++) {
2527 sp<Track> track = mTracks[i];
2528 track->invalidate();
2529 }
2530 }
Eric Laurent81784c32012-11-19 14:55:58 -08002531}
2532
2533/*
2534The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002535 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002536 - mActiveSleepTimeUs from activeSleepTimeUs()
2537 - mIdleSleepTimeUs from idleSleepTimeUs()
2538 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only)
Eric Laurent81784c32012-11-19 14:55:58 -08002539 - maxPeriod from frame count and sample rate (MIXER only)
2540
2541The parameters that affect these derived values are:
2542 - frame count
2543 - frame size
2544 - sample rate
2545 - device type: A2DP or not
2546 - device latency
2547 - format: PCM or not
2548 - active sleep time
2549 - idle sleep time
2550*/
2551
2552void AudioFlinger::PlaybackThread::cacheParameters_l()
2553{
Andy Hung25c2dac2014-02-27 14:56:00 -08002554 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002555 mActiveSleepTimeUs = activeSleepTimeUs();
2556 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent81784c32012-11-19 14:55:58 -08002557}
2558
2559void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2560{
Glenn Kasten7c027242012-12-26 14:43:16 -08002561 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurent81784c32012-11-19 14:55:58 -08002562 this, streamType, mTracks.size());
2563 Mutex::Autolock _l(mLock);
2564
2565 size_t size = mTracks.size();
2566 for (size_t i = 0; i < size; i++) {
2567 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07002568 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002569 t->invalidate();
Eric Laurent81784c32012-11-19 14:55:58 -08002570 }
2571 }
2572}
2573
2574status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2575{
2576 int session = chain->sessionId();
Andy Hung010a1a12014-03-13 13:57:33 -07002577 int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled
2578 ? mEffectBuffer : mSinkBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002579 bool ownsBuffer = false;
2580
2581 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
2582 if (session > 0) {
2583 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002584 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002585 if (mType != DIRECT) {
2586 size_t numSamples = mNormalFrameCount * mChannelCount;
2587 buffer = new int16_t[numSamples];
2588 memset(buffer, 0, numSamples * sizeof(int16_t));
2589 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2590 ownsBuffer = true;
2591 }
2592
2593 // Attach all tracks with same session ID to this chain.
2594 for (size_t i = 0; i < mTracks.size(); ++i) {
2595 sp<Track> track = mTracks[i];
2596 if (session == track->sessionId()) {
2597 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2598 buffer);
2599 track->setMainBuffer(buffer);
2600 chain->incTrackCnt();
2601 }
2602 }
2603
2604 // indicate all active tracks in the chain
2605 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2606 sp<Track> track = mActiveTracks[i].promote();
2607 if (track == 0) {
2608 continue;
2609 }
2610 if (session == track->sessionId()) {
2611 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2612 chain->incActiveTrackCnt();
2613 }
2614 }
2615 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002616 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08002617 chain->setInBuffer(buffer, ownsBuffer);
Andy Hung010a1a12014-03-13 13:57:33 -07002618 chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled
2619 ? mEffectBuffer : mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002620 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
2621 // chains list in order to be processed last as it contains output stage effects
2622 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2623 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
2624 // after track specific effects and before output stage
2625 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
2626 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
2627 // Effect chain for other sessions are inserted at beginning of effect
2628 // chains list to be processed before output mix effects. Relative order between other
2629 // sessions is not important
2630 size_t size = mEffectChains.size();
2631 size_t i = 0;
2632 for (i = 0; i < size; i++) {
2633 if (mEffectChains[i]->sessionId() < session) {
2634 break;
2635 }
2636 }
2637 mEffectChains.insertAt(chain, i);
2638 checkSuspendOnAddEffectChain_l(chain);
2639
2640 return NO_ERROR;
2641}
2642
2643size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2644{
2645 int session = chain->sessionId();
2646
2647 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2648
2649 for (size_t i = 0; i < mEffectChains.size(); i++) {
2650 if (chain == mEffectChains[i]) {
2651 mEffectChains.removeAt(i);
2652 // detach all active tracks from the chain
2653 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2654 sp<Track> track = mActiveTracks[i].promote();
2655 if (track == 0) {
2656 continue;
2657 }
2658 if (session == track->sessionId()) {
2659 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2660 chain.get(), session);
2661 chain->decActiveTrackCnt();
2662 }
2663 }
2664
2665 // detach all tracks with same session ID from this chain
2666 for (size_t i = 0; i < mTracks.size(); ++i) {
2667 sp<Track> track = mTracks[i];
2668 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002669 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002670 chain->decTrackCnt();
2671 }
2672 }
2673 break;
2674 }
2675 }
2676 return mEffectChains.size();
2677}
2678
2679status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2680 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2681{
2682 Mutex::Autolock _l(mLock);
2683 return attachAuxEffect_l(track, EffectId);
2684}
2685
2686status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2687 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2688{
2689 status_t status = NO_ERROR;
2690
2691 if (EffectId == 0) {
2692 track->setAuxBuffer(0, NULL);
2693 } else {
2694 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2695 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2696 if (effect != 0) {
2697 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2698 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2699 } else {
2700 status = INVALID_OPERATION;
2701 }
2702 } else {
2703 status = BAD_VALUE;
2704 }
2705 }
2706 return status;
2707}
2708
2709void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2710{
2711 for (size_t i = 0; i < mTracks.size(); ++i) {
2712 sp<Track> track = mTracks[i];
2713 if (track->auxEffectId() == effectId) {
2714 attachAuxEffect_l(track, 0);
2715 }
2716 }
2717}
2718
2719bool AudioFlinger::PlaybackThread::threadLoop()
2720{
2721 Vector< sp<Track> > tracksToRemove;
2722
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002723 mStandbyTimeNs = systemTime();
Eric Laurent81784c32012-11-19 14:55:58 -08002724
2725 // MIXER
2726 nsecs_t lastWarning = 0;
2727
2728 // DUPLICATING
2729 // FIXME could this be made local to while loop?
2730 writeFrames = 0;
2731
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002732 int lastGeneration = 0;
2733
Eric Laurent81784c32012-11-19 14:55:58 -08002734 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002735 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08002736
2737 if (mType == MIXER) {
2738 sleepTimeShift = 0;
2739 }
2740
2741 CpuStats cpuStats;
2742 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2743
2744 acquireWakeLock();
2745
Glenn Kasten9e58b552013-01-18 15:09:48 -08002746 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2747 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2748 // and then that string will be logged at the next convenient opportunity.
2749 const char *logString = NULL;
2750
Eric Laurent664539d2013-09-23 18:24:31 -07002751 checkSilentMode_l();
2752
Eric Laurent81784c32012-11-19 14:55:58 -08002753 while (!exitPending())
2754 {
2755 cpuStats.sample(myName);
2756
2757 Vector< sp<EffectChain> > effectChains;
2758
Eric Laurent81784c32012-11-19 14:55:58 -08002759 { // scope for mLock
2760
2761 Mutex::Autolock _l(mLock);
2762
Eric Laurent021cf962014-05-13 10:18:14 -07002763 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07002764
Glenn Kasten9e58b552013-01-18 15:09:48 -08002765 if (logString != NULL) {
2766 mNBLogWriter->logTimestamp();
2767 mNBLogWriter->log(logString);
2768 logString = NULL;
2769 }
2770
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002771 // Gather the framesReleased counters for all active tracks,
2772 // and latch them atomically with the timestamp.
2773 // FIXME We're using raw pointers as indices. A unique track ID would be a better index.
2774 mLatchD.mFramesReleased.clear();
2775 size_t size = mActiveTracks.size();
2776 for (size_t i = 0; i < size; i++) {
2777 sp<Track> t = mActiveTracks[i].promote();
2778 if (t != 0) {
2779 mLatchD.mFramesReleased.add(t.get(),
2780 t->mAudioTrackServerProxy->framesReleased());
2781 }
2782 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002783 if (mLatchDValid) {
2784 mLatchQ = mLatchD;
2785 mLatchDValid = false;
2786 mLatchQValid = true;
2787 }
2788
Eric Laurent81784c32012-11-19 14:55:58 -08002789 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002790 if (mSignalPending) {
2791 // A signal was raised while we were unlocked
2792 mSignalPending = false;
2793 } else if (waitingAsyncCallback_l()) {
2794 if (exitPending()) {
2795 break;
2796 }
Marco Nelissen078538c2015-05-12 09:17:57 -07002797 bool released = false;
2798 // The following works around a bug in the offload driver. Ideally we would release
2799 // the wake lock every time, but that causes the last offload buffer(s) to be
2800 // dropped while the device is on battery, so we need to hold a wake lock during
2801 // the drain phase.
2802 if (mBytesRemaining && !(mDrainSequence & 1)) {
2803 releaseWakeLock_l();
2804 released = true;
2805 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002806 mWakeLockUids.clear();
2807 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002808 ALOGV("wait async completion");
2809 mWaitWorkCV.wait(mLock);
2810 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07002811 if (released) {
2812 acquireWakeLock_l();
2813 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002814 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
2815 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002816
2817 continue;
2818 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002819 if ((!mActiveTracks.size() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08002820 isSuspended()) {
2821 // put audio hardware into standby after short delay
2822 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002823
2824 threadLoop_standby();
2825
2826 mStandby = true;
2827 }
2828
2829 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2830 // we're about to wait, flush the binder command buffer
2831 IPCThreadState::self()->flushCommands();
2832
2833 clearOutputTracks();
2834
2835 if (exitPending()) {
2836 break;
2837 }
2838
2839 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002840 mWakeLockUids.clear();
2841 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002842 // wait until we have something to do...
2843 ALOGV("%s going to sleep", myName.string());
2844 mWaitWorkCV.wait(mLock);
2845 ALOGV("%s waking up", myName.string());
2846 acquireWakeLock_l();
2847
2848 mMixerStatus = MIXER_IDLE;
2849 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2850 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002851 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002852 checkSilentMode_l();
2853
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002854 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
2855 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08002856 if (mType == MIXER) {
2857 sleepTimeShift = 0;
2858 }
2859
2860 continue;
2861 }
2862 }
Eric Laurent81784c32012-11-19 14:55:58 -08002863 // mMixerStatusIgnoringFastTracks is also updated internally
2864 mMixerStatus = prepareTracks_l(&tracksToRemove);
2865
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002866 // compare with previously applied list
2867 if (lastGeneration != mActiveTracksGeneration) {
2868 // update wakelock
2869 updateWakeLockUids_l(mWakeLockUids);
2870 lastGeneration = mActiveTracksGeneration;
2871 }
2872
Eric Laurent81784c32012-11-19 14:55:58 -08002873 // prevent any changes in effect chain list and in each effect chain
2874 // during mixing and effect process as the audio buffers could be deleted
2875 // or modified if an effect is created or deleted
2876 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002877 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08002878
Eric Laurentbfb1b832013-01-07 09:53:42 -08002879 if (mBytesRemaining == 0) {
2880 mCurrentWriteLength = 0;
2881 if (mMixerStatus == MIXER_TRACKS_READY) {
2882 // threadLoop_mix() sets mCurrentWriteLength
2883 threadLoop_mix();
2884 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
2885 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002886 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08002887 // must be written to HAL
2888 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002889 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08002890 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002891 }
2892 }
Andy Hung98ef9782014-03-04 14:46:50 -08002893 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002894 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08002895 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
2896 // or mSinkBuffer (if there are no effects).
2897 //
2898 // This is done pre-effects computation; if effects change to
2899 // support higher precision, this needs to move.
2900 //
2901 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002902 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08002903 if (mMixerBufferValid) {
2904 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
2905 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
2906
2907 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
2908 mNormalFrameCount * mChannelCount);
2909 }
2910
Eric Laurentbfb1b832013-01-07 09:53:42 -08002911 mBytesRemaining = mCurrentWriteLength;
2912 if (isSuspended()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002913 mSleepTimeUs = suspendSleepTimeUs();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002914 // simulate write to HAL when suspended
Andy Hung25c2dac2014-02-27 14:56:00 -08002915 mBytesWritten += mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002916 mBytesRemaining = 0;
2917 }
Eric Laurent81784c32012-11-19 14:55:58 -08002918
Eric Laurentbfb1b832013-01-07 09:53:42 -08002919 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002920 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002921 for (size_t i = 0; i < effectChains.size(); i ++) {
2922 effectChains[i]->process_l();
2923 }
Eric Laurent81784c32012-11-19 14:55:58 -08002924 }
2925 }
Eric Laurent59fe0102013-09-27 18:48:26 -07002926 // Process effect chains for offloaded thread even if no audio
2927 // was read from audio track: process only updates effect state
2928 // and thus does have to be synchronized with audio writes but may have
2929 // to be called while waiting for async write callback
2930 if (mType == OFFLOAD) {
2931 for (size_t i = 0; i < effectChains.size(); i ++) {
2932 effectChains[i]->process_l();
2933 }
2934 }
Eric Laurent81784c32012-11-19 14:55:58 -08002935
Andy Hung98ef9782014-03-04 14:46:50 -08002936 // Only if the Effects buffer is enabled and there is data in the
2937 // Effects buffer (buffer valid), we need to
2938 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002939 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08002940 if (mEffectBufferValid) {
2941 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
2942 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
2943 mNormalFrameCount * mChannelCount);
2944 }
2945
Eric Laurent81784c32012-11-19 14:55:58 -08002946 // enable changes in effect chain
2947 unlockEffectChains(effectChains);
2948
Eric Laurentbfb1b832013-01-07 09:53:42 -08002949 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002950 // mSleepTimeUs == 0 means we must write to audio hardware
2951 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07002952 ssize_t ret = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002953 if (mBytesRemaining) {
Andy Hung08fb1742015-05-31 23:22:10 -07002954 ret = threadLoop_write();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002955 if (ret < 0) {
2956 mBytesRemaining = 0;
2957 } else {
2958 mBytesWritten += ret;
2959 mBytesRemaining -= ret;
2960 }
2961 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
2962 (mMixerStatus == MIXER_DRAIN_ALL)) {
2963 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08002964 }
Andy Hung08fb1742015-05-31 23:22:10 -07002965 if (mType == MIXER && !mStandby) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07002966 // write blocked detection
2967 nsecs_t now = systemTime();
2968 nsecs_t delta = now - mLastWriteTime;
Andy Hung08fb1742015-05-31 23:22:10 -07002969 if (delta > maxPeriod) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07002970 mNumDelayedWrites++;
2971 if ((now - lastWarning) > kWarningThrottleNs) {
2972 ATRACE_NAME("underrun");
2973 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2974 ns2ms(delta), mNumDelayedWrites, this);
2975 lastWarning = now;
2976 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002977 }
Andy Hung08fb1742015-05-31 23:22:10 -07002978
2979 if (mThreadThrottle
2980 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
2981 && ret > 0) { // we wrote something
2982 // Limit MixerThread data processing to no more than twice the
2983 // expected processing rate.
2984 //
2985 // This helps prevent underruns with NuPlayer and other applications
2986 // which may set up buffers that are close to the minimum size, or use
2987 // deep buffers, and rely on a double-buffering sleep strategy to fill.
2988 //
2989 // The throttle smooths out sudden large data drains from the device,
2990 // e.g. when it comes out of standby, which often causes problems with
2991 // (1) mixer threads without a fast mixer (which has its own warm-up)
2992 // (2) minimum buffer sized tracks (even if the track is full,
2993 // the app won't fill fast enough to handle the sudden draw).
2994
2995 const int32_t deltaMs = delta / 1000000;
2996 const int32_t throttleMs = mHalfBufferMs - deltaMs;
2997 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
2998 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07002999 // notify of throttle start on verbose log
3000 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3001 "mixer(%p) throttle begin:"
3002 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003003 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07003004 mThreadThrottleTimeMs += throttleMs;
3005 } else {
3006 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3007 if (diff > 0) {
3008 // notify of throttle end on debug log
3009 ALOGD("mixer(%p) throttle end: throttle time(%u)", this, diff);
3010 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3011 }
Andy Hung08fb1742015-05-31 23:22:10 -07003012 }
3013 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003014 }
Eric Laurent81784c32012-11-19 14:55:58 -08003015
Eric Laurentbfb1b832013-01-07 09:53:42 -08003016 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003017 ATRACE_BEGIN("sleep");
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003018 usleep(mSleepTimeUs);
Glenn Kastene7754022014-10-31 12:11:26 -07003019 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003020 }
Eric Laurent81784c32012-11-19 14:55:58 -08003021 }
3022
3023 // Finally let go of removed track(s), without the lock held
3024 // since we can't guarantee the destructors won't acquire that
3025 // same lock. This will also mutate and push a new fast mixer state.
3026 threadLoop_removeTracks(tracksToRemove);
3027 tracksToRemove.clear();
3028
3029 // FIXME I don't understand the need for this here;
3030 // it was in the original code but maybe the
3031 // assignment in saveOutputTracks() makes this unnecessary?
3032 clearOutputTracks();
3033
3034 // Effect chains will be actually deleted here if they were removed from
3035 // mEffectChains list during mixing or effects processing
3036 effectChains.clear();
3037
3038 // FIXME Note that the above .clear() is no longer necessary since effectChains
3039 // is now local to this block, but will keep it for now (at least until merge done).
3040 }
3041
Eric Laurentbfb1b832013-01-07 09:53:42 -08003042 threadLoop_exit();
3043
Eric Laurentcf817a22014-08-04 20:36:31 -07003044 if (!mStandby) {
3045 threadLoop_standby();
3046 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003047 }
3048
3049 releaseWakeLock();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003050 mWakeLockUids.clear();
3051 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08003052
3053 ALOGV("Thread %p type %d exiting", this, mType);
3054 return false;
3055}
3056
Eric Laurentbfb1b832013-01-07 09:53:42 -08003057// removeTracks_l() must be called with ThreadBase::mLock held
3058void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3059{
3060 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07003061 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003062 for (size_t i=0 ; i<count ; i++) {
3063 const sp<Track>& track = tracksToRemove.itemAt(i);
3064 mActiveTracks.remove(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003065 mWakeLockUids.remove(track->uid());
3066 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003067 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
3068 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3069 if (chain != 0) {
3070 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
3071 track->sessionId());
3072 chain->decActiveTrackCnt();
3073 }
3074 if (track->isTerminated()) {
3075 removeTrack_l(track);
3076 }
3077 }
3078 }
3079
3080}
Eric Laurent81784c32012-11-19 14:55:58 -08003081
Eric Laurentaccc1472013-09-20 09:36:34 -07003082status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3083{
3084 if (mNormalSink != 0) {
3085 return mNormalSink->getTimestamp(timestamp);
3086 }
Andy Hung9a1c8892014-12-03 11:37:42 -08003087 if ((mType == OFFLOAD || mType == DIRECT)
3088 && mOutput != NULL && mOutput->stream->get_presentation_position) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003089 uint64_t position64;
Phil Burk062e67a2015-02-11 13:40:50 -08003090 int ret = mOutput->getPresentationPosition(&position64, &timestamp.mTime);
Eric Laurentaccc1472013-09-20 09:36:34 -07003091 if (ret == 0) {
3092 timestamp.mPosition = (uint32_t)position64;
3093 return NO_ERROR;
3094 }
3095 }
3096 return INVALID_OPERATION;
3097}
Eric Laurent1c333e22014-05-20 10:48:17 -07003098
Eric Laurent054d9d32015-04-24 08:48:48 -07003099status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
3100 audio_patch_handle_t *handle)
3101{
3102 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3103 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3104 if (mFastMixer != 0) {
3105 FastMixerStateQueue *sq = mFastMixer->sq();
3106 FastMixerState *state = sq->begin();
3107 if (!(state->mCommand & FastMixerState::IDLE)) {
3108 previousCommand = state->mCommand;
3109 state->mCommand = FastMixerState::HOT_IDLE;
3110 sq->end();
3111 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3112 } else {
3113 sq->end(false /*didModify*/);
3114 }
3115 }
3116 status_t status = PlaybackThread::createAudioPatch_l(patch, handle);
3117
3118 if (!(previousCommand & FastMixerState::IDLE)) {
3119 ALOG_ASSERT(mFastMixer != 0);
3120 FastMixerStateQueue *sq = mFastMixer->sq();
3121 FastMixerState *state = sq->begin();
3122 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3123 state->mCommand = previousCommand;
3124 sq->end();
3125 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3126 }
3127
3128 return status;
3129}
3130
Eric Laurent1c333e22014-05-20 10:48:17 -07003131status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3132 audio_patch_handle_t *handle)
3133{
3134 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003135
3136 // store new device and send to effects
3137 audio_devices_t type = AUDIO_DEVICE_NONE;
3138 for (unsigned int i = 0; i < patch->num_sinks; i++) {
3139 type |= patch->sinks[i].ext.device.type;
3140 }
3141
3142#ifdef ADD_BATTERY_DATA
3143 // when changing the audio output device, call addBatteryData to notify
3144 // the change
3145 if (mOutDevice != type) {
3146 uint32_t params = 0;
3147 // check whether speaker is on
3148 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3149 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003150 }
3151
Eric Laurent054d9d32015-04-24 08:48:48 -07003152 audio_devices_t deviceWithoutSpeaker
3153 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3154 // check if any other device (except speaker) is on
3155 if (type & deviceWithoutSpeaker) {
3156 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3157 }
3158
3159 if (params != 0) {
3160 addBatteryData(params);
3161 }
3162 }
3163#endif
3164
3165 for (size_t i = 0; i < mEffectChains.size(); i++) {
3166 mEffectChains[i]->setDevice_l(type);
3167 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003168
3169 // mPrevOutDevice is the latest device set by createAudioPatch_l(). It is not set when
3170 // the thread is created so that the first patch creation triggers an ioConfigChanged callback
3171 bool configChanged = mPrevOutDevice != type;
Eric Laurent054d9d32015-04-24 08:48:48 -07003172 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003173 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003174
3175 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003176 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
3177 status = hwDevice->create_audio_patch(hwDevice,
3178 patch->num_sources,
3179 patch->sources,
3180 patch->num_sinks,
3181 patch->sinks,
3182 handle);
3183 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003184 char *address;
3185 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3186 //FIXME: we only support address on first sink with HAL version < 3.0
3187 address = audio_device_address_to_parameter(
3188 patch->sinks[0].ext.device.type,
3189 patch->sinks[0].ext.device.address);
3190 } else {
3191 address = (char *)calloc(1, 1);
3192 }
3193 AudioParameter param = AudioParameter(String8(address));
3194 free(address);
3195 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), (int)type);
3196 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3197 param.toString().string());
3198 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003199 }
Eric Laurente8726fe2015-06-26 09:39:24 -07003200 if (configChanged) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003201 mPrevOutDevice = type;
Eric Laurente8726fe2015-06-26 09:39:24 -07003202 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
3203 }
Eric Laurent1c333e22014-05-20 10:48:17 -07003204 return status;
3205}
3206
Eric Laurent054d9d32015-04-24 08:48:48 -07003207status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3208{
3209 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3210 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3211 if (mFastMixer != 0) {
3212 FastMixerStateQueue *sq = mFastMixer->sq();
3213 FastMixerState *state = sq->begin();
3214 if (!(state->mCommand & FastMixerState::IDLE)) {
3215 previousCommand = state->mCommand;
3216 state->mCommand = FastMixerState::HOT_IDLE;
3217 sq->end();
3218 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3219 } else {
3220 sq->end(false /*didModify*/);
3221 }
3222 }
3223
3224 status_t status = PlaybackThread::releaseAudioPatch_l(handle);
3225
3226 if (!(previousCommand & FastMixerState::IDLE)) {
3227 ALOG_ASSERT(mFastMixer != 0);
3228 FastMixerStateQueue *sq = mFastMixer->sq();
3229 FastMixerState *state = sq->begin();
3230 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3231 state->mCommand = previousCommand;
3232 sq->end();
3233 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3234 }
3235
3236 return status;
3237}
3238
Eric Laurent1c333e22014-05-20 10:48:17 -07003239status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3240{
3241 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003242
3243 mOutDevice = AUDIO_DEVICE_NONE;
3244
Eric Laurent1c333e22014-05-20 10:48:17 -07003245 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
3246 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
3247 status = hwDevice->release_audio_patch(hwDevice, handle);
3248 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003249 AudioParameter param;
3250 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
3251 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3252 param.toString().string());
Eric Laurent1c333e22014-05-20 10:48:17 -07003253 }
3254 return status;
3255}
3256
Eric Laurent83b88082014-06-20 18:31:16 -07003257void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3258{
3259 Mutex::Autolock _l(mLock);
3260 mTracks.add(track);
3261}
3262
3263void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3264{
3265 Mutex::Autolock _l(mLock);
3266 destroyTrack_l(track);
3267}
3268
3269void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
3270{
3271 ThreadBase::getAudioPortConfig(config);
3272 config->role = AUDIO_PORT_ROLE_SOURCE;
3273 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3274 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
3275}
3276
Eric Laurent81784c32012-11-19 14:55:58 -08003277// ----------------------------------------------------------------------------
3278
3279AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurent72e3f392015-05-20 14:43:50 -07003280 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
3281 : PlaybackThread(audioFlinger, output, id, device, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08003282 // mAudioMixer below
3283 // mFastMixer below
3284 mFastMixerFutex(0)
3285 // mOutputSink below
3286 // mPipeSink below
3287 // mNormalSink below
3288{
3289 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07003290 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, "
Eric Laurent81784c32012-11-19 14:55:58 -08003291 "mFrameCount=%d, mNormalFrameCount=%d",
3292 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3293 mNormalFrameCount);
3294 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3295
Andy Hungfbfc3952015-01-15 13:33:51 -08003296 if (type == DUPLICATING) {
3297 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3298 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3299 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3300 return;
3301 }
Eric Laurent81784c32012-11-19 14:55:58 -08003302 // create an NBAIO sink for the HAL output stream, and negotiate
3303 mOutputSink = new AudioStreamOutSink(output->stream);
3304 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003305 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Eric Laurent81784c32012-11-19 14:55:58 -08003306 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
3307 ALOG_ASSERT(index == 0);
3308
3309 // initialize fast mixer depending on configuration
3310 bool initFastMixer;
3311 switch (kUseFastMixer) {
3312 case FastMixer_Never:
3313 initFastMixer = false;
3314 break;
3315 case FastMixer_Always:
3316 initFastMixer = true;
3317 break;
3318 case FastMixer_Static:
3319 case FastMixer_Dynamic:
3320 initFastMixer = mFrameCount < mNormalFrameCount;
3321 break;
3322 }
3323 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003324 audio_format_t fastMixerFormat;
3325 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3326 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3327 } else {
3328 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3329 }
3330 if (mFormat != fastMixerFormat) {
3331 // change our Sink format to accept our intermediate precision
3332 mFormat = fastMixerFormat;
3333 free(mSinkBuffer);
3334 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3335 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3336 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3337 }
Eric Laurent81784c32012-11-19 14:55:58 -08003338
3339 // create a MonoPipe to connect our submix to FastMixer
3340 NBAIO_Format format = mOutputSink->format();
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003341 NBAIO_Format origformat = format;
Andy Hung1258c1a2014-05-23 21:22:17 -07003342 // adjust format to match that of the Fast Mixer
Glenn Kasten97b7b752014-09-28 13:04:24 -07003343 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003344 format.mFormat = fastMixerFormat;
3345 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3346
Eric Laurent81784c32012-11-19 14:55:58 -08003347 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3348 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3349 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3350 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3351 const NBAIO_Format offers[1] = {format};
3352 size_t numCounterOffers = 0;
3353 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
3354 ALOG_ASSERT(index == 0);
3355 monoPipe->setAvgFrames((mScreenState & 1) ?
3356 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3357 mPipeSink = monoPipe;
3358
Glenn Kasten46909e72013-02-26 09:20:22 -08003359#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08003360 if (mTeeSinkOutputEnabled) {
3361 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003362 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
3363 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08003364 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003365 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003366 ALOG_ASSERT(index == 0);
3367 mTeeSink = teeSink;
3368 PipeReader *teeSource = new PipeReader(*teeSink);
3369 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003370 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003371 ALOG_ASSERT(index == 0);
3372 mTeeSource = teeSource;
3373 }
Glenn Kasten46909e72013-02-26 09:20:22 -08003374#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003375
3376 // create fast mixer and configure it initially with just one fast track for our submix
3377 mFastMixer = new FastMixer();
3378 FastMixerStateQueue *sq = mFastMixer->sq();
3379#ifdef STATE_QUEUE_DUMP
3380 sq->setObserverDump(&mStateQueueObserverDump);
3381 sq->setMutatorDump(&mStateQueueMutatorDump);
3382#endif
3383 FastMixerState *state = sq->begin();
3384 FastTrack *fastTrack = &state->mFastTracks[0];
3385 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3386 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3387 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003388 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3389 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003390 fastTrack->mGeneration++;
3391 state->mFastTracksGen++;
3392 state->mTrackMask = 1;
3393 // fast mixer will use the HAL output sink
3394 state->mOutputSink = mOutputSink.get();
3395 state->mOutputSinkGen++;
3396 state->mFrameCount = mFrameCount;
3397 state->mCommand = FastMixerState::COLD_IDLE;
3398 // already done in constructor initialization list
3399 //mFastMixerFutex = 0;
3400 state->mColdFutexAddr = &mFastMixerFutex;
3401 state->mColdGen++;
3402 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08003403#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003404 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08003405#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08003406 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3407 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003408 sq->end();
3409 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3410
3411 // start the fast mixer
3412 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3413 pid_t tid = mFastMixer->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003414 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003415
3416#ifdef AUDIO_WATCHDOG
3417 // create and start the watchdog
3418 mAudioWatchdog = new AudioWatchdog();
3419 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3420 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3421 tid = mAudioWatchdog->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003422 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003423#endif
3424
Eric Laurent81784c32012-11-19 14:55:58 -08003425 }
3426
3427 switch (kUseFastMixer) {
3428 case FastMixer_Never:
3429 case FastMixer_Dynamic:
3430 mNormalSink = mOutputSink;
3431 break;
3432 case FastMixer_Always:
3433 mNormalSink = mPipeSink;
3434 break;
3435 case FastMixer_Static:
3436 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3437 break;
3438 }
3439}
3440
3441AudioFlinger::MixerThread::~MixerThread()
3442{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003443 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003444 FastMixerStateQueue *sq = mFastMixer->sq();
3445 FastMixerState *state = sq->begin();
3446 if (state->mCommand == FastMixerState::COLD_IDLE) {
3447 int32_t old = android_atomic_inc(&mFastMixerFutex);
3448 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003449 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003450 }
3451 }
3452 state->mCommand = FastMixerState::EXIT;
3453 sq->end();
3454 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3455 mFastMixer->join();
3456 // Though the fast mixer thread has exited, it's state queue is still valid.
3457 // We'll use that extract the final state which contains one remaining fast track
3458 // corresponding to our sub-mix.
3459 state = sq->begin();
3460 ALOG_ASSERT(state->mTrackMask == 1);
3461 FastTrack *fastTrack = &state->mFastTracks[0];
3462 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3463 delete fastTrack->mBufferProvider;
3464 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003465 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003466#ifdef AUDIO_WATCHDOG
3467 if (mAudioWatchdog != 0) {
3468 mAudioWatchdog->requestExit();
3469 mAudioWatchdog->requestExitAndWait();
3470 mAudioWatchdog.clear();
3471 }
3472#endif
3473 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003474 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003475 delete mAudioMixer;
3476}
3477
3478
3479uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3480{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003481 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003482 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3483 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3484 }
3485 return latency;
3486}
3487
3488
3489void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3490{
3491 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3492}
3493
Eric Laurentbfb1b832013-01-07 09:53:42 -08003494ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003495{
3496 // FIXME we should only do one push per cycle; confirm this is true
3497 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003498 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003499 FastMixerStateQueue *sq = mFastMixer->sq();
3500 FastMixerState *state = sq->begin();
3501 if (state->mCommand != FastMixerState::MIX_WRITE &&
3502 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3503 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07003504
3505 // FIXME workaround for first HAL write being CPU bound on some devices
3506 ATRACE_BEGIN("write");
3507 mOutput->write((char *)mSinkBuffer, 0);
3508 ATRACE_END();
3509
Eric Laurent81784c32012-11-19 14:55:58 -08003510 int32_t old = android_atomic_inc(&mFastMixerFutex);
3511 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003512 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003513 }
3514#ifdef AUDIO_WATCHDOG
3515 if (mAudioWatchdog != 0) {
3516 mAudioWatchdog->resume();
3517 }
3518#endif
3519 }
3520 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08003521#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003522 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08003523 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08003524#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003525 sq->end();
3526 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3527 if (kUseFastMixer == FastMixer_Dynamic) {
3528 mNormalSink = mPipeSink;
3529 }
3530 } else {
3531 sq->end(false /*didModify*/);
3532 }
3533 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003534 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003535}
3536
3537void AudioFlinger::MixerThread::threadLoop_standby()
3538{
3539 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003540 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003541 FastMixerStateQueue *sq = mFastMixer->sq();
3542 FastMixerState *state = sq->begin();
3543 if (!(state->mCommand & FastMixerState::IDLE)) {
3544 state->mCommand = FastMixerState::COLD_IDLE;
3545 state->mColdFutexAddr = &mFastMixerFutex;
3546 state->mColdGen++;
3547 mFastMixerFutex = 0;
3548 sq->end();
3549 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3550 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3551 if (kUseFastMixer == FastMixer_Dynamic) {
3552 mNormalSink = mOutputSink;
3553 }
3554#ifdef AUDIO_WATCHDOG
3555 if (mAudioWatchdog != 0) {
3556 mAudioWatchdog->pause();
3557 }
3558#endif
3559 } else {
3560 sq->end(false /*didModify*/);
3561 }
3562 }
3563 PlaybackThread::threadLoop_standby();
3564}
3565
Eric Laurentbfb1b832013-01-07 09:53:42 -08003566bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3567{
3568 return false;
3569}
3570
3571bool AudioFlinger::PlaybackThread::shouldStandby_l()
3572{
3573 return !mStandby;
3574}
3575
3576bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3577{
3578 Mutex::Autolock _l(mLock);
3579 return waitingAsyncCallback_l();
3580}
3581
Eric Laurent81784c32012-11-19 14:55:58 -08003582// shared by MIXER and DIRECT, overridden by DUPLICATING
3583void AudioFlinger::PlaybackThread::threadLoop_standby()
3584{
3585 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08003586 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003587 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003588 // discard any pending drain or write ack by incrementing sequence
3589 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3590 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003591 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003592 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3593 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003594 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003595 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003596}
3597
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003598void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3599{
3600 ALOGV("signal playback thread");
3601 broadcast_l();
3602}
3603
Eric Laurent81784c32012-11-19 14:55:58 -08003604void AudioFlinger::MixerThread::threadLoop_mix()
3605{
3606 // obtain the presentation timestamp of the next output buffer
3607 int64_t pts;
3608 status_t status = INVALID_OPERATION;
3609
3610 if (mNormalSink != 0) {
3611 status = mNormalSink->getNextWriteTimestamp(&pts);
3612 } else {
3613 status = mOutputSink->getNextWriteTimestamp(&pts);
3614 }
3615
3616 if (status != NO_ERROR) {
3617 pts = AudioBufferProvider::kInvalidPTS;
3618 }
3619
3620 // mix buffers...
3621 mAudioMixer->process(pts);
Andy Hung25c2dac2014-02-27 14:56:00 -08003622 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003623 // increase sleep time progressively when application underrun condition clears.
3624 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3625 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3626 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003627 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003628 sleepTimeShift--;
3629 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003630 mSleepTimeUs = 0;
3631 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08003632 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003633
Eric Laurent81784c32012-11-19 14:55:58 -08003634}
3635
3636void AudioFlinger::MixerThread::threadLoop_sleepTime()
3637{
3638 // If no tracks are ready, sleep once for the duration of an output
3639 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003640 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003641 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003642 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
3643 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
3644 mSleepTimeUs = kMinThreadSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003645 }
3646 // reduce sleep time in case of consecutive application underruns to avoid
3647 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3648 // duration we would end up writing less data than needed by the audio HAL if
3649 // the condition persists.
3650 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3651 sleepTimeShift++;
3652 }
3653 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003654 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003655 }
3656 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003657 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3658 // before effects processing or output.
3659 if (mMixerBufferValid) {
3660 memset(mMixerBuffer, 0, mMixerBufferSize);
3661 } else {
3662 memset(mSinkBuffer, 0, mSinkBufferSize);
3663 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003664 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003665 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3666 "anticipated start");
3667 }
3668 // TODO add standby time extension fct of effect tail
3669}
3670
3671// prepareTracks_l() must be called with ThreadBase::mLock held
3672AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3673 Vector< sp<Track> > *tracksToRemove)
3674{
3675
3676 mixer_state mixerStatus = MIXER_IDLE;
3677 // find out which tracks need to be processed
3678 size_t count = mActiveTracks.size();
3679 size_t mixedTracks = 0;
3680 size_t tracksWithEffect = 0;
3681 // counts only _active_ fast tracks
3682 size_t fastTracks = 0;
3683 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
3684
3685 float masterVolume = mMasterVolume;
3686 bool masterMute = mMasterMute;
3687
3688 if (masterMute) {
3689 masterVolume = 0;
3690 }
3691 // Delegate master volume control to effect in output mix effect chain if needed
3692 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3693 if (chain != 0) {
3694 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
3695 chain->setVolume_l(&v, &v);
3696 masterVolume = (float)((v + (1 << 23)) >> 24);
3697 chain.clear();
3698 }
3699
3700 // prepare a new state to push
3701 FastMixerStateQueue *sq = NULL;
3702 FastMixerState *state = NULL;
3703 bool didModify = false;
3704 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003705 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003706 sq = mFastMixer->sq();
3707 state = sq->begin();
3708 }
3709
Andy Hung69aed5f2014-02-25 17:24:40 -08003710 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08003711 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08003712
Eric Laurent81784c32012-11-19 14:55:58 -08003713 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003714 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003715 if (t == 0) {
3716 continue;
3717 }
3718
3719 // this const just means the local variable doesn't change
3720 Track* const track = t.get();
3721
3722 // process fast tracks
3723 if (track->isFastTrack()) {
3724
3725 // It's theoretically possible (though unlikely) for a fast track to be created
3726 // and then removed within the same normal mix cycle. This is not a problem, as
3727 // the track never becomes active so it's fast mixer slot is never touched.
3728 // The converse, of removing an (active) track and then creating a new track
3729 // at the identical fast mixer slot within the same normal mix cycle,
3730 // is impossible because the slot isn't marked available until the end of each cycle.
3731 int j = track->mFastIndex;
3732 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
3733 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
3734 FastTrack *fastTrack = &state->mFastTracks[j];
3735
3736 // Determine whether the track is currently in underrun condition,
3737 // and whether it had a recent underrun.
3738 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
3739 FastTrackUnderruns underruns = ftDump->mUnderruns;
3740 uint32_t recentFull = (underruns.mBitFields.mFull -
3741 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
3742 uint32_t recentPartial = (underruns.mBitFields.mPartial -
3743 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
3744 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
3745 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
3746 uint32_t recentUnderruns = recentPartial + recentEmpty;
3747 track->mObservedUnderruns = underruns;
3748 // don't count underruns that occur while stopping or pausing
3749 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07003750 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
3751 recentUnderruns > 0) {
3752 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
3753 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003754 }
3755
3756 // This is similar to the state machine for normal tracks,
3757 // with a few modifications for fast tracks.
3758 bool isActive = true;
3759 switch (track->mState) {
3760 case TrackBase::STOPPING_1:
3761 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08003762 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003763 track->mState = TrackBase::STOPPING_2;
3764 }
3765 break;
3766 case TrackBase::PAUSING:
3767 // ramp down is not yet implemented
3768 track->setPaused();
3769 break;
3770 case TrackBase::RESUMING:
3771 // ramp up is not yet implemented
3772 track->mState = TrackBase::ACTIVE;
3773 break;
3774 case TrackBase::ACTIVE:
3775 if (recentFull > 0 || recentPartial > 0) {
3776 // track has provided at least some frames recently: reset retry count
3777 track->mRetryCount = kMaxTrackRetries;
3778 }
3779 if (recentUnderruns == 0) {
3780 // no recent underruns: stay active
3781 break;
3782 }
3783 // there has recently been an underrun of some kind
3784 if (track->sharedBuffer() == 0) {
3785 // were any of the recent underruns "empty" (no frames available)?
3786 if (recentEmpty == 0) {
3787 // no, then ignore the partial underruns as they are allowed indefinitely
3788 break;
3789 }
3790 // there has recently been an "empty" underrun: decrement the retry counter
3791 if (--(track->mRetryCount) > 0) {
3792 break;
3793 }
3794 // indicate to client process that the track was disabled because of underrun;
3795 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003796 android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003797 // remove from active list, but state remains ACTIVE [confusing but true]
3798 isActive = false;
3799 break;
3800 }
3801 // fall through
3802 case TrackBase::STOPPING_2:
3803 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003804 case TrackBase::STOPPED:
3805 case TrackBase::FLUSHED: // flush() while active
3806 // Check for presentation complete if track is inactive
3807 // We have consumed all the buffers of this track.
3808 // This would be incomplete if we auto-paused on underrun
3809 {
3810 size_t audioHALFrames =
3811 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3812 size_t framesWritten = mBytesWritten / mFrameSize;
3813 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
3814 // track stays in active list until presentation is complete
3815 break;
3816 }
3817 }
3818 if (track->isStopping_2()) {
3819 track->mState = TrackBase::STOPPED;
3820 }
3821 if (track->isStopped()) {
3822 // Can't reset directly, as fast mixer is still polling this track
3823 // track->reset();
3824 // So instead mark this track as needing to be reset after push with ack
3825 resetMask |= 1 << i;
3826 }
3827 isActive = false;
3828 break;
3829 case TrackBase::IDLE:
3830 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08003831 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08003832 }
3833
3834 if (isActive) {
3835 // was it previously inactive?
3836 if (!(state->mTrackMask & (1 << j))) {
3837 ExtendedAudioBufferProvider *eabp = track;
3838 VolumeProvider *vp = track;
3839 fastTrack->mBufferProvider = eabp;
3840 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08003841 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003842 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08003843 fastTrack->mGeneration++;
3844 state->mTrackMask |= 1 << j;
3845 didModify = true;
3846 // no acknowledgement required for newly active tracks
3847 }
3848 // cache the combined master volume and stream type volume for fast mixer; this
3849 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08003850 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08003851 ++fastTracks;
3852 } else {
3853 // was it previously active?
3854 if (state->mTrackMask & (1 << j)) {
3855 fastTrack->mBufferProvider = NULL;
3856 fastTrack->mGeneration++;
3857 state->mTrackMask &= ~(1 << j);
3858 didModify = true;
3859 // If any fast tracks were removed, we must wait for acknowledgement
3860 // because we're about to decrement the last sp<> on those tracks.
3861 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3862 } else {
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08003863 LOG_ALWAYS_FATAL("fast track %d should have been active; "
3864 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
3865 j, track->mState, state->mTrackMask, recentUnderruns,
3866 track->sharedBuffer() != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08003867 }
3868 tracksToRemove->add(track);
3869 // Avoids a misleading display in dumpsys
3870 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
3871 }
3872 continue;
3873 }
3874
3875 { // local variable scope to avoid goto warning
3876
3877 audio_track_cblk_t* cblk = track->cblk();
3878
3879 // The first time a track is added we wait
3880 // for all its buffers to be filled before processing it
3881 int name = track->name();
3882 // make sure that we have enough frames to mix one full buffer.
3883 // enforce this condition only once to enable draining the buffer in case the client
3884 // app does not call stop() and relies on underrun to stop:
3885 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
3886 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003887 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07003888 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07003889 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07003890
3891 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07003892 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07003893 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
3894 // add frames already consumed but not yet released by the resampler
3895 // because mAudioTrackServerProxy->framesReady() will include these frames
3896 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
3897
Eric Laurent81784c32012-11-19 14:55:58 -08003898 uint32_t minFrames = 1;
3899 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
3900 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003901 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08003902 }
Eric Laurent13e4c962013-12-20 17:36:01 -08003903
3904 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07003905 if (ATRACE_ENABLED()) {
3906 // I wish we had formatted trace names
3907 char traceName[16];
3908 strcpy(traceName, "nRdy");
3909 int name = track->name();
3910 if (AudioMixer::TRACK0 <= name &&
3911 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
3912 name -= AudioMixer::TRACK0;
3913 traceName[4] = (name / 10) + '0';
3914 traceName[5] = (name % 10) + '0';
3915 } else {
3916 traceName[4] = '?';
3917 traceName[5] = '?';
3918 }
3919 traceName[6] = '\0';
3920 ATRACE_INT(traceName, framesReady);
3921 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003922 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08003923 !track->isPaused() && !track->isTerminated())
3924 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003925 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003926
3927 mixedTracks++;
3928
Andy Hung69aed5f2014-02-25 17:24:40 -08003929 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
3930 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08003931 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08003932 if (track->mainBuffer() != mSinkBuffer &&
3933 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08003934 if (mEffectBufferEnabled) {
3935 mEffectBufferValid = true; // Later can set directly.
3936 }
Eric Laurent81784c32012-11-19 14:55:58 -08003937 chain = getEffectChain_l(track->sessionId());
3938 // Delegate volume control to effect in track effect chain if needed
3939 if (chain != 0) {
3940 tracksWithEffect++;
3941 } else {
3942 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
3943 "session %d",
3944 name, track->sessionId());
3945 }
3946 }
3947
3948
3949 int param = AudioMixer::VOLUME;
3950 if (track->mFillingUpStatus == Track::FS_FILLED) {
3951 // no ramp for the first volume setting
3952 track->mFillingUpStatus = Track::FS_ACTIVE;
3953 if (track->mState == TrackBase::RESUMING) {
3954 track->mState = TrackBase::ACTIVE;
3955 param = AudioMixer::RAMP_VOLUME;
3956 }
3957 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003958 // FIXME should not make a decision based on mServer
3959 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003960 // If the track is stopped before the first frame was mixed,
3961 // do not apply ramp
3962 param = AudioMixer::RAMP_VOLUME;
3963 }
3964
3965 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07003966 uint32_t vl, vr; // in U8.24 integer format
3967 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08003968 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07003969 vl = vr = 0;
3970 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08003971 if (track->isPausing()) {
3972 track->setPaused();
3973 }
3974 } else {
3975
3976 // read original volumes with volume control
3977 float typeVolume = mStreamTypes[track->streamType()].volume;
3978 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003979 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07003980 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07003981 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
3982 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08003983 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07003984 if (vlf > GAIN_FLOAT_UNITY) {
3985 ALOGV("Track left volume out of range: %.3g", vlf);
3986 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003987 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07003988 if (vrf > GAIN_FLOAT_UNITY) {
3989 ALOGV("Track right volume out of range: %.3g", vrf);
3990 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003991 }
3992 // now apply the master volume and stream type volume
Andy Hung6be49402014-05-30 10:42:03 -07003993 vlf *= v;
3994 vrf *= v;
Eric Laurent81784c32012-11-19 14:55:58 -08003995 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07003996 // then derive vl and vr as U8.24 versions for the effect chain
3997 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
3998 vl = (uint32_t) (scaleto8_24 * vlf);
3999 vr = (uint32_t) (scaleto8_24 * vrf);
4000 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08004001 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08004002 // send level comes from shared memory and so may be corrupt
4003 if (sendLevel > MAX_GAIN_INT) {
4004 ALOGV("Track send level out of range: %04X", sendLevel);
4005 sendLevel = MAX_GAIN_INT;
4006 }
Andy Hung6be49402014-05-30 10:42:03 -07004007 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
4008 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08004009 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004010
Eric Laurent81784c32012-11-19 14:55:58 -08004011 // Delegate volume control to effect in track effect chain if needed
4012 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
4013 // Do not ramp volume if volume is controlled by effect
4014 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08004015 // Update remaining floating point volume levels
4016 vlf = (float)vl / (1 << 24);
4017 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08004018 track->mHasVolumeController = true;
4019 } else {
4020 // force no volume ramp when volume controller was just disabled or removed
4021 // from effect chain to avoid volume spike
4022 if (track->mHasVolumeController) {
4023 param = AudioMixer::VOLUME;
4024 }
4025 track->mHasVolumeController = false;
4026 }
4027
Eric Laurent81784c32012-11-19 14:55:58 -08004028 // XXX: these things DON'T need to be done each time
4029 mAudioMixer->setBufferProvider(name, track);
4030 mAudioMixer->enable(name);
4031
Andy Hung6be49402014-05-30 10:42:03 -07004032 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
4033 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
4034 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08004035 mAudioMixer->setParameter(
4036 name,
4037 AudioMixer::TRACK,
4038 AudioMixer::FORMAT, (void *)track->format());
4039 mAudioMixer->setParameter(
4040 name,
4041 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004042 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07004043 mAudioMixer->setParameter(
4044 name,
4045 AudioMixer::TRACK,
4046 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08004047 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07004048 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004049 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08004050 if (reqSampleRate == 0) {
4051 reqSampleRate = mSampleRate;
4052 } else if (reqSampleRate > maxSampleRate) {
4053 reqSampleRate = maxSampleRate;
4054 }
Eric Laurent81784c32012-11-19 14:55:58 -08004055 mAudioMixer->setParameter(
4056 name,
4057 AudioMixer::RESAMPLE,
4058 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004059 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004060
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004061 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004062 mAudioMixer->setParameter(
4063 name,
4064 AudioMixer::TIMESTRETCH,
4065 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004066 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004067
Andy Hung69aed5f2014-02-25 17:24:40 -08004068 /*
4069 * Select the appropriate output buffer for the track.
4070 *
Andy Hung98ef9782014-03-04 14:46:50 -08004071 * Tracks with effects go into their own effects chain buffer
4072 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08004073 *
4074 * Other tracks can use mMixerBuffer for higher precision
4075 * channel accumulation. If this buffer is enabled
4076 * (mMixerBufferEnabled true), then selected tracks will accumulate
4077 * into it.
4078 *
4079 */
4080 if (mMixerBufferEnabled
4081 && (track->mainBuffer() == mSinkBuffer
4082 || track->mainBuffer() == mMixerBuffer)) {
4083 mAudioMixer->setParameter(
4084 name,
4085 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004086 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08004087 mAudioMixer->setParameter(
4088 name,
4089 AudioMixer::TRACK,
4090 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
4091 // TODO: override track->mainBuffer()?
4092 mMixerBufferValid = true;
4093 } else {
4094 mAudioMixer->setParameter(
4095 name,
4096 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004097 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08004098 mAudioMixer->setParameter(
4099 name,
4100 AudioMixer::TRACK,
4101 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
4102 }
Eric Laurent81784c32012-11-19 14:55:58 -08004103 mAudioMixer->setParameter(
4104 name,
4105 AudioMixer::TRACK,
4106 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
4107
4108 // reset retry count
4109 track->mRetryCount = kMaxTrackRetries;
4110
4111 // If one track is ready, set the mixer ready if:
4112 // - the mixer was not ready during previous round OR
4113 // - no other track is not ready
4114 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
4115 mixerStatus != MIXER_TRACKS_ENABLED) {
4116 mixerStatus = MIXER_TRACKS_READY;
4117 }
4118 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004119 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hung08fb1742015-05-31 23:22:10 -07004120 ALOGV("track(%p) underrun, framesReady(%zu) < framesDesired(%zd)",
4121 track, framesReady, desiredFrames);
Glenn Kasten82aaf942013-07-17 16:05:07 -07004122 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004123 }
Eric Laurent81784c32012-11-19 14:55:58 -08004124 // clear effect chain input buffer if an active track underruns to avoid sending
4125 // previous audio buffer again to effects
4126 chain = getEffectChain_l(track->sessionId());
4127 if (chain != 0) {
4128 chain->clearInputBuffer();
4129 }
4130
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004131 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004132 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
4133 track->isStopped() || track->isPaused()) {
4134 // We have consumed all the buffers of this track.
4135 // Remove it from the list of active tracks.
4136 // TODO: use actual buffer filling status instead of latency when available from
4137 // audio HAL
4138 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
4139 size_t framesWritten = mBytesWritten / mFrameSize;
4140 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
4141 if (track->isStopped()) {
4142 track->reset();
4143 }
4144 tracksToRemove->add(track);
4145 }
4146 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08004147 // No buffers for this track. Give it a few chances to
4148 // fill a buffer, then remove it from active list.
4149 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004150 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004151 tracksToRemove->add(track);
4152 // indicate to client process that the track was disabled because of underrun;
4153 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07004154 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08004155 // If one track is not ready, mark the mixer also not ready if:
4156 // - the mixer was ready during previous round OR
4157 // - no other track is ready
4158 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
4159 mixerStatus != MIXER_TRACKS_READY) {
4160 mixerStatus = MIXER_TRACKS_ENABLED;
4161 }
4162 }
4163 mAudioMixer->disable(name);
4164 }
4165
4166 } // local variable scope to avoid goto warning
4167track_is_ready: ;
4168
4169 }
4170
4171 // Push the new FastMixer state if necessary
4172 bool pauseAudioWatchdog = false;
4173 if (didModify) {
4174 state->mFastTracksGen++;
4175 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4176 if (kUseFastMixer == FastMixer_Dynamic &&
4177 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4178 state->mCommand = FastMixerState::COLD_IDLE;
4179 state->mColdFutexAddr = &mFastMixerFutex;
4180 state->mColdGen++;
4181 mFastMixerFutex = 0;
4182 if (kUseFastMixer == FastMixer_Dynamic) {
4183 mNormalSink = mOutputSink;
4184 }
4185 // If we go into cold idle, need to wait for acknowledgement
4186 // so that fast mixer stops doing I/O.
4187 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4188 pauseAudioWatchdog = true;
4189 }
Eric Laurent81784c32012-11-19 14:55:58 -08004190 }
4191 if (sq != NULL) {
4192 sq->end(didModify);
4193 sq->push(block);
4194 }
4195#ifdef AUDIO_WATCHDOG
4196 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4197 mAudioWatchdog->pause();
4198 }
4199#endif
4200
4201 // Now perform the deferred reset on fast tracks that have stopped
4202 while (resetMask != 0) {
4203 size_t i = __builtin_ctz(resetMask);
4204 ALOG_ASSERT(i < count);
4205 resetMask &= ~(1 << i);
4206 sp<Track> t = mActiveTracks[i].promote();
4207 if (t == 0) {
4208 continue;
4209 }
4210 Track* track = t.get();
4211 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
4212 track->reset();
4213 }
4214
4215 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004216 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004217
Eric Laurent97d547d2014-09-02 14:45:53 -07004218 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
4219 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07004220 }
4221
4222 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07004223 // as long as there are effects we should clear the effects buffer, to avoid
4224 // passing a non-clean buffer to the effect chain
4225 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07004226 }
Andy Hung69aed5f2014-02-25 17:24:40 -08004227 // sink or mix buffer must be cleared if all tracks are connected to an
4228 // effect chain as in this case the mixer will not write to the sink or mix buffer
4229 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08004230 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4231 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08004232 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08004233 if (mMixerBufferValid) {
4234 memset(mMixerBuffer, 0, mMixerBufferSize);
4235 // TODO: In testing, mSinkBuffer below need not be cleared because
4236 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
4237 // after mixing.
4238 //
4239 // To enforce this guarantee:
4240 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4241 // (mixedTracks == 0 && fastTracks > 0))
4242 // must imply MIXER_TRACKS_READY.
4243 // Later, we may clear buffers regardless, and skip much of this logic.
4244 }
Andy Hung98ef9782014-03-04 14:46:50 -08004245 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07004246 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004247 }
4248
4249 // if any fast tracks, then status is ready
4250 mMixerStatusIgnoringFastTracks = mixerStatus;
4251 if (fastTracks > 0) {
4252 mixerStatus = MIXER_TRACKS_READY;
4253 }
4254 return mixerStatus;
4255}
4256
4257// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07004258int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
4259 audio_format_t format, int sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08004260{
Andy Hunge8a1ced2014-05-09 15:02:21 -07004261 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08004262}
4263
4264// deleteTrackName_l() must be called with ThreadBase::mLock held
4265void AudioFlinger::MixerThread::deleteTrackName_l(int name)
4266{
4267 ALOGV("remove track (%d) and delete from mixer", name);
4268 mAudioMixer->deleteTrackName(name);
4269}
4270
Eric Laurent10351942014-05-08 18:49:52 -07004271// checkForNewParameter_l() must be called with ThreadBase::mLock held
4272bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
4273 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004274{
Eric Laurent81784c32012-11-19 14:55:58 -08004275 bool reconfig = false;
4276
Eric Laurent10351942014-05-08 18:49:52 -07004277 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004278
Eric Laurent10351942014-05-08 18:49:52 -07004279 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
4280 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004281 if (mFastMixer != 0) {
Eric Laurent10351942014-05-08 18:49:52 -07004282 FastMixerStateQueue *sq = mFastMixer->sq();
4283 FastMixerState *state = sq->begin();
4284 if (!(state->mCommand & FastMixerState::IDLE)) {
4285 previousCommand = state->mCommand;
4286 state->mCommand = FastMixerState::HOT_IDLE;
4287 sq->end();
4288 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
4289 } else {
4290 sq->end(false /*didModify*/);
Eric Laurent81784c32012-11-19 14:55:58 -08004291 }
Eric Laurent10351942014-05-08 18:49:52 -07004292 }
Eric Laurent81784c32012-11-19 14:55:58 -08004293
Eric Laurent10351942014-05-08 18:49:52 -07004294 AudioParameter param = AudioParameter(keyValuePair);
4295 int value;
4296 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4297 reconfig = true;
4298 }
4299 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004300 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004301 status = BAD_VALUE;
4302 } else {
4303 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08004304 reconfig = true;
4305 }
Eric Laurent10351942014-05-08 18:49:52 -07004306 }
4307 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004308 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004309 status = BAD_VALUE;
4310 } else {
4311 // no need to save value, since it's constant
4312 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004313 }
Eric Laurent10351942014-05-08 18:49:52 -07004314 }
4315 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4316 // do not accept frame count changes if tracks are open as the track buffer
4317 // size depends on frame count and correct behavior would not be guaranteed
4318 // if frame count is changed after track creation
4319 if (!mTracks.isEmpty()) {
4320 status = INVALID_OPERATION;
4321 } else {
4322 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004323 }
Eric Laurent10351942014-05-08 18:49:52 -07004324 }
4325 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004326#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07004327 // when changing the audio output device, call addBatteryData to notify
4328 // the change
4329 if (mOutDevice != value) {
4330 uint32_t params = 0;
4331 // check whether speaker is on
4332 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
4333 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08004334 }
Eric Laurent10351942014-05-08 18:49:52 -07004335
4336 audio_devices_t deviceWithoutSpeaker
4337 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
4338 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07004339 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07004340 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4341 }
4342
4343 if (params != 0) {
4344 addBatteryData(params);
4345 }
4346 }
Eric Laurent81784c32012-11-19 14:55:58 -08004347#endif
4348
Eric Laurent10351942014-05-08 18:49:52 -07004349 // forward device change to effects that have requested to be
4350 // aware of attached audio device.
4351 if (value != AUDIO_DEVICE_NONE) {
4352 mOutDevice = value;
4353 for (size_t i = 0; i < mEffectChains.size(); i++) {
4354 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08004355 }
4356 }
Eric Laurent10351942014-05-08 18:49:52 -07004357 }
Eric Laurent81784c32012-11-19 14:55:58 -08004358
Eric Laurent10351942014-05-08 18:49:52 -07004359 if (status == NO_ERROR) {
4360 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4361 keyValuePair.string());
4362 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004363 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004364 mStandby = true;
4365 mBytesWritten = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004366 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Eric Laurent10351942014-05-08 18:49:52 -07004367 keyValuePair.string());
Eric Laurent81784c32012-11-19 14:55:58 -08004368 }
Eric Laurent10351942014-05-08 18:49:52 -07004369 if (status == NO_ERROR && reconfig) {
4370 readOutputParameters_l();
4371 delete mAudioMixer;
4372 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4373 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07004374 int name = getTrackName_l(mTracks[i]->mChannelMask,
4375 mTracks[i]->mFormat, mTracks[i]->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07004376 if (name < 0) {
4377 break;
4378 }
4379 mTracks[i]->mName = name;
4380 }
Eric Laurent73e26b62015-04-27 16:55:58 -07004381 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004382 }
Eric Laurent81784c32012-11-19 14:55:58 -08004383 }
4384
4385 if (!(previousCommand & FastMixerState::IDLE)) {
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004386 ALOG_ASSERT(mFastMixer != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08004387 FastMixerStateQueue *sq = mFastMixer->sq();
4388 FastMixerState *state = sq->begin();
4389 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
4390 state->mCommand = previousCommand;
4391 sq->end();
4392 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4393 }
4394
4395 return reconfig;
4396}
4397
4398
4399void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
4400{
4401 const size_t SIZE = 256;
4402 char buffer[SIZE];
4403 String8 result;
4404
4405 PlaybackThread::dumpInternals(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07004406 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Elliott Hughes87cebad2014-05-22 10:14:43 -07004407 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Eric Laurent81784c32012-11-19 14:55:58 -08004408
4409 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten2f90c512015-12-02 11:40:09 -08004410 // while we are dumping it. It may be inconsistent, but it won't mutate!
4411 // This is a large object so we place it on the heap.
4412 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
4413 const FastMixerDumpState *copy = new FastMixerDumpState(mFastMixerDumpState);
4414 copy->dump(fd);
4415 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08004416
4417#ifdef STATE_QUEUE_DUMP
4418 // Similar for state queue
4419 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4420 observerCopy.dump(fd);
4421 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4422 mutatorCopy.dump(fd);
4423#endif
4424
Glenn Kasten46909e72013-02-26 09:20:22 -08004425#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08004426 // Write the tee output to a .wav file
4427 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08004428#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004429
4430#ifdef AUDIO_WATCHDOG
4431 if (mAudioWatchdog != 0) {
4432 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4433 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4434 wdCopy.dump(fd);
4435 }
4436#endif
4437}
4438
4439uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4440{
4441 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4442}
4443
4444uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4445{
4446 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4447}
4448
4449void AudioFlinger::MixerThread::cacheParameters_l()
4450{
4451 PlaybackThread::cacheParameters_l();
4452
4453 // FIXME: Relaxed timing because of a certain device that can't meet latency
4454 // Should be reduced to 2x after the vendor fixes the driver issue
4455 // increase threshold again due to low power audio mode. The way this warning
4456 // threshold is calculated and its usefulness should be reconsidered anyway.
4457 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4458}
4459
4460// ----------------------------------------------------------------------------
4461
4462AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07004463 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device, bool systemReady)
4464 : PlaybackThread(audioFlinger, output, id, device, DIRECT, systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08004465 // mLeftVolFloat, mRightVolFloat
4466{
4467}
4468
Eric Laurentbfb1b832013-01-07 09:53:42 -08004469AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4470 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07004471 ThreadBase::type_t type, bool systemReady)
4472 : PlaybackThread(audioFlinger, output, id, device, type, systemReady)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004473 // mLeftVolFloat, mRightVolFloat
4474{
4475}
4476
Eric Laurent81784c32012-11-19 14:55:58 -08004477AudioFlinger::DirectOutputThread::~DirectOutputThread()
4478{
4479}
4480
Eric Laurentbfb1b832013-01-07 09:53:42 -08004481void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
4482{
4483 audio_track_cblk_t* cblk = track->cblk();
4484 float left, right;
4485
4486 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4487 left = right = 0;
4488 } else {
4489 float typeVolume = mStreamTypes[track->streamType()].volume;
4490 float v = mMasterVolume * typeVolume;
4491 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004492 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4493 left = float_from_gain(gain_minifloat_unpack_left(vlr));
4494 if (left > GAIN_FLOAT_UNITY) {
4495 left = GAIN_FLOAT_UNITY;
4496 }
4497 left *= v;
4498 right = float_from_gain(gain_minifloat_unpack_right(vlr));
4499 if (right > GAIN_FLOAT_UNITY) {
4500 right = GAIN_FLOAT_UNITY;
4501 }
4502 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004503 }
4504
4505 if (lastTrack) {
4506 if (left != mLeftVolFloat || right != mRightVolFloat) {
4507 mLeftVolFloat = left;
4508 mRightVolFloat = right;
4509
4510 // Convert volumes from float to 8.24
4511 uint32_t vl = (uint32_t)(left * (1 << 24));
4512 uint32_t vr = (uint32_t)(right * (1 << 24));
4513
4514 // Delegate volume control to effect in track effect chain if needed
4515 // only one effect chain can be present on DirectOutputThread, so if
4516 // there is one, the track is connected to it
4517 if (!mEffectChains.isEmpty()) {
4518 mEffectChains[0]->setVolume_l(&vl, &vr);
4519 left = (float)vl / (1 << 24);
4520 right = (float)vr / (1 << 24);
4521 }
4522 if (mOutput->stream->set_volume) {
4523 mOutput->stream->set_volume(mOutput->stream, left, right);
4524 }
4525 }
4526 }
4527}
4528
Phil Burk43b4dcc2015-06-09 16:53:44 -07004529void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
4530{
4531 sp<Track> previousTrack = mPreviousTrack.promote();
4532 sp<Track> latestTrack = mLatestActiveTrack.promote();
4533
Eric Laurent0f0631e2015-07-06 18:01:25 -07004534 if (previousTrack != 0 && latestTrack != 0) {
4535 if (mType == DIRECT) {
4536 if (previousTrack.get() != latestTrack.get()) {
4537 mFlushPending = true;
4538 }
4539 } else /* mType == OFFLOAD */ {
4540 if (previousTrack->sessionId() != latestTrack->sessionId()) {
4541 mFlushPending = true;
4542 }
4543 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004544 }
4545 PlaybackThread::onAddNewTrack_l();
4546}
Eric Laurentbfb1b832013-01-07 09:53:42 -08004547
Eric Laurent81784c32012-11-19 14:55:58 -08004548AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4549 Vector< sp<Track> > *tracksToRemove
4550)
4551{
Eric Laurentd595b7c2013-04-03 17:27:56 -07004552 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08004553 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004554 bool doHwPause = false;
4555 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004556
4557 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07004558 for (size_t i = 0; i < count; i++) {
4559 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08004560 // The track died recently
4561 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004562 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08004563 }
4564
Phil Burk43b4dcc2015-06-09 16:53:44 -07004565 if (t->isInvalid()) {
4566 ALOGW("An invalidated track shouldn't be in active list");
4567 tracksToRemove->add(t);
4568 continue;
4569 }
4570
Eric Laurent81784c32012-11-19 14:55:58 -08004571 Track* const track = t.get();
4572 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07004573 // Only consider last track started for volume and mixer state control.
4574 // In theory an older track could underrun and restart after the new one starts
4575 // but as we only care about the transition phase between two tracks on a
4576 // direct output, it is not a problem to ignore the underrun case.
4577 sp<Track> l = mLatestActiveTrack.promote();
4578 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08004579
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004580 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004581 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004582 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004583 doHwPause = true;
4584 mHwPaused = true;
4585 }
4586 tracksToRemove->add(track);
4587 } else if (track->isFlushPending()) {
4588 track->flushAck();
4589 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004590 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004591 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004592 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004593 track->resumeAck();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004594 if (last && mHwPaused) {
4595 doHwResume = true;
4596 mHwPaused = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004597 }
4598 }
4599
Eric Laurent81784c32012-11-19 14:55:58 -08004600 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08004601 // for all its buffers to be filled before processing it.
4602 // Allow draining the buffer in case the client
4603 // app does not call stop() and relies on underrun to stop:
4604 // hence the test on (track->mRetryCount > 1).
4605 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07004606 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08004607 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08004608 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkca5e6142015-07-14 09:42:29 -07004609 && (track->mRetryCount > 1) && audio_is_linear_pcm(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004610 minFrames = mNormalFrameCount;
4611 } else {
4612 minFrames = 1;
4613 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004614
Eric Laurentab5cdba2014-06-09 17:22:27 -07004615 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4616 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08004617 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004618 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08004619
4620 if (track->mFillingUpStatus == Track::FS_FILLED) {
4621 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004622 // make sure processVolume_l() will apply new volume even if 0
4623 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004624 if (!mHwSupportsPause) {
4625 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08004626 }
4627 }
4628
4629 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004630 processVolume_l(track, last);
4631 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004632 sp<Track> previousTrack = mPreviousTrack.promote();
4633 if (previousTrack != 0) {
4634 if (track != previousTrack.get()) {
4635 // Flush any data still being written from last track
4636 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07004637 // Invalidate previous track to force a seek when resuming.
4638 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004639 }
4640 }
4641 mPreviousTrack = track;
4642
Eric Laurentd595b7c2013-04-03 17:27:56 -07004643 // reset retry count
4644 track->mRetryCount = kMaxTrackRetriesDirect;
4645 mActiveTrack = t;
4646 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07004647 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004648 doHwResume = true;
4649 mHwPaused = false;
4650 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004651 }
Eric Laurent81784c32012-11-19 14:55:58 -08004652 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004653 // clear effect chain input buffer if the last active track started underruns
4654 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07004655 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004656 mEffectChains[0]->clearInputBuffer();
4657 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004658 if (track->isStopping_1()) {
4659 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07004660 if (last && mHwPaused) {
4661 doHwResume = true;
4662 mHwPaused = false;
4663 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004664 }
4665 if ((track->sharedBuffer() != 0) || track->isStopped() ||
4666 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004667 // We have consumed all the buffers of this track.
4668 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07004669 size_t audioHALFrames;
4670 if (audio_is_linear_pcm(mFormat)) {
4671 audioHALFrames = (latency_l() * mSampleRate) / 1000;
4672 } else {
4673 audioHALFrames = 0;
4674 }
4675
Eric Laurent81784c32012-11-19 14:55:58 -08004676 size_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07004677 if (mStandby || !last ||
4678 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004679 if (track->isStopping_2()) {
4680 track->mState = TrackBase::STOPPED;
4681 }
Eric Laurent81784c32012-11-19 14:55:58 -08004682 if (track->isStopped()) {
4683 track->reset();
4684 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004685 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08004686 }
4687 } else {
4688 // No buffers for this track. Give it a few chances to
4689 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07004690 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08004691 if (--(track->mRetryCount) <= 0) {
4692 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07004693 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004694 // indicate to client process that the track was disabled because of underrun;
4695 // it will then automatically call start() when data is available
4696 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004697 } else if (last) {
Phil Burkca5e6142015-07-14 09:42:29 -07004698 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
4699 "minFrames = %u, mFormat = %#x",
4700 track->framesReady(), minFrames, mFormat);
Eric Laurent81784c32012-11-19 14:55:58 -08004701 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07004702 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004703 doHwPause = true;
4704 mHwPaused = true;
4705 }
Eric Laurent81784c32012-11-19 14:55:58 -08004706 }
4707 }
4708 }
4709 }
4710
Eric Laurentd1f69b02014-12-15 14:33:13 -08004711 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07004712 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004713 for (size_t i = 0; i < mTracks.size(); i++) {
4714 if (mTracks[i]->isFlushPending()) {
4715 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004716 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004717 }
4718 }
4719 }
4720
4721 // make sure the pause/flush/resume sequence is executed in the right order.
4722 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4723 // before flush and then resume HW. This can happen in case of pause/flush/resume
4724 // if resume is received before pause is executed.
4725 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07004726 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004727 mOutput->stream->pause(mOutput->stream);
4728 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004729 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004730 flushHw_l();
4731 }
4732 if (mHwSupportsPause && !mStandby && doHwResume) {
4733 mOutput->stream->resume(mOutput->stream);
4734 }
Eric Laurent81784c32012-11-19 14:55:58 -08004735 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004736 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004737
4738 return mixerStatus;
4739}
4740
4741void AudioFlinger::DirectOutputThread::threadLoop_mix()
4742{
Eric Laurent81784c32012-11-19 14:55:58 -08004743 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08004744 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004745 // output audio to hardware
4746 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07004747 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004748 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08004749 status_t status = mActiveTrack->getNextBuffer(&buffer);
4750 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08004751 memset(curBuf, 0, frameCount * mFrameSize);
4752 break;
4753 }
4754 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
4755 frameCount -= buffer.frameCount;
4756 curBuf += buffer.frameCount * mFrameSize;
4757 mActiveTrack->releaseBuffer(&buffer);
4758 }
Andy Hung2098f272014-02-27 14:00:06 -08004759 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004760 mSleepTimeUs = 0;
4761 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08004762 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004763}
4764
4765void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
4766{
Eric Laurentd1f69b02014-12-15 14:33:13 -08004767 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004768 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004769 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004770 return;
4771 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004772 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004773 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004774 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004775 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004776 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004777 }
4778 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08004779 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004780 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004781 }
4782}
4783
Eric Laurentd1f69b02014-12-15 14:33:13 -08004784void AudioFlinger::DirectOutputThread::threadLoop_exit()
4785{
4786 {
4787 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08004788 for (size_t i = 0; i < mTracks.size(); i++) {
4789 if (mTracks[i]->isFlushPending()) {
4790 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004791 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004792 }
4793 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004794 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004795 flushHw_l();
4796 }
4797 }
4798 PlaybackThread::threadLoop_exit();
4799}
4800
4801// must be called with thread mutex locked
4802bool AudioFlinger::DirectOutputThread::shouldStandby_l()
4803{
4804 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07004805 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004806
4807 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4808 // after a timeout and we will enter standby then.
4809 if (mTracks.size() > 0) {
4810 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07004811 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
4812 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004813 }
4814
Eric Laurent5cff4032015-05-26 13:49:58 -07004815 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08004816}
4817
Eric Laurent81784c32012-11-19 14:55:58 -08004818// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004819int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Andy Hunge8a1ced2014-05-09 15:02:21 -07004820 audio_format_t format __unused, int sessionId __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004821{
4822 return 0;
4823}
4824
4825// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004826void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004827{
4828}
4829
Eric Laurent10351942014-05-08 18:49:52 -07004830// checkForNewParameter_l() must be called with ThreadBase::mLock held
4831bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
4832 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004833{
4834 bool reconfig = false;
4835
Eric Laurent10351942014-05-08 18:49:52 -07004836 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004837
Eric Laurent10351942014-05-08 18:49:52 -07004838 AudioParameter param = AudioParameter(keyValuePair);
4839 int value;
4840 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4841 // forward device change to effects that have requested to be
4842 // aware of attached audio device.
4843 if (value != AUDIO_DEVICE_NONE) {
4844 mOutDevice = value;
4845 for (size_t i = 0; i < mEffectChains.size(); i++) {
4846 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07004847 }
4848 }
Eric Laurent81784c32012-11-19 14:55:58 -08004849 }
Eric Laurent10351942014-05-08 18:49:52 -07004850 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4851 // do not accept frame count changes if tracks are open as the track buffer
4852 // size depends on frame count and correct behavior would not be garantied
4853 // if frame count is changed after track creation
4854 if (!mTracks.isEmpty()) {
4855 status = INVALID_OPERATION;
4856 } else {
4857 reconfig = true;
4858 }
4859 }
4860 if (status == NO_ERROR) {
4861 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4862 keyValuePair.string());
4863 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004864 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004865 mStandby = true;
4866 mBytesWritten = 0;
4867 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4868 keyValuePair.string());
4869 }
4870 if (status == NO_ERROR && reconfig) {
4871 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07004872 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004873 }
4874 }
4875
Eric Laurent81784c32012-11-19 14:55:58 -08004876 return reconfig;
4877}
4878
4879uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
4880{
4881 uint32_t time;
4882 if (audio_is_linear_pcm(mFormat)) {
4883 time = PlaybackThread::activeSleepTimeUs();
4884 } else {
4885 time = 10000;
4886 }
4887 return time;
4888}
4889
4890uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
4891{
4892 uint32_t time;
4893 if (audio_is_linear_pcm(mFormat)) {
4894 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
4895 } else {
4896 time = 10000;
4897 }
4898 return time;
4899}
4900
4901uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
4902{
4903 uint32_t time;
4904 if (audio_is_linear_pcm(mFormat)) {
4905 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
4906 } else {
4907 time = 10000;
4908 }
4909 return time;
4910}
4911
4912void AudioFlinger::DirectOutputThread::cacheParameters_l()
4913{
4914 PlaybackThread::cacheParameters_l();
4915
4916 // use shorter standby delay as on normal output to release
4917 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07004918 // no delay on outputs with HW A/V sync
4919 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004920 mStandbyDelayNs = 0;
Eric Laurent5cff4032015-05-26 13:49:58 -07004921 } else if ((mType == OFFLOAD) && !audio_is_linear_pcm(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004922 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07004923 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004924 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07004925 }
Eric Laurent81784c32012-11-19 14:55:58 -08004926}
4927
Eric Laurente659ef42014-09-29 13:06:46 -07004928void AudioFlinger::DirectOutputThread::flushHw_l()
4929{
Phil Burk062e67a2015-02-11 13:40:50 -08004930 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08004931 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07004932 mFlushPending = false;
Eric Laurente659ef42014-09-29 13:06:46 -07004933}
4934
Eric Laurent81784c32012-11-19 14:55:58 -08004935// ----------------------------------------------------------------------------
4936
Eric Laurentbfb1b832013-01-07 09:53:42 -08004937AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07004938 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004939 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07004940 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07004941 mWriteAckSequence(0),
4942 mDrainSequence(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004943{
4944}
4945
4946AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
4947{
4948}
4949
4950void AudioFlinger::AsyncCallbackThread::onFirstRef()
4951{
4952 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
4953}
4954
4955bool AudioFlinger::AsyncCallbackThread::threadLoop()
4956{
4957 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004958 uint32_t writeAckSequence;
4959 uint32_t drainSequence;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004960
4961 {
4962 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08004963 while (!((mWriteAckSequence & 1) ||
4964 (mDrainSequence & 1) ||
4965 exitPending())) {
4966 mWaitWorkCV.wait(mLock);
4967 }
4968
Eric Laurentbfb1b832013-01-07 09:53:42 -08004969 if (exitPending()) {
4970 break;
4971 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004972 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
4973 mWriteAckSequence, mDrainSequence);
4974 writeAckSequence = mWriteAckSequence;
4975 mWriteAckSequence &= ~1;
4976 drainSequence = mDrainSequence;
4977 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004978 }
4979 {
Eric Laurent4de95592013-09-26 15:28:21 -07004980 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
4981 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004982 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004983 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004984 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004985 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004986 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004987 }
4988 }
4989 }
4990 }
4991 return false;
4992}
4993
4994void AudioFlinger::AsyncCallbackThread::exit()
4995{
4996 ALOGV("AsyncCallbackThread::exit");
4997 Mutex::Autolock _l(mLock);
4998 requestExit();
4999 mWaitWorkCV.broadcast();
5000}
5001
Eric Laurent3b4529e2013-09-05 18:09:19 -07005002void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005003{
5004 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005005 // bit 0 is cleared
5006 mWriteAckSequence = sequence << 1;
5007}
5008
5009void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
5010{
5011 Mutex::Autolock _l(mLock);
5012 // ignore unexpected callbacks
5013 if (mWriteAckSequence & 2) {
5014 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005015 mWaitWorkCV.signal();
5016 }
5017}
5018
Eric Laurent3b4529e2013-09-05 18:09:19 -07005019void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005020{
5021 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005022 // bit 0 is cleared
5023 mDrainSequence = sequence << 1;
5024}
5025
5026void AudioFlinger::AsyncCallbackThread::resetDraining()
5027{
5028 Mutex::Autolock _l(mLock);
5029 // ignore unexpected callbacks
5030 if (mDrainSequence & 2) {
5031 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005032 mWaitWorkCV.signal();
5033 }
5034}
5035
5036
5037// ----------------------------------------------------------------------------
5038AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07005039 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady)
5040 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady),
Eric Laurentd7e59222013-11-15 12:02:28 -08005041 mPausedBytesRemaining(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005042{
Eric Laurentfd477972013-10-25 18:10:40 -07005043 //FIXME: mStandby should be set to true by ThreadBase constructor
5044 mStandby = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005045}
5046
Eric Laurentbfb1b832013-01-07 09:53:42 -08005047void AudioFlinger::OffloadThread::threadLoop_exit()
5048{
5049 if (mFlushPending || mHwPaused) {
5050 // If a flush is pending or track was paused, just discard buffered data
5051 flushHw_l();
5052 } else {
5053 mMixerStatus = MIXER_DRAIN_ALL;
5054 threadLoop_drain();
5055 }
Uday Gupta56604aa2014-05-13 11:19:17 -07005056 if (mUseAsyncWrite) {
5057 ALOG_ASSERT(mCallbackThread != 0);
5058 mCallbackThread->exit();
5059 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005060 PlaybackThread::threadLoop_exit();
5061}
5062
5063AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
5064 Vector< sp<Track> > *tracksToRemove
5065)
5066{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005067 size_t count = mActiveTracks.size();
5068
5069 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07005070 bool doHwPause = false;
5071 bool doHwResume = false;
5072
Eric Laurentede6c3b2013-09-19 14:37:46 -07005073 ALOGV("OffloadThread::prepareTracks_l active tracks %d", count);
5074
Eric Laurentbfb1b832013-01-07 09:53:42 -08005075 // find out which tracks need to be processed
5076 for (size_t i = 0; i < count; i++) {
5077 sp<Track> t = mActiveTracks[i].promote();
5078 // The track died recently
5079 if (t == 0) {
5080 continue;
5081 }
5082 Track* const track = t.get();
5083 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07005084 // Only consider last track started for volume and mixer state control.
5085 // In theory an older track could underrun and restart after the new one starts
5086 // but as we only care about the transition phase between two tracks on a
5087 // direct output, it is not a problem to ignore the underrun case.
5088 sp<Track> l = mLatestActiveTrack.promote();
5089 bool last = l.get() == track;
5090
Haynes Mathew George7844f672014-01-15 12:32:55 -08005091 if (track->isInvalid()) {
5092 ALOGW("An invalidated track shouldn't be in active list");
5093 tracksToRemove->add(track);
5094 continue;
5095 }
5096
5097 if (track->mState == TrackBase::IDLE) {
5098 ALOGW("An idle track shouldn't be in active list");
5099 continue;
5100 }
5101
Eric Laurentbfb1b832013-01-07 09:53:42 -08005102 if (track->isPausing()) {
5103 track->setPaused();
5104 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07005105 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07005106 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005107 mHwPaused = true;
5108 }
5109 // If we were part way through writing the mixbuffer to
5110 // the HAL we must save this until we resume
5111 // BUG - this will be wrong if a different track is made active,
5112 // in that case we want to discard the pending data in the
5113 // mixbuffer and tell the client to present it again when the
5114 // track is resumed
5115 mPausedWriteLength = mCurrentWriteLength;
5116 mPausedBytesRemaining = mBytesRemaining;
5117 mBytesRemaining = 0; // stop writing
5118 }
5119 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08005120 } else if (track->isFlushPending()) {
5121 track->flushAck();
5122 if (last) {
5123 mFlushPending = true;
5124 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005125 } else if (track->isResumePending()){
5126 track->resumeAck();
5127 if (last) {
5128 if (mPausedBytesRemaining) {
5129 // Need to continue write that was interrupted
5130 mCurrentWriteLength = mPausedWriteLength;
5131 mBytesRemaining = mPausedBytesRemaining;
5132 mPausedBytesRemaining = 0;
5133 }
5134 if (mHwPaused) {
5135 doHwResume = true;
5136 mHwPaused = false;
5137 // threadLoop_mix() will handle the case that we need to
5138 // resume an interrupted write
5139 }
5140 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005141 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005142
5143 // Do not handle new data in this iteration even if track->framesReady()
5144 mixerStatus = MIXER_TRACKS_ENABLED;
5145 }
5146 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07005147 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005148 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005149 if (track->mFillingUpStatus == Track::FS_FILLED) {
5150 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07005151 // make sure processVolume_l() will apply new volume even if 0
5152 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005153 }
5154
5155 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08005156 sp<Track> previousTrack = mPreviousTrack.promote();
5157 if (previousTrack != 0) {
5158 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08005159 // Flush any data still being written from last track
5160 mBytesRemaining = 0;
5161 if (mPausedBytesRemaining) {
5162 // Last track was paused so we also need to flush saved
5163 // mixbuffer state and invalidate track so that it will
5164 // re-submit that unwritten data when it is next resumed
5165 mPausedBytesRemaining = 0;
5166 // Invalidate is a bit drastic - would be more efficient
5167 // to have a flag to tell client that some of the
5168 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08005169 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005170 }
5171 // flush data already sent to the DSP if changing audio session as audio
5172 // comes from a different source. Also invalidate previous track to force a
5173 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08005174 if (previousTrack->sessionId() != track->sessionId()) {
5175 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005176 }
5177 }
5178 }
5179 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005180 // reset retry count
5181 track->mRetryCount = kMaxTrackRetriesOffload;
5182 mActiveTrack = t;
5183 mixerStatus = MIXER_TRACKS_READY;
5184 }
5185 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005186 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005187 if (track->isStopping_1()) {
5188 // Hardware buffer can hold a large amount of audio so we must
5189 // wait for all current track's data to drain before we say
5190 // that the track is stopped.
5191 if (mBytesRemaining == 0) {
5192 // Only start draining when all data in mixbuffer
5193 // has been written
5194 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
5195 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005196 // do not drain if no data was ever sent to HAL (mStandby == true)
5197 if (last && !mStandby) {
Eric Laurent1b9f9b12013-11-12 19:10:17 -08005198 // do not modify drain sequence if we are already draining. This happens
5199 // when resuming from pause after drain.
5200 if ((mDrainSequence & 1) == 0) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005201 mSleepTimeUs = 0;
5202 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent1b9f9b12013-11-12 19:10:17 -08005203 mixerStatus = MIXER_DRAIN_TRACK;
5204 mDrainSequence += 2;
5205 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005206 if (mHwPaused) {
5207 // It is possible to move from PAUSED to STOPPING_1 without
5208 // a resume so we must ensure hardware is running
Eric Laurent1b9f9b12013-11-12 19:10:17 -08005209 doHwResume = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005210 mHwPaused = false;
5211 }
5212 }
5213 }
5214 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005215 // Drain has completed or we are in standby, signal presentation complete
5216 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005217 track->mState = TrackBase::STOPPED;
5218 size_t audioHALFrames =
5219 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
5220 size_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08005221 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005222 track->presentationComplete(framesWritten, audioHALFrames);
5223 track->reset();
5224 tracksToRemove->add(track);
5225 }
5226 } else {
5227 // No buffers for this track. Give it a few chances to
5228 // fill a buffer, then remove it from active list.
5229 if (--(track->mRetryCount) <= 0) {
5230 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
5231 track->name());
5232 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08005233 // indicate to client process that the track was disabled because of underrun;
5234 // it will then automatically call start() when data is available
5235 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005236 } else if (last){
5237 mixerStatus = MIXER_TRACKS_ENABLED;
5238 }
5239 }
5240 }
5241 // compute volume for this track
5242 processVolume_l(track, last);
5243 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005244
Eric Laurentea0fade2013-10-04 16:23:48 -07005245 // make sure the pause/flush/resume sequence is executed in the right order.
5246 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5247 // before flush and then resume HW. This can happen in case of pause/flush/resume
5248 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07005249 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurent972a1732013-09-04 09:42:59 -07005250 mOutput->stream->pause(mOutput->stream);
5251 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005252 if (mFlushPending) {
5253 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005254 }
Eric Laurentfd477972013-10-25 18:10:40 -07005255 if (!mStandby && doHwResume) {
Eric Laurent972a1732013-09-04 09:42:59 -07005256 mOutput->stream->resume(mOutput->stream);
5257 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005258
Eric Laurentbfb1b832013-01-07 09:53:42 -08005259 // remove all the tracks that need to be...
5260 removeTracks_l(*tracksToRemove);
5261
5262 return mixerStatus;
5263}
5264
Eric Laurentbfb1b832013-01-07 09:53:42 -08005265// must be called with thread mutex locked
5266bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
5267{
Eric Laurent3b4529e2013-09-05 18:09:19 -07005268 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
5269 mWriteAckSequence, mDrainSequence);
5270 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005271 return true;
5272 }
5273 return false;
5274}
5275
Eric Laurentbfb1b832013-01-07 09:53:42 -08005276bool AudioFlinger::OffloadThread::waitingAsyncCallback()
5277{
5278 Mutex::Autolock _l(mLock);
5279 return waitingAsyncCallback_l();
5280}
5281
5282void AudioFlinger::OffloadThread::flushHw_l()
5283{
Eric Laurente659ef42014-09-29 13:06:46 -07005284 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005285 // Flush anything still waiting in the mixbuffer
5286 mCurrentWriteLength = 0;
5287 mBytesRemaining = 0;
5288 mPausedWriteLength = 0;
5289 mPausedBytesRemaining = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08005290
Eric Laurentbfb1b832013-01-07 09:53:42 -08005291 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005292 // discard any pending drain or write ack by incrementing sequence
5293 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5294 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005295 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005296 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5297 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005298 }
5299}
5300
5301// ----------------------------------------------------------------------------
5302
Eric Laurent81784c32012-11-19 14:55:58 -08005303AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07005304 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08005305 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
Eric Laurent72e3f392015-05-20 14:43:50 -07005306 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08005307 mWaitTimeMs(UINT_MAX)
5308{
5309 addOutputTrack(mainThread);
5310}
5311
5312AudioFlinger::DuplicatingThread::~DuplicatingThread()
5313{
5314 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5315 mOutputTracks[i]->destroy();
5316 }
5317}
5318
5319void AudioFlinger::DuplicatingThread::threadLoop_mix()
5320{
5321 // mix buffers...
5322 if (outputsReady(outputTracks)) {
5323 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
5324 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08005325 if (mMixerBufferValid) {
5326 memset(mMixerBuffer, 0, mMixerBufferSize);
5327 } else {
5328 memset(mSinkBuffer, 0, mSinkBufferSize);
5329 }
Eric Laurent81784c32012-11-19 14:55:58 -08005330 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005331 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005332 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005333 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005334 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005335}
5336
5337void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
5338{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005339 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005340 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005341 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005342 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005343 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005344 }
5345 } else if (mBytesWritten != 0) {
5346 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5347 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005348 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005349 } else {
5350 // flush remaining overflow buffers in output tracks
5351 writeFrames = 0;
5352 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005353 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005354 }
5355}
5356
Eric Laurentbfb1b832013-01-07 09:53:42 -08005357ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005358{
5359 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08005360 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005361 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07005362 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08005363 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005364}
5365
5366void AudioFlinger::DuplicatingThread::threadLoop_standby()
5367{
5368 // DuplicatingThread implements standby by stopping all tracks
5369 for (size_t i = 0; i < outputTracks.size(); i++) {
5370 outputTracks[i]->stop();
5371 }
5372}
5373
5374void AudioFlinger::DuplicatingThread::saveOutputTracks()
5375{
5376 outputTracks = mOutputTracks;
5377}
5378
5379void AudioFlinger::DuplicatingThread::clearOutputTracks()
5380{
5381 outputTracks.clear();
5382}
5383
5384void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
5385{
5386 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08005387 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
5388 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
5389 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
5390 const size_t frameCount =
5391 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
5392 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
5393 // from different OutputTracks and their associated MixerThreads (e.g. one may
5394 // nearly empty and the other may be dropping data).
5395
5396 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08005397 this,
5398 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08005399 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08005400 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005401 frameCount,
5402 IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08005403 if (outputTrack->cblk() != NULL) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005404 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
Eric Laurent81784c32012-11-19 14:55:58 -08005405 mOutputTracks.add(outputTrack);
Andy Hungc25b84a2015-01-14 19:04:10 -08005406 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005407 updateWaitTime_l();
5408 }
5409}
5410
5411void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
5412{
5413 Mutex::Autolock _l(mLock);
5414 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5415 if (mOutputTracks[i]->thread() == thread) {
5416 mOutputTracks[i]->destroy();
5417 mOutputTracks.removeAt(i);
5418 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07005419 if (thread->getOutput() == mOutput) {
5420 mOutput = NULL;
5421 }
Eric Laurent81784c32012-11-19 14:55:58 -08005422 return;
5423 }
5424 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07005425 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005426}
5427
5428// caller must hold mLock
5429void AudioFlinger::DuplicatingThread::updateWaitTime_l()
5430{
5431 mWaitTimeMs = UINT_MAX;
5432 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5433 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
5434 if (strong != 0) {
5435 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
5436 if (waitTimeMs < mWaitTimeMs) {
5437 mWaitTimeMs = waitTimeMs;
5438 }
5439 }
5440 }
5441}
5442
5443
5444bool AudioFlinger::DuplicatingThread::outputsReady(
5445 const SortedVector< sp<OutputTrack> > &outputTracks)
5446{
5447 for (size_t i = 0; i < outputTracks.size(); i++) {
5448 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
5449 if (thread == 0) {
5450 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
5451 outputTracks[i].get());
5452 return false;
5453 }
5454 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5455 // see note at standby() declaration
5456 if (playbackThread->standby() && !playbackThread->isSuspended()) {
5457 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
5458 thread.get());
5459 return false;
5460 }
5461 }
5462 return true;
5463}
5464
5465uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
5466{
5467 return (mWaitTimeMs * 1000) / 2;
5468}
5469
5470void AudioFlinger::DuplicatingThread::cacheParameters_l()
5471{
5472 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
5473 updateWaitTime_l();
5474
5475 MixerThread::cacheParameters_l();
5476}
5477
5478// ----------------------------------------------------------------------------
5479// Record
5480// ----------------------------------------------------------------------------
5481
5482AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5483 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08005484 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08005485 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07005486 audio_devices_t inDevice,
5487 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08005488#ifdef TEE_SINK
5489 , const sp<NBAIO_Sink>& teeSink
5490#endif
5491 ) :
Eric Laurent72e3f392015-05-20 14:43:50 -07005492 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005493 mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005494 // mRsmpInFrames and mRsmpInFramesP2 are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005495 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08005496#ifdef TEE_SINK
5497 , mTeeSink(teeSink)
5498#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07005499 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
5500 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005501 // mFastCapture below
5502 , mFastCaptureFutex(0)
5503 // mInputSource
5504 // mPipeSink
5505 // mPipeSource
5506 , mPipeFramesP2(0)
5507 // mPipeMemory
5508 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005509 , mFastTrackAvail(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005510{
Glenn Kastend7dca052015-03-05 16:05:54 -08005511 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
5512 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08005513
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005514 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005515
5516 // create an NBAIO source for the HAL input stream, and negotiate
5517 mInputSource = new AudioStreamInSource(input->stream);
5518 size_t numCounterOffers = 0;
5519 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
5520 ssize_t index = mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
5521 ALOG_ASSERT(index == 0);
5522
5523 // initialize fast capture depending on configuration
5524 bool initFastCapture;
5525 switch (kUseFastCapture) {
5526 case FastCapture_Never:
5527 initFastCapture = false;
5528 break;
5529 case FastCapture_Always:
5530 initFastCapture = true;
5531 break;
5532 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07005533 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005534 break;
5535 // case FastCapture_Dynamic:
5536 }
5537
5538 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07005539 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005540 NBAIO_Format format = mInputSource->format();
Glenn Kasten49d00ad2014-07-21 11:22:03 -07005541 size_t pipeFramesP2 = roundup(mSampleRate / 25); // double-buffering of 20 ms each
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005542 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
5543 void *pipeBuffer;
5544 const sp<MemoryDealer> roHeap(readOnlyHeap());
5545 sp<IMemory> pipeMemory;
5546 if ((roHeap == 0) ||
5547 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
5548 (pipeBuffer = pipeMemory->pointer()) == NULL) {
5549 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
5550 goto failed;
5551 }
5552 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
5553 memset(pipeBuffer, 0, pipeSize);
5554 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
5555 const NBAIO_Format offers[1] = {format};
5556 size_t numCounterOffers = 0;
5557 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
5558 ALOG_ASSERT(index == 0);
5559 mPipeSink = pipe;
5560 PipeReader *pipeReader = new PipeReader(*pipe);
5561 numCounterOffers = 0;
5562 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
5563 ALOG_ASSERT(index == 0);
5564 mPipeSource = pipeReader;
5565 mPipeFramesP2 = pipeFramesP2;
5566 mPipeMemory = pipeMemory;
5567
5568 // create fast capture
5569 mFastCapture = new FastCapture();
5570 FastCaptureStateQueue *sq = mFastCapture->sq();
5571#ifdef STATE_QUEUE_DUMP
5572 // FIXME
5573#endif
5574 FastCaptureState *state = sq->begin();
5575 state->mCblk = NULL;
5576 state->mInputSource = mInputSource.get();
5577 state->mInputSourceGen++;
5578 state->mPipeSink = pipe;
5579 state->mPipeSinkGen++;
5580 state->mFrameCount = mFrameCount;
5581 state->mCommand = FastCaptureState::COLD_IDLE;
5582 // already done in constructor initialization list
5583 //mFastCaptureFutex = 0;
5584 state->mColdFutexAddr = &mFastCaptureFutex;
5585 state->mColdGen++;
5586 state->mDumpState = &mFastCaptureDumpState;
5587#ifdef TEE_SINK
5588 // FIXME
5589#endif
5590 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
5591 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
5592 sq->end();
5593 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5594
5595 // start the fast capture
5596 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
5597 pid_t tid = mFastCapture->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07005598 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005599#ifdef AUDIO_WATCHDOG
5600 // FIXME
5601#endif
5602
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005603 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005604 }
5605failed: ;
5606
5607 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08005608}
5609
Eric Laurent81784c32012-11-19 14:55:58 -08005610AudioFlinger::RecordThread::~RecordThread()
5611{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005612 if (mFastCapture != 0) {
5613 FastCaptureStateQueue *sq = mFastCapture->sq();
5614 FastCaptureState *state = sq->begin();
5615 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5616 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5617 if (old == -1) {
5618 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5619 }
5620 }
5621 state->mCommand = FastCaptureState::EXIT;
5622 sq->end();
5623 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5624 mFastCapture->join();
5625 mFastCapture.clear();
5626 }
5627 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07005628 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07005629 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08005630}
5631
5632void AudioFlinger::RecordThread::onFirstRef()
5633{
Glenn Kastend7dca052015-03-05 16:05:54 -08005634 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08005635}
5636
Eric Laurent81784c32012-11-19 14:55:58 -08005637bool AudioFlinger::RecordThread::threadLoop()
5638{
Eric Laurent81784c32012-11-19 14:55:58 -08005639 nsecs_t lastWarning = 0;
5640
5641 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08005642
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005643reacquire_wakelock:
5644 sp<RecordTrack> activeTrack;
Glenn Kasten2b806402013-11-20 16:37:38 -08005645 int activeTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005646 {
5647 Mutex::Autolock _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005648 size_t size = mActiveTracks.size();
5649 activeTracksGen = mActiveTracksGen;
5650 if (size > 0) {
5651 // FIXME an arbitrary choice
5652 activeTrack = mActiveTracks[0];
5653 acquireWakeLock_l(activeTrack->uid());
5654 if (size > 1) {
5655 SortedVector<int> tmp;
5656 for (size_t i = 0; i < size; i++) {
5657 tmp.add(mActiveTracks[i]->uid());
5658 }
5659 updateWakeLockUids_l(tmp);
5660 }
5661 } else {
5662 acquireWakeLock_l(-1);
5663 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005664 }
5665
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005666 // used to request a deferred sleep, to be executed later while mutex is unlocked
5667 uint32_t sleepUs = 0;
5668
5669 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005670 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005671 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07005672
Glenn Kasten5edadd42013-08-14 16:30:49 -07005673 // sleep with mutex unlocked
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005674 if (sleepUs > 0) {
Glenn Kastene7754022014-10-31 12:11:26 -07005675 ATRACE_BEGIN("sleep");
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005676 usleep(sleepUs);
Glenn Kastene7754022014-10-31 12:11:26 -07005677 ATRACE_END();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005678 sleepUs = 0;
Glenn Kasten5edadd42013-08-14 16:30:49 -07005679 }
5680
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005681 // activeTracks accumulates a copy of a subset of mActiveTracks
5682 Vector< sp<RecordTrack> > activeTracks;
5683
Glenn Kasten735f45f2014-08-18 15:51:59 -07005684 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005685 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07005686
Glenn Kasten735f45f2014-08-18 15:51:59 -07005687 // reference to a fast track which is about to be removed
5688 sp<RecordTrack> fastTrackToRemove;
5689
Eric Laurent81784c32012-11-19 14:55:58 -08005690 { // scope for mLock
5691 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08005692
Eric Laurent021cf962014-05-13 10:18:14 -07005693 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005694
Eric Laurent000a4192014-01-29 15:17:32 -08005695 // check exitPending here because checkForNewParameters_l() and
5696 // checkForNewParameters_l() can temporarily release mLock
5697 if (exitPending()) {
5698 break;
5699 }
5700
Glenn Kasten2b806402013-11-20 16:37:38 -08005701 // if no active track(s), then standby and release wakelock
5702 size_t size = mActiveTracks.size();
5703 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07005704 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005705 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08005706 releaseWakeLock_l();
5707 ALOGV("RecordThread: loop stopping");
5708 // go to sleep
5709 mWaitWorkCV.wait(mLock);
5710 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005711 goto reacquire_wakelock;
5712 }
5713
Glenn Kasten2b806402013-11-20 16:37:38 -08005714 if (mActiveTracksGen != activeTracksGen) {
5715 activeTracksGen = mActiveTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005716 SortedVector<int> tmp;
Glenn Kasten2b806402013-11-20 16:37:38 -08005717 for (size_t i = 0; i < size; i++) {
5718 tmp.add(mActiveTracks[i]->uid());
5719 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005720 updateWakeLockUids_l(tmp);
Eric Laurent81784c32012-11-19 14:55:58 -08005721 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005722
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005723 bool doBroadcast = false;
5724 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07005725
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005726 activeTrack = mActiveTracks[i];
5727 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07005728 if (activeTrack->isFastTrack()) {
5729 ALOG_ASSERT(fastTrackToRemove == 0);
5730 fastTrackToRemove = activeTrack;
5731 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005732 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08005733 mActiveTracks.remove(activeTrack);
5734 mActiveTracksGen++;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005735 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07005736 continue;
5737 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005738
5739 TrackBase::track_state activeTrackState = activeTrack->mState;
5740 switch (activeTrackState) {
5741
5742 case TrackBase::PAUSING:
5743 mActiveTracks.remove(activeTrack);
5744 mActiveTracksGen++;
5745 doBroadcast = true;
5746 size--;
5747 continue;
5748
5749 case TrackBase::STARTING_1:
5750 sleepUs = 10000;
5751 i++;
5752 continue;
5753
5754 case TrackBase::STARTING_2:
5755 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005756 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07005757 activeTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005758 break;
5759
5760 case TrackBase::ACTIVE:
5761 break;
5762
5763 case TrackBase::IDLE:
5764 i++;
5765 continue;
5766
5767 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08005768 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07005769 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005770
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005771 activeTracks.add(activeTrack);
5772 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07005773
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005774 if (activeTrack->isFastTrack()) {
5775 ALOG_ASSERT(!mFastTrackAvail);
5776 ALOG_ASSERT(fastTrack == 0);
5777 fastTrack = activeTrack;
5778 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005779 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005780 if (doBroadcast) {
5781 mStartStopCond.broadcast();
5782 }
5783
5784 // sleep if there are no active tracks to process
5785 if (activeTracks.size() == 0) {
5786 if (sleepUs == 0) {
5787 sleepUs = kRecordThreadSleepUs;
5788 }
5789 continue;
5790 }
5791 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07005792
Eric Laurent81784c32012-11-19 14:55:58 -08005793 lockEffectChains_l(effectChains);
5794 }
5795
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005796 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07005797
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005798 size_t size = effectChains.size();
5799 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005800 // thread mutex is not locked, but effect chain is locked
5801 effectChains[i]->process_l();
5802 }
5803
Glenn Kasten735f45f2014-08-18 15:51:59 -07005804 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005805 if (mFastCapture != 0) {
5806 FastCaptureStateQueue *sq = mFastCapture->sq();
5807 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07005808 bool didModify = false;
5809 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005810 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
5811 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
5812 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5813 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5814 if (old == -1) {
5815 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5816 }
5817 }
5818 state->mCommand = FastCaptureState::READ_WRITE;
5819#if 0 // FIXME
5820 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08005821 FastThreadDumpState::kSamplingNforLowRamDevice :
5822 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005823#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07005824 didModify = true;
5825 }
5826 audio_track_cblk_t *cblkOld = state->mCblk;
5827 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
5828 if (cblkNew != cblkOld) {
5829 state->mCblk = cblkNew;
5830 // block until acked if removing a fast track
5831 if (cblkOld != NULL) {
5832 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
5833 }
5834 didModify = true;
5835 }
5836 sq->end(didModify);
5837 if (didModify) {
5838 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005839#if 0
5840 if (kUseFastCapture == FastCapture_Dynamic) {
5841 mNormalSource = mPipeSource;
5842 }
5843#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005844 }
5845 }
5846
Glenn Kasten735f45f2014-08-18 15:51:59 -07005847 // now run the fast track destructor with thread mutex unlocked
5848 fastTrackToRemove.clear();
5849
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005850 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
5851 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
5852 // slow, then this RecordThread will overrun by not calling HAL read often enough.
5853 // If destination is non-contiguous, first read past the nominal end of buffer, then
5854 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005855
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005856 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005857 ssize_t framesRead;
5858
5859 // If an NBAIO source is present, use it to read the normal capture's data
5860 if (mPipeSource != 0) {
5861 size_t framesToRead = mBufferSize / mFrameSize;
Andy Hung57446612015-04-19 23:56:46 -07005862 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005863 framesToRead, AudioBufferProvider::kInvalidPTS);
5864 if (framesRead == 0) {
5865 // since pipe is non-blocking, simulate blocking input
5866 sleepUs = (framesToRead * 1000000LL) / mSampleRate;
5867 }
5868 // otherwise use the HAL / AudioStreamIn directly
5869 } else {
5870 ssize_t bytesRead = mInput->stream->read(mInput->stream,
Andy Hung57446612015-04-19 23:56:46 -07005871 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005872 if (bytesRead < 0) {
5873 framesRead = bytesRead;
5874 } else {
5875 framesRead = bytesRead / mFrameSize;
5876 }
5877 }
5878
5879 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
5880 ALOGE("read failed: framesRead=%d", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005881 // Force input into standby so that it tries to recover at next read attempt
5882 inputStandBy();
5883 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005884 }
5885 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005886 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005887 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005888 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005889
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005890 if (mTeeSink != 0) {
Andy Hung57446612015-04-19 23:56:46 -07005891 (void) mTeeSink->write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005892 }
5893 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005894 {
5895 size_t part1 = mRsmpInFramesP2 - rear;
5896 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07005897 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005898 (framesRead - part1) * mFrameSize);
5899 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005900 }
5901 rear = mRsmpInRear += framesRead;
5902
5903 size = activeTracks.size();
5904 // loop over each active track
5905 for (size_t i = 0; i < size; i++) {
5906 activeTrack = activeTracks[i];
5907
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005908 // skip fast tracks, as those are handled directly by FastCapture
5909 if (activeTrack->isFastTrack()) {
5910 continue;
5911 }
5912
Andy Hung73c02e42015-03-29 01:13:58 -07005913 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07005914 // TODO: Update the activeTrack buffer converter in case of reconfigure.
5915
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005916 enum {
5917 OVERRUN_UNKNOWN,
5918 OVERRUN_TRUE,
5919 OVERRUN_FALSE
5920 } overrun = OVERRUN_UNKNOWN;
5921
5922 // loop over getNextBuffer to handle circular sink
5923 for (;;) {
5924
5925 activeTrack->mSink.frameCount = ~0;
5926 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
5927 size_t framesOut = activeTrack->mSink.frameCount;
5928 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
5929
Andy Hung73c02e42015-03-29 01:13:58 -07005930 // check available frames and handle overrun conditions
5931 // if the record track isn't draining fast enough.
5932 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005933 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07005934 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
5935 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005936 overrun = OVERRUN_TRUE;
5937 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005938 if (framesOut == 0 || framesIn == 0) {
5939 break;
5940 }
5941
Andy Hung6770c6f2015-04-07 13:43:36 -07005942 // Don't allow framesOut to be larger than what is possible with resampling
5943 // from framesIn.
5944 // This isn't strictly necessary but helps limit buffer resizing in
5945 // RecordBufferConverter. TODO: remove when no longer needed.
5946 framesOut = min(framesOut,
5947 destinationFramesPossible(
5948 framesIn, mSampleRate, activeTrack->mSampleRate));
Andy Hung97a893e2015-03-29 01:03:07 -07005949 // process frames from the RecordThread buffer provider to the RecordTrack buffer
5950 framesOut = activeTrack->mRecordBufferConverter->convert(
5951 activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005952
5953 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
5954 overrun = OVERRUN_FALSE;
5955 }
5956
5957 if (activeTrack->mFramesToDrop == 0) {
5958 if (framesOut > 0) {
5959 activeTrack->mSink.frameCount = framesOut;
5960 activeTrack->releaseBuffer(&activeTrack->mSink);
5961 }
5962 } else {
5963 // FIXME could do a partial drop of framesOut
5964 if (activeTrack->mFramesToDrop > 0) {
5965 activeTrack->mFramesToDrop -= framesOut;
5966 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005967 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005968 }
5969 } else {
5970 activeTrack->mFramesToDrop += framesOut;
5971 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
5972 activeTrack->mSyncStartEvent->isCancelled()) {
5973 ALOGW("Synced record %s, session %d, trigger session %d",
5974 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
5975 activeTrack->sessionId(),
5976 (activeTrack->mSyncStartEvent != 0) ?
5977 activeTrack->mSyncStartEvent->triggerSession() : 0);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005978 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005979 }
5980 }
5981 }
5982
5983 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005984 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005985 }
5986 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005987
5988 switch (overrun) {
5989 case OVERRUN_TRUE:
5990 // client isn't retrieving buffers fast enough
5991 if (!activeTrack->setOverflow()) {
5992 nsecs_t now = systemTime();
5993 // FIXME should lastWarning per track?
5994 if ((now - lastWarning) > kWarningThrottleNs) {
5995 ALOGW("RecordThread: buffer overflow");
5996 lastWarning = now;
5997 }
5998 }
5999 break;
6000 case OVERRUN_FALSE:
6001 activeTrack->clearOverflow();
6002 break;
6003 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006004 break;
6005 }
6006
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006007 }
6008
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006009unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08006010 // enable changes in effect chain
6011 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006012 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08006013 }
6014
Glenn Kasten93e471f2013-08-19 08:40:07 -07006015 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08006016
6017 {
6018 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07006019 for (size_t i = 0; i < mTracks.size(); i++) {
6020 sp<RecordTrack> track = mTracks[i];
6021 track->invalidate();
6022 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006023 mActiveTracks.clear();
6024 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08006025 mStartStopCond.broadcast();
6026 }
6027
6028 releaseWakeLock();
6029
6030 ALOGV("RecordThread %p exiting", this);
6031 return false;
6032}
6033
Glenn Kasten93e471f2013-08-19 08:40:07 -07006034void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08006035{
6036 if (!mStandby) {
6037 inputStandBy();
6038 mStandby = true;
6039 }
6040}
6041
6042void AudioFlinger::RecordThread::inputStandBy()
6043{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006044 // Idle the fast capture if it's currently running
6045 if (mFastCapture != 0) {
6046 FastCaptureStateQueue *sq = mFastCapture->sq();
6047 FastCaptureState *state = sq->begin();
6048 if (!(state->mCommand & FastCaptureState::IDLE)) {
6049 state->mCommand = FastCaptureState::COLD_IDLE;
6050 state->mColdFutexAddr = &mFastCaptureFutex;
6051 state->mColdGen++;
6052 mFastCaptureFutex = 0;
6053 sq->end();
6054 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
6055 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
6056#if 0
6057 if (kUseFastCapture == FastCapture_Dynamic) {
6058 // FIXME
6059 }
6060#endif
6061#ifdef AUDIO_WATCHDOG
6062 // FIXME
6063#endif
6064 } else {
6065 sq->end(false /*didModify*/);
6066 }
6067 }
Eric Laurent81784c32012-11-19 14:55:58 -08006068 mInput->stream->common.standby(&mInput->stream->common);
6069}
6070
Glenn Kasten05997e22014-03-13 15:08:33 -07006071// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07006072sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08006073 const sp<AudioFlinger::Client>& client,
6074 uint32_t sampleRate,
6075 audio_format_t format,
6076 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08006077 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08006078 int sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07006079 size_t *notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08006080 int uid,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07006081 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08006082 pid_t tid,
6083 status_t *status)
6084{
Glenn Kasten74935e42013-12-19 08:56:45 -08006085 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08006086 sp<RecordTrack> track;
6087 status_t lStatus;
6088
Glenn Kasten90e58b12013-07-31 16:16:02 -07006089 // client expresses a preference for FAST, but we get the final say
6090 if (*flags & IAudioFlinger::TRACK_FAST) {
6091 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07006092 // we formerly checked for a callback handler (non-0 tid),
6093 // but that is no longer required for TRANSFER_OBTAIN mode
6094 //
Glenn Kasten74105912014-07-03 12:28:53 -07006095 // frame count is not specified, or is exactly the pipe depth
6096 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006097 // PCM data
6098 audio_is_linear_pcm(format) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006099 // native format
6100 (format == mFormat) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006101 // native channel mask
6102 (channelMask == mChannelMask) &&
6103 // native hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07006104 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006105 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006106 hasFastCapture() &&
6107 // there are sufficient fast track slots available
6108 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07006109 ) {
Glenn Kasten74105912014-07-03 12:28:53 -07006110 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%u mFrameCount=%u",
Glenn Kasten90e58b12013-07-31 16:16:02 -07006111 frameCount, mFrameCount);
6112 } else {
Glenn Kasten74105912014-07-03 12:28:53 -07006113 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%u mFrameCount=%u mPipeFramesP2=%u "
6114 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006115 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Glenn Kasten74105912014-07-03 12:28:53 -07006116 frameCount, mFrameCount, mPipeFramesP2,
6117 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
6118 hasFastCapture(), tid, mFastTrackAvail);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006119 *flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kasten74105912014-07-03 12:28:53 -07006120 }
6121 }
6122
6123 // compute track buffer size in frames, and suggest the notification frame count
6124 if (*flags & IAudioFlinger::TRACK_FAST) {
6125 // fast track: frame count is exactly the pipe depth
6126 frameCount = mPipeFramesP2;
6127 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
6128 *notificationFrames = mFrameCount;
6129 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006130 // not fast track: max notification period is resampled equivalent of one HAL buffer time
6131 // or 20 ms if there is a fast capture
6132 // TODO This could be a roundupRatio inline, and const
6133 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
6134 * sampleRate + mSampleRate - 1) / mSampleRate;
6135 // minimum number of notification periods is at least kMinNotifications,
6136 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
6137 static const size_t kMinNotifications = 3;
6138 static const uint32_t kMinMs = 30;
6139 // TODO This could be a roundupRatio inline
6140 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
6141 // TODO This could be a roundupRatio inline
6142 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
6143 maxNotificationFrames;
6144 const size_t minFrameCount = maxNotificationFrames *
6145 max(kMinNotifications, minNotificationsByMs);
6146 frameCount = max(frameCount, minFrameCount);
6147 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
6148 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07006149 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07006150 }
Glenn Kasten74935e42013-12-19 08:56:45 -08006151 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07006152
Glenn Kasten15e57982013-09-24 11:52:37 -07006153 lStatus = initCheck();
6154 if (lStatus != NO_ERROR) {
6155 ALOGE("createRecordTrack_l() audio driver not initialized");
6156 goto Exit;
6157 }
Eric Laurent81784c32012-11-19 14:55:58 -08006158
6159 { // scope for mLock
6160 Mutex::Autolock _l(mLock);
6161
6162 track = new RecordTrack(this, client, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07006163 format, channelMask, frameCount, NULL, sessionId, uid,
6164 *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08006165
Glenn Kasten03003332013-08-06 15:40:54 -07006166 lStatus = track->initCheck();
6167 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07006168 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08006169 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08006170 goto Exit;
6171 }
6172 mTracks.add(track);
6173
6174 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6175 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6176 mAudioFlinger->btNrecIsOff();
6177 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6178 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006179
6180 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
6181 pid_t callingPid = IPCThreadState::self()->getCallingPid();
6182 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
6183 // so ask activity manager to do this on our behalf
6184 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
6185 }
Eric Laurent81784c32012-11-19 14:55:58 -08006186 }
Glenn Kasten05997e22014-03-13 15:08:33 -07006187
Eric Laurent81784c32012-11-19 14:55:58 -08006188 lStatus = NO_ERROR;
6189
6190Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07006191 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08006192 return track;
6193}
6194
6195status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
6196 AudioSystem::sync_event_t event,
6197 int triggerSession)
6198{
6199 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
6200 sp<ThreadBase> strongMe = this;
6201 status_t status = NO_ERROR;
6202
6203 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006204 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006205 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006206 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08006207 triggerSession,
6208 recordTrack->sessionId(),
6209 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006210 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08006211 // Sync event can be cancelled by the trigger session if the track is not in a
6212 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006213 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006214 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006215 } else {
6216 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006217 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006218 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08006219 }
6220 }
6221
6222 {
Glenn Kasten47c20702013-08-13 15:37:35 -07006223 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08006224 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006225 if (mActiveTracks.indexOf(recordTrack) >= 0) {
6226 if (recordTrack->mState == TrackBase::PAUSING) {
6227 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006228 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006229 } else {
6230 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08006231 }
6232 return status;
6233 }
6234
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006235 // TODO consider other ways of handling this, such as changing the state to :STARTING and
6236 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
6237 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006238 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08006239 mActiveTracks.add(recordTrack);
6240 mActiveTracksGen++;
Eric Laurent83b88082014-06-20 18:31:16 -07006241 status_t status = NO_ERROR;
6242 if (recordTrack->isExternalTrack()) {
6243 mLock.unlock();
Eric Laurent4dc68062014-07-28 17:26:49 -07006244 status = AudioSystem::startInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006245 mLock.lock();
6246 // FIXME should verify that recordTrack is still in mActiveTracks
6247 if (status != NO_ERROR) {
6248 mActiveTracks.remove(recordTrack);
6249 mActiveTracksGen++;
6250 recordTrack->clearSyncStartEvent();
6251 ALOGV("RecordThread::start error %d", status);
6252 return status;
6253 }
Eric Laurent81784c32012-11-19 14:55:58 -08006254 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006255 // Catch up with current buffer indices if thread is already running.
6256 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
6257 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
6258 // see previously buffered data before it called start(), but with greater risk of overrun.
6259
Andy Hung73c02e42015-03-29 01:13:58 -07006260 recordTrack->mResamplerBufferProvider->reset();
Andy Hung97a893e2015-03-29 01:03:07 -07006261 // clear any converter state as new data will be discontinuous
6262 recordTrack->mRecordBufferConverter->reset();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006263 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08006264 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08006265 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08006266 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006267 ALOGV("Record failed to start");
6268 status = BAD_VALUE;
6269 goto startError;
6270 }
Eric Laurent81784c32012-11-19 14:55:58 -08006271 return status;
6272 }
Glenn Kasten7c027242012-12-26 14:43:16 -08006273
Eric Laurent81784c32012-11-19 14:55:58 -08006274startError:
Eric Laurent83b88082014-06-20 18:31:16 -07006275 if (recordTrack->isExternalTrack()) {
Eric Laurent4dc68062014-07-28 17:26:49 -07006276 AudioSystem::stopInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006277 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006278 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006279 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08006280 return status;
6281}
6282
Eric Laurent81784c32012-11-19 14:55:58 -08006283void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6284{
6285 sp<SyncEvent> strongEvent = event.promote();
6286
6287 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08006288 sp<RefBase> ptr = strongEvent->cookie().promote();
6289 if (ptr != 0) {
6290 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
6291 recordTrack->handleSyncStartEvent(strongEvent);
6292 }
Eric Laurent81784c32012-11-19 14:55:58 -08006293 }
6294}
6295
Glenn Kastena8356f62013-07-25 14:37:52 -07006296bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08006297 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07006298 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006299 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08006300 return false;
6301 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006302 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08006303 recordTrack->mState = TrackBase::PAUSING;
6304 // do not wait for mStartStopCond if exiting
6305 if (exitPending()) {
6306 return true;
6307 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006308 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08006309 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006310 // if we have been restarted, recordTrack is in mActiveTracks here
6311 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006312 ALOGV("Record stopped OK");
6313 return true;
6314 }
6315 return false;
6316}
6317
Glenn Kasten0f11b512014-01-31 16:18:54 -08006318bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08006319{
6320 return false;
6321}
6322
Glenn Kasten0f11b512014-01-31 16:18:54 -08006323status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006324{
6325#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
6326 if (!isValidSyncEvent(event)) {
6327 return BAD_VALUE;
6328 }
6329
6330 int eventSession = event->triggerSession();
6331 status_t ret = NAME_NOT_FOUND;
6332
6333 Mutex::Autolock _l(mLock);
6334
6335 for (size_t i = 0; i < mTracks.size(); i++) {
6336 sp<RecordTrack> track = mTracks[i];
6337 if (eventSession == track->sessionId()) {
6338 (void) track->setSyncEvent(event);
6339 ret = NO_ERROR;
6340 }
6341 }
6342 return ret;
6343#else
6344 return BAD_VALUE;
6345#endif
6346}
6347
6348// destroyTrack_l() must be called with ThreadBase::mLock held
6349void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6350{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006351 track->terminate();
6352 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08006353 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08006354 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006355 removeTrack_l(track);
6356 }
6357}
6358
6359void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6360{
6361 mTracks.remove(track);
6362 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006363 if (track->isFastTrack()) {
6364 ALOG_ASSERT(!mFastTrackAvail);
6365 mFastTrackAvail = true;
6366 }
Eric Laurent81784c32012-11-19 14:55:58 -08006367}
6368
6369void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6370{
6371 dumpInternals(fd, args);
6372 dumpTracks(fd, args);
6373 dumpEffectChains(fd, args);
6374}
6375
6376void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6377{
Elliott Hughes87cebad2014-05-22 10:14:43 -07006378 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08006379
Glenn Kasten44182c22015-03-05 17:12:23 -08006380 dumpBase(fd, args);
6381
6382 if (mActiveTracks.size() == 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006383 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006384 }
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006385 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006386 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08006387
Glenn Kasten2f90c512015-12-02 11:40:09 -08006388 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
6389 // while we are dumping it. It may be inconsistent, but it won't mutate!
6390 // This is a large object so we place it on the heap.
6391 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
6392 const FastCaptureDumpState *copy = new FastCaptureDumpState(mFastCaptureDumpState);
6393 copy->dump(fd);
6394 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08006395}
6396
Glenn Kasten0f11b512014-01-31 16:18:54 -08006397void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006398{
6399 const size_t SIZE = 256;
6400 char buffer[SIZE];
6401 String8 result;
6402
Marco Nelissenb2208842014-02-07 14:00:50 -08006403 size_t numtracks = mTracks.size();
6404 size_t numactive = mActiveTracks.size();
6405 size_t numactiveseen = 0;
Elliott Hughes87cebad2014-05-22 10:14:43 -07006406 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08006407 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006408 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08006409 RecordTrack::appendDumpHeader(result);
6410 for (size_t i = 0; i < numtracks ; ++i) {
6411 sp<RecordTrack> track = mTracks[i];
6412 if (track != 0) {
6413 bool active = mActiveTracks.indexOf(track) >= 0;
6414 if (active) {
6415 numactiveseen++;
6416 }
6417 track->dump(buffer, SIZE, active);
6418 result.append(buffer);
6419 }
Eric Laurent81784c32012-11-19 14:55:58 -08006420 }
Marco Nelissenb2208842014-02-07 14:00:50 -08006421 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006422 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006423 }
6424
Marco Nelissenb2208842014-02-07 14:00:50 -08006425 if (numactiveseen != numactive) {
6426 snprintf(buffer, SIZE, " The following tracks are in the active list but"
6427 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006428 result.append(buffer);
6429 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08006430 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08006431 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08006432 if (mTracks.indexOf(track) < 0) {
6433 track->dump(buffer, SIZE, true);
6434 result.append(buffer);
6435 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006436 }
Eric Laurent81784c32012-11-19 14:55:58 -08006437
6438 }
6439 write(fd, result.string(), result.size());
6440}
6441
Andy Hung73c02e42015-03-29 01:13:58 -07006442
6443void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
6444{
6445 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6446 RecordThread *recordThread = (RecordThread *) threadBase.get();
6447 mRsmpInFront = recordThread->mRsmpInRear;
6448 mRsmpInUnrel = 0;
6449}
6450
6451void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
6452 size_t *framesAvailable, bool *hasOverrun)
6453{
6454 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6455 RecordThread *recordThread = (RecordThread *) threadBase.get();
6456 const int32_t rear = recordThread->mRsmpInRear;
6457 const int32_t front = mRsmpInFront;
6458 const ssize_t filled = rear - front;
6459
6460 size_t framesIn;
6461 bool overrun = false;
6462 if (filled < 0) {
6463 // should not happen, but treat like a massive overrun and re-sync
6464 framesIn = 0;
6465 mRsmpInFront = rear;
6466 overrun = true;
6467 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
6468 framesIn = (size_t) filled;
6469 } else {
6470 // client is not keeping up with server, but give it latest data
6471 framesIn = recordThread->mRsmpInFrames;
6472 mRsmpInFront = /* front = */ rear - framesIn;
6473 overrun = true;
6474 }
6475 if (framesAvailable != NULL) {
6476 *framesAvailable = framesIn;
6477 }
6478 if (hasOverrun != NULL) {
6479 *hasOverrun = overrun;
6480 }
6481}
6482
Eric Laurent81784c32012-11-19 14:55:58 -08006483// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006484status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
6485 AudioBufferProvider::Buffer* buffer, int64_t pts __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006486{
Andy Hung73c02e42015-03-29 01:13:58 -07006487 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006488 if (threadBase == 0) {
6489 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006490 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006491 return NOT_ENOUGH_DATA;
6492 }
6493 RecordThread *recordThread = (RecordThread *) threadBase.get();
6494 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07006495 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07006496 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006497 // FIXME should not be P2 (don't want to increase latency)
6498 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006499 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07006500 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006501 front &= recordThread->mRsmpInFramesP2 - 1;
6502 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07006503 if (part1 > (size_t) filled) {
6504 part1 = filled;
6505 }
6506 size_t ask = buffer->frameCount;
6507 ALOG_ASSERT(ask > 0);
6508 if (part1 > ask) {
6509 part1 = ask;
6510 }
6511 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07006512 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07006513 buffer->raw = NULL;
6514 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07006515 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07006516 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08006517 }
6518
Andy Hung57446612015-04-19 23:56:46 -07006519 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07006520 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07006521 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08006522 return NO_ERROR;
6523}
6524
6525// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006526void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
6527 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006528{
Glenn Kasten85948432013-08-19 12:09:05 -07006529 size_t stepCount = buffer->frameCount;
6530 if (stepCount == 0) {
6531 return;
6532 }
Andy Hung73c02e42015-03-29 01:13:58 -07006533 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
6534 mRsmpInUnrel -= stepCount;
6535 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07006536 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006537 buffer->frameCount = 0;
6538}
6539
Andy Hung97a893e2015-03-29 01:03:07 -07006540AudioFlinger::RecordThread::RecordBufferConverter::RecordBufferConverter(
6541 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6542 uint32_t srcSampleRate,
6543 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6544 uint32_t dstSampleRate) :
6545 mSrcChannelMask(AUDIO_CHANNEL_INVALID), // updateParameters will set following vars
6546 // mSrcFormat
6547 // mSrcSampleRate
6548 // mDstChannelMask
6549 // mDstFormat
6550 // mDstSampleRate
6551 // mSrcChannelCount
6552 // mDstChannelCount
6553 // mDstFrameSize
6554 mBuf(NULL), mBufFrames(0), mBufFrameSize(0),
Andy Hungd330ee42015-04-20 13:23:41 -07006555 mResampler(NULL),
6556 mIsLegacyDownmix(false),
6557 mIsLegacyUpmix(false),
6558 mRequiresFloat(false),
6559 mInputConverterProvider(NULL)
Andy Hung97a893e2015-03-29 01:03:07 -07006560{
6561 (void)updateParameters(srcChannelMask, srcFormat, srcSampleRate,
6562 dstChannelMask, dstFormat, dstSampleRate);
6563}
6564
6565AudioFlinger::RecordThread::RecordBufferConverter::~RecordBufferConverter() {
6566 free(mBuf);
6567 delete mResampler;
Andy Hungd330ee42015-04-20 13:23:41 -07006568 delete mInputConverterProvider;
Andy Hung97a893e2015-03-29 01:03:07 -07006569}
6570
6571size_t AudioFlinger::RecordThread::RecordBufferConverter::convert(void *dst,
6572 AudioBufferProvider *provider, size_t frames)
6573{
Andy Hungd330ee42015-04-20 13:23:41 -07006574 if (mInputConverterProvider != NULL) {
6575 mInputConverterProvider->setBufferProvider(provider);
6576 provider = mInputConverterProvider;
6577 }
6578
6579 if (mResampler == NULL) {
Andy Hung97a893e2015-03-29 01:03:07 -07006580 ALOGVV("NO RESAMPLING sampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6581 mSrcSampleRate, mSrcFormat, mDstFormat);
6582
6583 AudioBufferProvider::Buffer buffer;
6584 for (size_t i = frames; i > 0; ) {
6585 buffer.frameCount = i;
6586 status_t status = provider->getNextBuffer(&buffer, 0);
6587 if (status != OK || buffer.frameCount == 0) {
6588 frames -= i; // cannot fill request.
6589 break;
6590 }
Andy Hungd330ee42015-04-20 13:23:41 -07006591 // format convert to destination buffer
6592 convertNoResampler(dst, buffer.raw, buffer.frameCount);
Andy Hung97a893e2015-03-29 01:03:07 -07006593
6594 dst = (int8_t*)dst + buffer.frameCount * mDstFrameSize;
6595 i -= buffer.frameCount;
6596 provider->releaseBuffer(&buffer);
6597 }
6598 } else {
6599 ALOGVV("RESAMPLING mSrcSampleRate:%u mDstSampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6600 mSrcSampleRate, mDstSampleRate, mSrcFormat, mDstFormat);
6601
Andy Hungd330ee42015-04-20 13:23:41 -07006602 // reallocate buffer if needed
6603 if (mBufFrameSize != 0 && mBufFrames < frames) {
6604 free(mBuf);
6605 mBufFrames = frames;
6606 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
6607 }
Andy Hung97a893e2015-03-29 01:03:07 -07006608 // resampler accumulates, but we only have one source track
Andy Hungd330ee42015-04-20 13:23:41 -07006609 memset(mBuf, 0, frames * mBufFrameSize);
6610 frames = mResampler->resample((int32_t*)mBuf, frames, provider);
6611 // format convert to destination buffer
6612 convertResampler(dst, mBuf, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006613 }
6614 return frames;
6615}
6616
6617status_t AudioFlinger::RecordThread::RecordBufferConverter::updateParameters(
6618 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6619 uint32_t srcSampleRate,
6620 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6621 uint32_t dstSampleRate)
6622{
6623 // quick evaluation if there is any change.
6624 if (mSrcFormat == srcFormat
6625 && mSrcChannelMask == srcChannelMask
6626 && mSrcSampleRate == srcSampleRate
6627 && mDstFormat == dstFormat
6628 && mDstChannelMask == dstChannelMask
6629 && mDstSampleRate == dstSampleRate) {
6630 return NO_ERROR;
6631 }
6632
Andy Hungdb4c0312015-05-06 08:46:52 -07006633 ALOGV("RecordBufferConverter updateParameters srcMask:%#x dstMask:%#x"
6634 " srcFormat:%#x dstFormat:%#x srcRate:%u dstRate:%u",
6635 srcChannelMask, dstChannelMask, srcFormat, dstFormat, srcSampleRate, dstSampleRate);
Andy Hung97a893e2015-03-29 01:03:07 -07006636 const bool valid =
6637 audio_is_input_channel(srcChannelMask)
6638 && audio_is_input_channel(dstChannelMask)
6639 && audio_is_valid_format(srcFormat) && audio_is_linear_pcm(srcFormat)
6640 && audio_is_valid_format(dstFormat) && audio_is_linear_pcm(dstFormat)
6641 && (srcSampleRate <= dstSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX)
6642 ; // no upsampling checks for now
6643 if (!valid) {
6644 return BAD_VALUE;
6645 }
6646
6647 mSrcFormat = srcFormat;
6648 mSrcChannelMask = srcChannelMask;
6649 mSrcSampleRate = srcSampleRate;
6650 mDstFormat = dstFormat;
6651 mDstChannelMask = dstChannelMask;
6652 mDstSampleRate = dstSampleRate;
6653
6654 // compute derived parameters
6655 mSrcChannelCount = audio_channel_count_from_in_mask(srcChannelMask);
6656 mDstChannelCount = audio_channel_count_from_in_mask(dstChannelMask);
6657 mDstFrameSize = mDstChannelCount * audio_bytes_per_sample(mDstFormat);
6658
Andy Hungd330ee42015-04-20 13:23:41 -07006659 // do we need to resample?
6660 delete mResampler;
6661 mResampler = NULL;
6662 if (mSrcSampleRate != mDstSampleRate) {
6663 mResampler = AudioResampler::create(AUDIO_FORMAT_PCM_FLOAT,
6664 mSrcChannelCount, mDstSampleRate);
6665 mResampler->setSampleRate(mSrcSampleRate);
6666 mResampler->setVolume(AudioMixer::UNITY_GAIN_FLOAT, AudioMixer::UNITY_GAIN_FLOAT);
6667 }
6668
6669 // are we running legacy channel conversion modes?
6670 mIsLegacyDownmix = (mSrcChannelMask == AUDIO_CHANNEL_IN_STEREO
6671 || mSrcChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK)
6672 && mDstChannelMask == AUDIO_CHANNEL_IN_MONO;
6673 mIsLegacyUpmix = mSrcChannelMask == AUDIO_CHANNEL_IN_MONO
6674 && (mDstChannelMask == AUDIO_CHANNEL_IN_STEREO
6675 || mDstChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK);
6676
6677 // do we need to process in float?
6678 mRequiresFloat = mResampler != NULL || mIsLegacyDownmix || mIsLegacyUpmix;
6679
6680 // do we need a staging buffer to convert for destination (we can still optimize this)?
6681 // we use mBufFrameSize > 0 to indicate both frame size as well as buffer necessity
6682 if (mResampler != NULL) {
6683 mBufFrameSize = max(mSrcChannelCount, FCC_2)
6684 * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
Andy Hunga97630b2015-07-22 23:27:24 -07006685 } else if (mIsLegacyUpmix || mIsLegacyDownmix) { // legacy modes always float
Andy Hungd330ee42015-04-20 13:23:41 -07006686 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
6687 } else if (mSrcChannelMask != mDstChannelMask && mDstFormat != mSrcFormat) {
Andy Hung97a893e2015-03-29 01:03:07 -07006688 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(mSrcFormat);
6689 } else {
6690 mBufFrameSize = 0;
6691 }
6692 mBufFrames = 0; // force the buffer to be resized.
6693
Andy Hungd330ee42015-04-20 13:23:41 -07006694 // do we need an input converter buffer provider to give us float?
6695 delete mInputConverterProvider;
6696 mInputConverterProvider = NULL;
6697 if (mRequiresFloat && mSrcFormat != AUDIO_FORMAT_PCM_FLOAT) {
6698 mInputConverterProvider = new ReformatBufferProvider(
6699 audio_channel_count_from_in_mask(mSrcChannelMask),
6700 mSrcFormat,
6701 AUDIO_FORMAT_PCM_FLOAT,
6702 256 /* provider buffer frame count */);
6703 }
6704
6705 // do we need a remixer to do channel mask conversion
6706 if (!mIsLegacyDownmix && !mIsLegacyUpmix && mSrcChannelMask != mDstChannelMask) {
6707 (void) memcpy_by_index_array_initialization_from_channel_mask(
6708 mIdxAry, ARRAY_SIZE(mIdxAry), mDstChannelMask, mSrcChannelMask);
Andy Hung97a893e2015-03-29 01:03:07 -07006709 }
6710 return NO_ERROR;
6711}
6712
Andy Hungd330ee42015-04-20 13:23:41 -07006713void AudioFlinger::RecordThread::RecordBufferConverter::convertNoResampler(
6714 void *dst, const void *src, size_t frames)
Andy Hung97a893e2015-03-29 01:03:07 -07006715{
Andy Hungd330ee42015-04-20 13:23:41 -07006716 // src is native type unless there is legacy upmix or downmix, whereupon it is float.
Andy Hung97a893e2015-03-29 01:03:07 -07006717 if (mBufFrameSize != 0 && mBufFrames < frames) {
6718 free(mBuf);
6719 mBufFrames = frames;
6720 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
6721 }
Andy Hungd330ee42015-04-20 13:23:41 -07006722 // do we need to do legacy upmix and downmix?
6723 if (mIsLegacyUpmix || mIsLegacyDownmix) {
Andy Hung97a893e2015-03-29 01:03:07 -07006724 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07006725 if (mIsLegacyUpmix) {
6726 upmix_to_stereo_float_from_mono_float((float *)dstBuf,
6727 (const float *)src, frames);
6728 } else /*mIsLegacyDownmix */ {
6729 downmix_to_mono_float_from_stereo_float((float *)dstBuf,
6730 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006731 }
Andy Hungd330ee42015-04-20 13:23:41 -07006732 if (mBuf != NULL) {
6733 memcpy_by_audio_format(dst, mDstFormat, mBuf, AUDIO_FORMAT_PCM_FLOAT,
6734 frames * mDstChannelCount);
6735 }
6736 return;
6737 }
6738 // do we need to do channel mask conversion?
6739 if (mSrcChannelMask != mDstChannelMask) {
Andy Hung97a893e2015-03-29 01:03:07 -07006740 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07006741 memcpy_by_index_array(dstBuf, mDstChannelCount,
6742 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mSrcFormat), frames);
6743 if (dstBuf == dst) {
6744 return; // format is the same
6745 }
6746 }
6747 // convert to destination buffer
6748 const void *convertBuf = mBuf != NULL ? mBuf : src;
6749 memcpy_by_audio_format(dst, mDstFormat, convertBuf, mSrcFormat,
6750 frames * mDstChannelCount);
6751}
6752
6753void AudioFlinger::RecordThread::RecordBufferConverter::convertResampler(
6754 void *dst, /*not-a-const*/ void *src, size_t frames)
6755{
6756 // src buffer format is ALWAYS float when entering this routine
6757 if (mIsLegacyUpmix) {
6758 ; // mono to stereo already handled by resampler
6759 } else if (mIsLegacyDownmix
6760 || (mSrcChannelMask == mDstChannelMask && mSrcChannelCount == 1)) {
6761 // the resampler outputs stereo for mono input channel (a feature?)
6762 // must convert to mono
6763 downmix_to_mono_float_from_stereo_float((float *)src,
6764 (const float *)src, frames);
6765 } else if (mSrcChannelMask != mDstChannelMask) {
6766 // convert to mono channel again for channel mask conversion (could be skipped
6767 // with further optimization).
Andy Hung97a893e2015-03-29 01:03:07 -07006768 if (mSrcChannelCount == 1) {
Andy Hungd330ee42015-04-20 13:23:41 -07006769 downmix_to_mono_float_from_stereo_float((float *)src,
6770 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006771 }
Andy Hungd330ee42015-04-20 13:23:41 -07006772 // convert to destination format (in place, OK as float is larger than other types)
6773 if (mDstFormat != AUDIO_FORMAT_PCM_FLOAT) {
6774 memcpy_by_audio_format(src, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
6775 frames * mSrcChannelCount);
6776 }
6777 // channel convert and save to dst
6778 memcpy_by_index_array(dst, mDstChannelCount,
6779 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mDstFormat), frames);
6780 return;
Andy Hung97a893e2015-03-29 01:03:07 -07006781 }
Andy Hungd330ee42015-04-20 13:23:41 -07006782 // convert to destination format and save to dst
6783 memcpy_by_audio_format(dst, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
6784 frames * mDstChannelCount);
Andy Hung97a893e2015-03-29 01:03:07 -07006785}
6786
Eric Laurent10351942014-05-08 18:49:52 -07006787bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
6788 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006789{
6790 bool reconfig = false;
6791
Eric Laurent10351942014-05-08 18:49:52 -07006792 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006793
Eric Laurent10351942014-05-08 18:49:52 -07006794 audio_format_t reqFormat = mFormat;
6795 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07006796 // 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 -07006797 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
6798
6799 AudioParameter param = AudioParameter(keyValuePair);
6800 int value;
6801 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
6802 // channel count change can be requested. Do we mandate the first client defines the
6803 // HAL sampling rate and channel count or do we allow changes on the fly?
6804 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6805 samplingRate = value;
6806 reconfig = true;
6807 }
6808 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07006809 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07006810 status = BAD_VALUE;
6811 } else {
6812 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08006813 reconfig = true;
6814 }
Eric Laurent10351942014-05-08 18:49:52 -07006815 }
6816 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
6817 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07006818 if (!audio_is_input_channel(mask) ||
6819 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07006820 status = BAD_VALUE;
6821 } else {
6822 channelMask = mask;
6823 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006824 }
Eric Laurent10351942014-05-08 18:49:52 -07006825 }
6826 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6827 // do not accept frame count changes if tracks are open as the track buffer
6828 // size depends on frame count and correct behavior would not be guaranteed
6829 // if frame count is changed after track creation
6830 if (mActiveTracks.size() > 0) {
6831 status = INVALID_OPERATION;
6832 } else {
6833 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006834 }
Eric Laurent10351942014-05-08 18:49:52 -07006835 }
6836 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6837 // forward device change to effects that have requested to be
6838 // aware of attached audio device.
6839 for (size_t i = 0; i < mEffectChains.size(); i++) {
6840 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08006841 }
Eric Laurent81784c32012-11-19 14:55:58 -08006842
Eric Laurent10351942014-05-08 18:49:52 -07006843 // store input device and output device but do not forward output device to audio HAL.
6844 // Note that status is ignored by the caller for output device
6845 // (see AudioFlinger::setParameters()
6846 if (audio_is_output_devices(value)) {
6847 mOutDevice = value;
6848 status = BAD_VALUE;
6849 } else {
6850 mInDevice = value;
Eric Laurente8726fe2015-06-26 09:39:24 -07006851 if (value != AUDIO_DEVICE_NONE) {
6852 mPrevInDevice = value;
6853 }
Eric Laurent10351942014-05-08 18:49:52 -07006854 // disable AEC and NS if the device is a BT SCO headset supporting those
6855 // pre processings
6856 if (mTracks.size() > 0) {
6857 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6858 mAudioFlinger->btNrecIsOff();
6859 for (size_t i = 0; i < mTracks.size(); i++) {
6860 sp<RecordTrack> track = mTracks[i];
6861 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
6862 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08006863 }
6864 }
6865 }
Eric Laurent10351942014-05-08 18:49:52 -07006866 }
6867 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
6868 mAudioSource != (audio_source_t)value) {
6869 // forward device change to effects that have requested to be
6870 // aware of attached audio device.
6871 for (size_t i = 0; i < mEffectChains.size(); i++) {
6872 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08006873 }
Eric Laurent10351942014-05-08 18:49:52 -07006874 mAudioSource = (audio_source_t)value;
6875 }
Glenn Kastene198c362013-08-13 09:13:36 -07006876
Eric Laurent10351942014-05-08 18:49:52 -07006877 if (status == NO_ERROR) {
6878 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6879 keyValuePair.string());
6880 if (status == INVALID_OPERATION) {
6881 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006882 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6883 keyValuePair.string());
Eric Laurent10351942014-05-08 18:49:52 -07006884 }
6885 if (reconfig) {
6886 if (status == BAD_VALUE &&
Andy Hung97a893e2015-03-29 01:03:07 -07006887 audio_is_linear_pcm(mInput->stream->common.get_format(&mInput->stream->common)) &&
6888 audio_is_linear_pcm(reqFormat) &&
Eric Laurent10351942014-05-08 18:49:52 -07006889 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
Andy Hung97a893e2015-03-29 01:03:07 -07006890 <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate)) &&
Andy Hunge5412692014-05-16 11:25:07 -07006891 audio_channel_count_from_in_mask(
Andy Hungd1abb8f2015-05-05 23:42:34 -07006892 mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07006893 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006894 }
Eric Laurent10351942014-05-08 18:49:52 -07006895 if (status == NO_ERROR) {
6896 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07006897 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08006898 }
6899 }
Eric Laurent81784c32012-11-19 14:55:58 -08006900 }
Eric Laurent10351942014-05-08 18:49:52 -07006901
Eric Laurent81784c32012-11-19 14:55:58 -08006902 return reconfig;
6903}
6904
6905String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6906{
Eric Laurent81784c32012-11-19 14:55:58 -08006907 Mutex::Autolock _l(mLock);
6908 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07006909 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08006910 }
6911
Glenn Kastend8ea6992013-07-16 14:17:15 -07006912 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
6913 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08006914 free(s);
6915 return out_s8;
6916}
6917
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07006918void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07006919 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
6920
6921 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08006922
6923 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07006924 case AUDIO_INPUT_OPENED:
6925 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07006926 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07006927 desc->mChannelMask = mChannelMask;
6928 desc->mSamplingRate = mSampleRate;
6929 desc->mFormat = mFormat;
6930 desc->mFrameCount = mFrameCount;
6931 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006932 break;
6933
Eric Laurent73e26b62015-04-27 16:55:58 -07006934 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08006935 default:
6936 break;
6937 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07006938 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08006939}
6940
Glenn Kastendeca2ae2014-02-07 10:25:56 -08006941void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006942{
Eric Laurent81784c32012-11-19 14:55:58 -08006943 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
6944 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Andy Hunge5412692014-05-16 11:25:07 -07006945 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Andy Hungd330ee42015-04-20 13:23:41 -07006946 if (mChannelCount > FCC_8) {
6947 ALOGE("HAL channel count %d > %d", mChannelCount, FCC_8);
6948 }
Andy Hung463be252014-07-10 16:56:07 -07006949 mHALFormat = mInput->stream->common.get_format(&mInput->stream->common);
6950 mFormat = mHALFormat;
Andy Hungd330ee42015-04-20 13:23:41 -07006951 if (!audio_is_linear_pcm(mFormat)) {
6952 ALOGE("HAL format %#x is not linear pcm", mFormat);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07006953 }
Eric Laurent665470b2014-07-03 16:37:08 -07006954 mFrameSize = audio_stream_in_frame_size(mInput->stream);
Glenn Kasten548efc92012-11-29 08:48:51 -08006955 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
6956 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006957 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08006958 // 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 -07006959 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08006960 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006961 // A larger value should allow more old data to be read after a track calls start(),
6962 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07006963 //
6964 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08006965 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07006966 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07006967 free(mRsmpInBuffer);
Andy Hung0a01c2f2015-09-21 12:44:54 -07006968 mRsmpInBuffer = NULL;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006969
6970 // TODO optimize audio capture buffer sizes ...
6971 // Here we calculate the size of the sliding buffer used as a source
6972 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
6973 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
6974 // be better to have it derived from the pipe depth in the long term.
6975 // The current value is higher than necessary. However it should not add to latency.
6976
Glenn Kasten85948432013-08-19 12:09:05 -07006977 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Andy Hung0a01c2f2015-09-21 12:44:54 -07006978 size_t bufferSize = (mRsmpInFramesP2 + mFrameCount - 1) * mFrameSize;
6979 (void)posix_memalign(&mRsmpInBuffer, 32, bufferSize);
6980 memset(mRsmpInBuffer, 0, bufferSize); // if posix_memalign fails, will segv here.
Eric Laurent81784c32012-11-19 14:55:58 -08006981
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006982 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
6983 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08006984}
6985
Glenn Kasten5f972c02014-01-13 09:59:31 -08006986uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08006987{
6988 Mutex::Autolock _l(mLock);
6989 if (initCheck() != NO_ERROR) {
6990 return 0;
6991 }
6992
6993 return mInput->stream->get_input_frames_lost(mInput->stream);
6994}
6995
6996uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
6997{
6998 Mutex::Autolock _l(mLock);
6999 uint32_t result = 0;
7000 if (getEffectChain_l(sessionId) != 0) {
7001 result = EFFECT_SESSION;
7002 }
7003
7004 for (size_t i = 0; i < mTracks.size(); ++i) {
7005 if (sessionId == mTracks[i]->sessionId()) {
7006 result |= TRACK_SESSION;
7007 break;
7008 }
7009 }
7010
7011 return result;
7012}
7013
7014KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
7015{
7016 KeyedVector<int, bool> ids;
7017 Mutex::Autolock _l(mLock);
7018 for (size_t j = 0; j < mTracks.size(); ++j) {
7019 sp<RecordThread::RecordTrack> track = mTracks[j];
7020 int sessionId = track->sessionId();
7021 if (ids.indexOfKey(sessionId) < 0) {
7022 ids.add(sessionId, true);
7023 }
7024 }
7025 return ids;
7026}
7027
7028AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
7029{
7030 Mutex::Autolock _l(mLock);
7031 AudioStreamIn *input = mInput;
7032 mInput = NULL;
7033 return input;
7034}
7035
7036// this method must always be called either with ThreadBase mLock held or inside the thread loop
7037audio_stream_t* AudioFlinger::RecordThread::stream() const
7038{
7039 if (mInput == NULL) {
7040 return NULL;
7041 }
7042 return &mInput->stream->common;
7043}
7044
7045status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7046{
7047 // only one chain per input thread
7048 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07007049 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08007050 return INVALID_OPERATION;
7051 }
7052 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07007053 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08007054 chain->setInBuffer(NULL);
7055 chain->setOutBuffer(NULL);
7056
7057 checkSuspendOnAddEffectChain_l(chain);
7058
Eric Laurent1b928682014-10-02 19:41:47 -07007059 // make sure enabled pre processing effects state is communicated to the HAL as we
7060 // just moved them to a new input stream.
7061 chain->syncHalEffectsState();
7062
Eric Laurent81784c32012-11-19 14:55:58 -08007063 mEffectChains.add(chain);
7064
7065 return NO_ERROR;
7066}
7067
7068size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7069{
7070 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
7071 ALOGW_IF(mEffectChains.size() != 1,
7072 "removeEffectChain_l() %p invalid chain size %d on thread %p",
7073 chain.get(), mEffectChains.size(), this);
7074 if (mEffectChains.size() == 1) {
7075 mEffectChains.removeAt(0);
7076 }
7077 return 0;
7078}
7079
Eric Laurent1c333e22014-05-20 10:48:17 -07007080status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
7081 audio_patch_handle_t *handle)
7082{
7083 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007084
7085 // store new device and send to effects
7086 mInDevice = patch->sources[0].ext.device.type;
Eric Laurent296fb132015-05-01 11:38:42 -07007087 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07007088 for (size_t i = 0; i < mEffectChains.size(); i++) {
7089 mEffectChains[i]->setDevice_l(mInDevice);
7090 }
7091
7092 // disable AEC and NS if the device is a BT SCO headset supporting those
7093 // pre processings
7094 if (mTracks.size() > 0) {
7095 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7096 mAudioFlinger->btNrecIsOff();
7097 for (size_t i = 0; i < mTracks.size(); i++) {
7098 sp<RecordTrack> track = mTracks[i];
7099 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7100 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
7101 }
7102 }
7103
7104 // store new source and send to effects
7105 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7106 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07007107 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07007108 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07007109 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007110 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007111
Eric Laurent054d9d32015-04-24 08:48:48 -07007112 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007113 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
7114 status = hwDevice->create_audio_patch(hwDevice,
7115 patch->num_sources,
7116 patch->sources,
7117 patch->num_sinks,
7118 patch->sinks,
7119 handle);
7120 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007121 char *address;
7122 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
7123 address = audio_device_address_to_parameter(
7124 patch->sources[0].ext.device.type,
7125 patch->sources[0].ext.device.address);
7126 } else {
7127 address = (char *)calloc(1, 1);
7128 }
7129 AudioParameter param = AudioParameter(String8(address));
7130 free(address);
7131 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING),
7132 (int)patch->sources[0].ext.device.type);
7133 param.addInt(String8(AUDIO_PARAMETER_STREAM_INPUT_SOURCE),
7134 (int)patch->sinks[0].ext.mix.usecase.source);
7135 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7136 param.toString().string());
7137 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07007138 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007139
Eric Laurente8726fe2015-06-26 09:39:24 -07007140 if (mInDevice != mPrevInDevice) {
7141 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
7142 mPrevInDevice = mInDevice;
7143 }
Eric Laurent296fb132015-05-01 11:38:42 -07007144
Eric Laurent1c333e22014-05-20 10:48:17 -07007145 return status;
7146}
7147
7148status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
7149{
7150 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007151
7152 mInDevice = AUDIO_DEVICE_NONE;
7153
Eric Laurent1c333e22014-05-20 10:48:17 -07007154 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
7155 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
7156 status = hwDevice->release_audio_patch(hwDevice, handle);
7157 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007158 AudioParameter param;
7159 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
7160 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7161 param.toString().string());
Eric Laurent1c333e22014-05-20 10:48:17 -07007162 }
7163 return status;
7164}
7165
Eric Laurent83b88082014-06-20 18:31:16 -07007166void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
7167{
7168 Mutex::Autolock _l(mLock);
7169 mTracks.add(record);
7170}
7171
7172void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
7173{
7174 Mutex::Autolock _l(mLock);
7175 destroyTrack_l(record);
7176}
7177
7178void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
7179{
7180 ThreadBase::getAudioPortConfig(config);
7181 config->role = AUDIO_PORT_ROLE_SINK;
7182 config->ext.mix.hw_module = mInput->audioHwDev->handle();
7183 config->ext.mix.usecase.source = mAudioSource;
7184}
Eric Laurent1c333e22014-05-20 10:48:17 -07007185
Glenn Kasten63238ef2015-03-02 15:50:29 -08007186} // namespace android