blob: fb89699e116771f1cc194431eab76d0e71c85447 [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>
Andy Hung2ddee192015-12-18 17:34:44 -080039#include <audio_utils/conversion.h>
Eric Laurent81784c32012-11-19 14:55:58 -080040#include <audio_utils/primitives.h>
Andy Hung98ef9782014-03-04 14:46:50 -080041#include <audio_utils/format.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070042#include <audio_utils/minifloat.h>
Eric Laurent81784c32012-11-19 14:55:58 -080043
44// NBAIO implementations
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070045#include <media/nbaio/AudioStreamInSource.h>
Eric Laurent81784c32012-11-19 14:55:58 -080046#include <media/nbaio/AudioStreamOutSink.h>
47#include <media/nbaio/MonoPipe.h>
48#include <media/nbaio/MonoPipeReader.h>
49#include <media/nbaio/Pipe.h>
50#include <media/nbaio/PipeReader.h>
51#include <media/nbaio/SourceAudioBufferProvider.h>
Wei Jia3f273d12015-11-24 09:06:49 -080052#include <mediautils/BatteryNotifier.h>
Eric Laurent81784c32012-11-19 14:55:58 -080053
54#include <powermanager/PowerManager.h>
55
56#include <common_time/cc_helper.h>
57#include <common_time/local_clock.h>
58
59#include "AudioFlinger.h"
60#include "AudioMixer.h"
Andy Hungd330ee42015-04-20 13:23:41 -070061#include "BufferProviders.h"
Eric Laurent81784c32012-11-19 14:55:58 -080062#include "FastMixer.h"
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070063#include "FastCapture.h"
Eric Laurent81784c32012-11-19 14:55:58 -080064#include "ServiceUtilities.h"
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -070065#include "mediautils/SchedulingPolicyService.h"
Eric Laurent81784c32012-11-19 14:55:58 -080066
Eric Laurent81784c32012-11-19 14:55:58 -080067#ifdef ADD_BATTERY_DATA
68#include <media/IMediaPlayerService.h>
69#include <media/IMediaDeathNotifier.h>
70#endif
71
Eric Laurent81784c32012-11-19 14:55:58 -080072#ifdef DEBUG_CPU_USAGE
73#include <cpustats/CentralTendencyStatistics.h>
74#include <cpustats/ThreadCpuUsage.h>
75#endif
76
77// ----------------------------------------------------------------------------
78
79// Note: the following macro is used for extremely verbose logging message. In
80// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
81// 0; but one side effect of this is to turn all LOGV's as well. Some messages
82// are so verbose that we want to suppress them even when we have ALOG_ASSERT
83// turned on. Do not uncomment the #def below unless you really know what you
84// are doing and want to see all of the extremely verbose messages.
85//#define VERY_VERY_VERBOSE_LOGGING
86#ifdef VERY_VERY_VERBOSE_LOGGING
87#define ALOGVV ALOGV
88#else
89#define ALOGVV(a...) do { } while(0)
90#endif
91
Andy Hung6770c6f2015-04-07 13:43:36 -070092// TODO: Move these macro/inlines to a header file.
Glenn Kasten49d00ad2014-07-21 11:22:03 -070093#define max(a, b) ((a) > (b) ? (a) : (b))
Andy Hung6770c6f2015-04-07 13:43:36 -070094template <typename T>
95static inline T min(const T& a, const T& b)
96{
97 return a < b ? a : b;
98}
Glenn Kasten49d00ad2014-07-21 11:22:03 -070099
Andy Hungd330ee42015-04-20 13:23:41 -0700100#ifndef ARRAY_SIZE
101#define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
102#endif
103
Eric Laurent81784c32012-11-19 14:55:58 -0800104namespace android {
105
106// retry counts for buffer fill timeout
107// 50 * ~20msecs = 1 second
108static const int8_t kMaxTrackRetries = 50;
109static const int8_t kMaxTrackStartupRetries = 50;
110// allow less retry attempts on direct output thread.
111// direct outputs can be a scarce resource in audio hardware and should
112// be released as quickly as possible.
113static const int8_t kMaxTrackRetriesDirect = 2;
114
115// don't warn about blocked writes or record buffer overflows more often than this
116static const nsecs_t kWarningThrottleNs = seconds(5);
117
118// RecordThread loop sleep time upon application overrun or audio HAL read error
119static const int kRecordThreadSleepUs = 5000;
120
Eric Laurent10351942014-05-08 18:49:52 -0700121// maximum time to wait in sendConfigEvent_l() for a status to be received
122static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800123
124// minimum sleep time for the mixer thread loop when tracks are active but in underrun
125static const uint32_t kMinThreadSleepTimeUs = 5000;
126// maximum divider applied to the active sleep time in the mixer thread loop
127static const uint32_t kMaxThreadSleepTimeShift = 2;
128
Andy Hung09a50072014-02-27 14:30:47 -0800129// minimum normal sink buffer size, expressed in milliseconds rather than frames
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700130// FIXME This should be based on experimentally observed scheduling jitter
Andy Hung09a50072014-02-27 14:30:47 -0800131static const uint32_t kMinNormalSinkBufferSizeMs = 20;
132// maximum normal sink buffer size
133static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800134
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700135// minimum capture buffer size in milliseconds to _not_ need a fast capture thread
136// FIXME This should be based on experimentally observed scheduling jitter
137static const uint32_t kMinNormalCaptureBufferSizeMs = 12;
138
Eric Laurent972a1732013-09-04 09:42:59 -0700139// Offloaded output thread standby delay: allows track transition without going to standby
140static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
141
Eric Laurent81784c32012-11-19 14:55:58 -0800142// Whether to use fast mixer
143static const enum {
144 FastMixer_Never, // never initialize or use: for debugging only
145 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
146 // normal mixer multiplier is 1
147 FastMixer_Static, // initialize if needed, then use all the time if initialized,
148 // multiplier is calculated based on min & max normal mixer buffer size
149 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
150 // multiplier is calculated based on min & max normal mixer buffer size
151 // FIXME for FastMixer_Dynamic:
152 // Supporting this option will require fixing HALs that can't handle large writes.
153 // For example, one HAL implementation returns an error from a large write,
154 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
155 // We could either fix the HAL implementations, or provide a wrapper that breaks
156 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
157} kUseFastMixer = FastMixer_Static;
158
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700159// Whether to use fast capture
160static const enum {
161 FastCapture_Never, // never initialize or use: for debugging only
162 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
163 FastCapture_Static, // initialize if needed, then use all the time if initialized
164} kUseFastCapture = FastCapture_Static;
165
Eric Laurent81784c32012-11-19 14:55:58 -0800166// Priorities for requestPriority
167static const int kPriorityAudioApp = 2;
168static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700169static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800170
171// IAudioFlinger::createTrack() reports back to client the total size of shared memory area
172// for the track. The client then sub-divides this into smaller buffers for its use.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800173// Currently the client uses N-buffering by default, but doesn't tell us about the value of N.
174// So for now we just assume that client is double-buffered for fast tracks.
175// FIXME It would be better for client to tell AudioFlinger the value of N,
176// so AudioFlinger could allocate the right amount of memory.
Eric Laurent81784c32012-11-19 14:55:58 -0800177// See the client's minBufCount and mNotificationFramesAct calculations for details.
Glenn Kasten03490092014-05-27 12:30:54 -0700178
179// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800180static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800181
Glenn Kasten03490092014-05-27 12:30:54 -0700182// The minimum and maximum allowed values
183static const int kFastTrackMultiplierMin = 1;
184static const int kFastTrackMultiplierMax = 2;
185
186// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
187static int sFastTrackMultiplier = kFastTrackMultiplier;
188
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700189// See Thread::readOnlyHeap().
190// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
191// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
192// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Glenn Kasten9f81de32014-07-27 15:02:23 -0700193static const size_t kRecordThreadReadOnlyHeapSize = 0x2000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700194
Eric Laurent81784c32012-11-19 14:55:58 -0800195// ----------------------------------------------------------------------------
196
Glenn Kasten03490092014-05-27 12:30:54 -0700197static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
198
199static void sFastTrackMultiplierInit()
200{
201 char value[PROPERTY_VALUE_MAX];
202 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
203 char *endptr;
204 unsigned long ul = strtoul(value, &endptr, 0);
205 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
206 sFastTrackMultiplier = (int) ul;
207 }
208 }
209}
210
211// ----------------------------------------------------------------------------
212
Eric Laurent81784c32012-11-19 14:55:58 -0800213#ifdef ADD_BATTERY_DATA
214// To collect the amplifier usage
215static void addBatteryData(uint32_t params) {
216 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
217 if (service == NULL) {
218 // it already logged
219 return;
220 }
221
222 service->addBatteryData(params);
223}
224#endif
225
226
227// ----------------------------------------------------------------------------
228// CPU Stats
229// ----------------------------------------------------------------------------
230
231class CpuStats {
232public:
233 CpuStats();
234 void sample(const String8 &title);
235#ifdef DEBUG_CPU_USAGE
236private:
237 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
238 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
239
240 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
241
242 int mCpuNum; // thread's current CPU number
243 int mCpukHz; // frequency of thread's current CPU in kHz
244#endif
245};
246
247CpuStats::CpuStats()
248#ifdef DEBUG_CPU_USAGE
249 : mCpuNum(-1), mCpukHz(-1)
250#endif
251{
252}
253
Glenn Kasten0f11b512014-01-31 16:18:54 -0800254void CpuStats::sample(const String8 &title
255#ifndef DEBUG_CPU_USAGE
256 __unused
257#endif
258 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800259#ifdef DEBUG_CPU_USAGE
260 // get current thread's delta CPU time in wall clock ns
261 double wcNs;
262 bool valid = mCpuUsage.sampleAndEnable(wcNs);
263
264 // record sample for wall clock statistics
265 if (valid) {
266 mWcStats.sample(wcNs);
267 }
268
269 // get the current CPU number
270 int cpuNum = sched_getcpu();
271
272 // get the current CPU frequency in kHz
273 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
274
275 // check if either CPU number or frequency changed
276 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
277 mCpuNum = cpuNum;
278 mCpukHz = cpukHz;
279 // ignore sample for purposes of cycles
280 valid = false;
281 }
282
283 // if no change in CPU number or frequency, then record sample for cycle statistics
284 if (valid && mCpukHz > 0) {
285 double cycles = wcNs * cpukHz * 0.000001;
286 mHzStats.sample(cycles);
287 }
288
289 unsigned n = mWcStats.n();
290 // mCpuUsage.elapsed() is expensive, so don't call it every loop
291 if ((n & 127) == 1) {
292 long long elapsed = mCpuUsage.elapsed();
293 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
294 double perLoop = elapsed / (double) n;
295 double perLoop100 = perLoop * 0.01;
296 double perLoop1k = perLoop * 0.001;
297 double mean = mWcStats.mean();
298 double stddev = mWcStats.stddev();
299 double minimum = mWcStats.minimum();
300 double maximum = mWcStats.maximum();
301 double meanCycles = mHzStats.mean();
302 double stddevCycles = mHzStats.stddev();
303 double minCycles = mHzStats.minimum();
304 double maxCycles = mHzStats.maximum();
305 mCpuUsage.resetElapsed();
306 mWcStats.reset();
307 mHzStats.reset();
308 ALOGD("CPU usage for %s over past %.1f secs\n"
309 " (%u mixer loops at %.1f mean ms per loop):\n"
310 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
311 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
312 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
313 title.string(),
314 elapsed * .000000001, n, perLoop * .000001,
315 mean * .001,
316 stddev * .001,
317 minimum * .001,
318 maximum * .001,
319 mean / perLoop100,
320 stddev / perLoop100,
321 minimum / perLoop100,
322 maximum / perLoop100,
323 meanCycles / perLoop1k,
324 stddevCycles / perLoop1k,
325 minCycles / perLoop1k,
326 maxCycles / perLoop1k);
327
328 }
329 }
330#endif
331};
332
333// ----------------------------------------------------------------------------
334// ThreadBase
335// ----------------------------------------------------------------------------
336
Glenn Kasten97b7b752014-09-28 13:04:24 -0700337// static
338const char *AudioFlinger::ThreadBase::threadTypeToString(AudioFlinger::ThreadBase::type_t type)
339{
340 switch (type) {
341 case MIXER:
342 return "MIXER";
343 case DIRECT:
344 return "DIRECT";
345 case DUPLICATING:
346 return "DUPLICATING";
347 case RECORD:
348 return "RECORD";
349 case OFFLOAD:
350 return "OFFLOAD";
351 default:
352 return "unknown";
353 }
354}
355
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800356String8 devicesToString(audio_devices_t devices)
357{
358 static const struct mapping {
359 audio_devices_t mDevices;
360 const char * mString;
361 } mappingsOut[] = {
Glenn Kasten818da522015-12-02 13:53:26 -0800362 {AUDIO_DEVICE_OUT_EARPIECE, "EARPIECE"},
363 {AUDIO_DEVICE_OUT_SPEAKER, "SPEAKER"},
364 {AUDIO_DEVICE_OUT_WIRED_HEADSET, "WIRED_HEADSET"},
365 {AUDIO_DEVICE_OUT_WIRED_HEADPHONE, "WIRED_HEADPHONE"},
366 {AUDIO_DEVICE_OUT_BLUETOOTH_SCO, "BLUETOOTH_SCO"},
367 {AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET, "BLUETOOTH_SCO_HEADSET"},
368 {AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT, "BLUETOOTH_SCO_CARKIT"},
369 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, "BLUETOOTH_A2DP"},
370 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,"BLUETOOTH_A2DP_HEADPHONES"},
371 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER, "BLUETOOTH_A2DP_SPEAKER"},
372 {AUDIO_DEVICE_OUT_AUX_DIGITAL, "AUX_DIGITAL"},
373 {AUDIO_DEVICE_OUT_HDMI, "HDMI"},
374 {AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET,"ANLG_DOCK_HEADSET"},
375 {AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET,"DGTL_DOCK_HEADSET"},
376 {AUDIO_DEVICE_OUT_USB_ACCESSORY, "USB_ACCESSORY"},
377 {AUDIO_DEVICE_OUT_USB_DEVICE, "USB_DEVICE"},
378 {AUDIO_DEVICE_OUT_TELEPHONY_TX, "TELEPHONY_TX"},
379 {AUDIO_DEVICE_OUT_LINE, "LINE"},
380 {AUDIO_DEVICE_OUT_HDMI_ARC, "HDMI_ARC"},
381 {AUDIO_DEVICE_OUT_SPDIF, "SPDIF"},
382 {AUDIO_DEVICE_OUT_FM, "FM"},
383 {AUDIO_DEVICE_OUT_AUX_LINE, "AUX_LINE"},
384 {AUDIO_DEVICE_OUT_SPEAKER_SAFE, "SPEAKER_SAFE"},
385 {AUDIO_DEVICE_OUT_IP, "IP"},
386 {AUDIO_DEVICE_NONE, "NONE"}, // must be last
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800387 }, mappingsIn[] = {
Glenn Kasten818da522015-12-02 13:53:26 -0800388 {AUDIO_DEVICE_IN_COMMUNICATION, "COMMUNICATION"},
389 {AUDIO_DEVICE_IN_AMBIENT, "AMBIENT"},
390 {AUDIO_DEVICE_IN_BUILTIN_MIC, "BUILTIN_MIC"},
391 {AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET, "BLUETOOTH_SCO_HEADSET"},
392 {AUDIO_DEVICE_IN_WIRED_HEADSET, "WIRED_HEADSET"},
393 {AUDIO_DEVICE_IN_AUX_DIGITAL, "AUX_DIGITAL"},
394 {AUDIO_DEVICE_IN_VOICE_CALL, "VOICE_CALL"},
395 {AUDIO_DEVICE_IN_TELEPHONY_RX, "TELEPHONY_RX"},
396 {AUDIO_DEVICE_IN_BACK_MIC, "BACK_MIC"},
397 {AUDIO_DEVICE_IN_REMOTE_SUBMIX, "REMOTE_SUBMIX"},
398 {AUDIO_DEVICE_IN_ANLG_DOCK_HEADSET, "ANLG_DOCK_HEADSET"},
399 {AUDIO_DEVICE_IN_DGTL_DOCK_HEADSET, "DGTL_DOCK_HEADSET"},
400 {AUDIO_DEVICE_IN_USB_ACCESSORY, "USB_ACCESSORY"},
401 {AUDIO_DEVICE_IN_USB_DEVICE, "USB_DEVICE"},
402 {AUDIO_DEVICE_IN_FM_TUNER, "FM_TUNER"},
403 {AUDIO_DEVICE_IN_TV_TUNER, "TV_TUNER"},
404 {AUDIO_DEVICE_IN_LINE, "LINE"},
405 {AUDIO_DEVICE_IN_SPDIF, "SPDIF"},
406 {AUDIO_DEVICE_IN_BLUETOOTH_A2DP, "BLUETOOTH_A2DP"},
407 {AUDIO_DEVICE_IN_LOOPBACK, "LOOPBACK"},
408 {AUDIO_DEVICE_IN_IP, "IP"},
409 {AUDIO_DEVICE_NONE, "NONE"}, // must be last
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800410 };
411 String8 result;
412 audio_devices_t allDevices = AUDIO_DEVICE_NONE;
413 const mapping *entry;
414 if (devices & AUDIO_DEVICE_BIT_IN) {
415 devices &= ~AUDIO_DEVICE_BIT_IN;
416 entry = mappingsIn;
417 } else {
418 entry = mappingsOut;
419 }
420 for ( ; entry->mDevices != AUDIO_DEVICE_NONE; entry++) {
421 allDevices = (audio_devices_t) (allDevices | entry->mDevices);
422 if (devices & entry->mDevices) {
423 if (!result.isEmpty()) {
424 result.append("|");
425 }
426 result.append(entry->mString);
427 }
428 }
429 if (devices & ~allDevices) {
430 if (!result.isEmpty()) {
431 result.append("|");
432 }
433 result.appendFormat("0x%X", devices & ~allDevices);
434 }
435 if (result.isEmpty()) {
436 result.append(entry->mString);
437 }
438 return result;
439}
440
441String8 inputFlagsToString(audio_input_flags_t flags)
442{
443 static const struct mapping {
444 audio_input_flags_t mFlag;
445 const char * mString;
446 } mappings[] = {
Glenn Kasten818da522015-12-02 13:53:26 -0800447 {AUDIO_INPUT_FLAG_FAST, "FAST"},
448 {AUDIO_INPUT_FLAG_HW_HOTWORD, "HW_HOTWORD"},
449 {AUDIO_INPUT_FLAG_RAW, "RAW"},
450 {AUDIO_INPUT_FLAG_SYNC, "SYNC"},
451 {AUDIO_INPUT_FLAG_NONE, "NONE"}, // must be last
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800452 };
453 String8 result;
454 audio_input_flags_t allFlags = AUDIO_INPUT_FLAG_NONE;
455 const mapping *entry;
456 for (entry = mappings; entry->mFlag != AUDIO_INPUT_FLAG_NONE; entry++) {
457 allFlags = (audio_input_flags_t) (allFlags | entry->mFlag);
458 if (flags & entry->mFlag) {
459 if (!result.isEmpty()) {
460 result.append("|");
461 }
462 result.append(entry->mString);
463 }
464 }
465 if (flags & ~allFlags) {
466 if (!result.isEmpty()) {
467 result.append("|");
468 }
469 result.appendFormat("0x%X", flags & ~allFlags);
470 }
471 if (result.isEmpty()) {
472 result.append(entry->mString);
473 }
474 return result;
475}
476
477String8 outputFlagsToString(audio_output_flags_t flags)
Glenn Kasten97b7b752014-09-28 13:04:24 -0700478{
479 static const struct mapping {
480 audio_output_flags_t mFlag;
481 const char * mString;
482 } mappings[] = {
Glenn Kasten818da522015-12-02 13:53:26 -0800483 {AUDIO_OUTPUT_FLAG_DIRECT, "DIRECT"},
484 {AUDIO_OUTPUT_FLAG_PRIMARY, "PRIMARY"},
485 {AUDIO_OUTPUT_FLAG_FAST, "FAST"},
486 {AUDIO_OUTPUT_FLAG_DEEP_BUFFER, "DEEP_BUFFER"},
487 {AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,"COMPRESS_OFFLOAD"},
488 {AUDIO_OUTPUT_FLAG_NON_BLOCKING, "NON_BLOCKING"},
489 {AUDIO_OUTPUT_FLAG_HW_AV_SYNC, "HW_AV_SYNC"},
490 {AUDIO_OUTPUT_FLAG_RAW, "RAW"},
491 {AUDIO_OUTPUT_FLAG_SYNC, "SYNC"},
492 {AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO, "IEC958_NONAUDIO"},
493 {AUDIO_OUTPUT_FLAG_NONE, "NONE"}, // must be last
Glenn Kasten97b7b752014-09-28 13:04:24 -0700494 };
495 String8 result;
496 audio_output_flags_t allFlags = AUDIO_OUTPUT_FLAG_NONE;
497 const mapping *entry;
498 for (entry = mappings; entry->mFlag != AUDIO_OUTPUT_FLAG_NONE; entry++) {
499 allFlags = (audio_output_flags_t) (allFlags | entry->mFlag);
500 if (flags & entry->mFlag) {
501 if (!result.isEmpty()) {
502 result.append("|");
503 }
504 result.append(entry->mString);
505 }
506 }
507 if (flags & ~allFlags) {
508 if (!result.isEmpty()) {
509 result.append("|");
510 }
511 result.appendFormat("0x%X", flags & ~allFlags);
512 }
513 if (result.isEmpty()) {
514 result.append(entry->mString);
515 }
516 return result;
517}
518
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800519const char *sourceToString(audio_source_t source)
520{
521 switch (source) {
522 case AUDIO_SOURCE_DEFAULT: return "default";
523 case AUDIO_SOURCE_MIC: return "mic";
524 case AUDIO_SOURCE_VOICE_UPLINK: return "voice uplink";
525 case AUDIO_SOURCE_VOICE_DOWNLINK: return "voice downlink";
526 case AUDIO_SOURCE_VOICE_CALL: return "voice call";
527 case AUDIO_SOURCE_CAMCORDER: return "camcorder";
528 case AUDIO_SOURCE_VOICE_RECOGNITION: return "voice recognition";
529 case AUDIO_SOURCE_VOICE_COMMUNICATION: return "voice communication";
530 case AUDIO_SOURCE_REMOTE_SUBMIX: return "remote submix";
531 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{
Andy Hung2ddee192015-12-18 17:34:44 -0800673 sp<ConfigEvent> configEvent;
674 AudioParameter param(keyValuePair);
675 int value;
676 if (param.getInt(String8(AUDIO_PARAMETER_MONO_OUTPUT), value) == NO_ERROR) {
677 setMasterMono_l(value != 0);
678 if (param.size() == 1) {
679 return NO_ERROR; // should be a solo parameter - we don't pass down
680 }
681 param.remove(String8(AUDIO_PARAMETER_MONO_OUTPUT));
682 configEvent = new SetParameterConfigEvent(param.toString());
683 } else {
684 configEvent = new SetParameterConfigEvent(keyValuePair);
685 }
Eric Laurent10351942014-05-08 18:49:52 -0700686 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700687}
688
Eric Laurent1c333e22014-05-20 10:48:17 -0700689status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
690 const struct audio_patch *patch,
691 audio_patch_handle_t *handle)
692{
693 Mutex::Autolock _l(mLock);
694 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
695 status_t status = sendConfigEvent_l(configEvent);
696 if (status == NO_ERROR) {
697 CreateAudioPatchConfigEventData *data =
698 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
699 *handle = data->mHandle;
700 }
701 return status;
702}
703
704status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
705 const audio_patch_handle_t handle)
706{
707 Mutex::Autolock _l(mLock);
708 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
709 return sendConfigEvent_l(configEvent);
710}
711
712
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700713// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700714void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700715{
Eric Laurent10351942014-05-08 18:49:52 -0700716 bool configChanged = false;
717
Eric Laurent81784c32012-11-19 14:55:58 -0800718 while (!mConfigEvents.isEmpty()) {
Eric Laurent10351942014-05-08 18:49:52 -0700719 ALOGV("processConfigEvents_l() remaining events %d", mConfigEvents.size());
720 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800721 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700722 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700723 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700724 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
725 // FIXME Need to understand why this has to be done asynchronously
726 int err = requestPriority(data->mPid, data->mTid, data->mPrio,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700727 true /*asynchronous*/);
728 if (err != 0) {
729 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700730 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700731 }
732 } break;
733 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700734 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700735 ioConfigChanged(data->mEvent, data->mPid);
Eric Laurent10351942014-05-08 18:49:52 -0700736 } break;
737 case CFG_EVENT_SET_PARAMETER: {
738 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
739 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
740 configChanged = true;
Glenn Kastend5418eb2013-08-14 13:11:06 -0700741 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700742 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700743 case CFG_EVENT_CREATE_AUDIO_PATCH: {
744 CreateAudioPatchConfigEventData *data =
745 (CreateAudioPatchConfigEventData *)event->mData.get();
746 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
747 } break;
748 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
749 ReleaseAudioPatchConfigEventData *data =
750 (ReleaseAudioPatchConfigEventData *)event->mData.get();
751 event->mStatus = releaseAudioPatch_l(data->mHandle);
752 } break;
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700753 default:
Eric Laurent10351942014-05-08 18:49:52 -0700754 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700755 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800756 }
Eric Laurent10351942014-05-08 18:49:52 -0700757 {
758 Mutex::Autolock _l(event->mLock);
759 if (event->mWaitStatus) {
760 event->mWaitStatus = false;
761 event->mCond.signal();
762 }
763 }
764 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
765 }
766
767 if (configChanged) {
768 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800769 }
Eric Laurent81784c32012-11-19 14:55:58 -0800770}
771
Marco Nelissenb2208842014-02-07 14:00:50 -0800772String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
773 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700774 const audio_channel_representation_t representation =
775 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700776
777 switch (representation) {
778 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
779 if (output) {
780 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
781 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
782 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
783 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
784 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
785 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
786 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
787 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
788 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
789 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
790 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
791 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
792 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
793 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
794 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
795 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
796 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
797 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
798 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
799 } else {
800 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
801 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
802 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
803 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
804 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
805 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
806 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
807 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
808 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
809 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
810 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
811 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
812 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
813 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
814 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
815 }
816 const int len = s.length();
817 if (len > 2) {
818 char *str = s.lockBuffer(len); // needed?
819 s.unlockBuffer(len - 2); // remove trailing ", "
820 }
821 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800822 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700823 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
824 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
825 return s;
826 default:
827 s.appendFormat("unknown mask, representation:%d bits:%#x",
828 representation, audio_channel_mask_get_bits(mask));
829 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800830 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800831}
832
Glenn Kasten0f11b512014-01-31 16:18:54 -0800833void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800834{
835 const size_t SIZE = 256;
836 char buffer[SIZE];
837 String8 result;
838
839 bool locked = AudioFlinger::dumpTryLock(mLock);
840 if (!locked) {
Glenn Kasten97b7b752014-09-28 13:04:24 -0700841 dprintf(fd, "thread %p may be deadlocked\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -0800842 }
843
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800844 dprintf(fd, " Thread name: %s\n", mThreadName);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700845 dprintf(fd, " I/O handle: %d\n", mId);
846 dprintf(fd, " TID: %d\n", getTid());
847 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700848 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700849 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700850 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat));
Elliott Hughes87cebad2014-05-22 10:14:43 -0700851 dprintf(fd, " HAL buffer size: %u bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700852 dprintf(fd, " Channel count: %u\n", mChannelCount);
853 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800854 channelMaskToString(mChannelMask, mType != RECORD).string());
Glenn Kastenf87c2f52015-08-21 08:03:57 -0700855 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat, formatToString(mFormat));
856 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700857 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800858 size_t numConfig = mConfigEvents.size();
859 if (numConfig) {
860 for (size_t i = 0; i < numConfig; i++) {
861 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700862 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800863 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700864 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800865 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700866 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800867 }
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800868 dprintf(fd, " Output device: %#x (%s)\n", mOutDevice, devicesToString(mOutDevice).string());
869 dprintf(fd, " Input device: %#x (%s)\n", mInDevice, devicesToString(mInDevice).string());
870 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, sourceToString(mAudioSource));
Eric Laurent81784c32012-11-19 14:55:58 -0800871
872 if (locked) {
873 mLock.unlock();
874 }
875}
876
877void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
878{
879 const size_t SIZE = 256;
880 char buffer[SIZE];
881 String8 result;
882
Marco Nelissenb2208842014-02-07 14:00:50 -0800883 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000884 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800885 write(fd, buffer, strlen(buffer));
886
Marco Nelissenb2208842014-02-07 14:00:50 -0800887 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800888 sp<EffectChain> chain = mEffectChains[i];
889 if (chain != 0) {
890 chain->dump(fd, args);
891 }
892 }
893}
894
Marco Nelissene14a5d62013-10-03 08:51:24 -0700895void AudioFlinger::ThreadBase::acquireWakeLock(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800896{
897 Mutex::Autolock _l(mLock);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700898 acquireWakeLock_l(uid);
Eric Laurent81784c32012-11-19 14:55:58 -0800899}
900
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100901String16 AudioFlinger::ThreadBase::getWakeLockTag()
902{
903 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -0800904 case MIXER:
905 return String16("AudioMix");
906 case DIRECT:
907 return String16("AudioDirectOut");
908 case DUPLICATING:
909 return String16("AudioDup");
910 case RECORD:
911 return String16("AudioIn");
912 case OFFLOAD:
913 return String16("AudioOffload");
914 default:
915 ALOG_ASSERT(false);
916 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100917 }
918}
919
Marco Nelissene14a5d62013-10-03 08:51:24 -0700920void AudioFlinger::ThreadBase::acquireWakeLock_l(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800921{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800922 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800923 if (mPowerManager != 0) {
924 sp<IBinder> binder = new BBinder();
Marco Nelissene14a5d62013-10-03 08:51:24 -0700925 status_t status;
926 if (uid >= 0) {
Eric Laurent547789d2013-10-04 11:46:55 -0700927 status = mPowerManager->acquireWakeLockWithUid(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700928 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100929 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -0700930 String16("audioserver"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700931 uid,
932 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700933 } else {
Eric Laurent547789d2013-10-04 11:46:55 -0700934 status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700935 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100936 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -0700937 String16("audioserver"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700938 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700939 }
Eric Laurent81784c32012-11-19 14:55:58 -0800940 if (status == NO_ERROR) {
941 mWakeLockToken = binder;
942 }
Glenn Kastend7dca052015-03-05 16:05:54 -0800943 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Eric Laurent81784c32012-11-19 14:55:58 -0800944 }
Wei Jia3f273d12015-11-24 09:06:49 -0800945
946 if (!mNotifiedBatteryStart) {
947 BatteryNotifier::getInstance().noteStartAudio();
948 mNotifiedBatteryStart = true;
949 }
Eric Laurent81784c32012-11-19 14:55:58 -0800950}
951
952void AudioFlinger::ThreadBase::releaseWakeLock()
953{
954 Mutex::Autolock _l(mLock);
955 releaseWakeLock_l();
956}
957
958void AudioFlinger::ThreadBase::releaseWakeLock_l()
959{
960 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800961 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -0800962 if (mPowerManager != 0) {
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700963 mPowerManager->releaseWakeLock(mWakeLockToken, 0,
964 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800965 }
966 mWakeLockToken.clear();
967 }
Wei Jia3f273d12015-11-24 09:06:49 -0800968
969 if (mNotifiedBatteryStart) {
970 BatteryNotifier::getInstance().noteStopAudio();
971 mNotifiedBatteryStart = false;
972 }
Eric Laurent81784c32012-11-19 14:55:58 -0800973}
974
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800975void AudioFlinger::ThreadBase::updateWakeLockUids(const SortedVector<int> &uids) {
976 Mutex::Autolock _l(mLock);
977 updateWakeLockUids_l(uids);
978}
979
980void AudioFlinger::ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -0700981 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800982 // use checkService() to avoid blocking if power service is not up yet
983 sp<IBinder> binder =
984 defaultServiceManager()->checkService(String16("power"));
985 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800986 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800987 } else {
988 mPowerManager = interface_cast<IPowerManager>(binder);
989 binder->linkToDeath(mDeathRecipient);
990 }
991 }
992}
993
994void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<int> &uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800995 getPowerManager_l();
Andy Hung438e7572015-12-14 15:51:17 -0800996 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
997 if (mSystemReady) {
998 ALOGE("no wake lock to update, but system ready!");
999 } else {
1000 ALOGW("no wake lock to update, system not ready yet");
1001 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001002 return;
1003 }
1004 if (mPowerManager != 0) {
1005 sp<IBinder> binder = new BBinder();
1006 status_t status;
Glenn Kasten3abc2de2014-09-05 16:45:52 -07001007 status = mPowerManager->updateWakeLockUids(mWakeLockToken, uids.size(), uids.array(),
1008 true /* FIXME force oneway contrary to .aidl */);
Glenn Kastend7dca052015-03-05 16:05:54 -08001009 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001010 }
1011}
1012
Eric Laurent81784c32012-11-19 14:55:58 -08001013void AudioFlinger::ThreadBase::clearPowerManager()
1014{
1015 Mutex::Autolock _l(mLock);
1016 releaseWakeLock_l();
1017 mPowerManager.clear();
1018}
1019
Glenn Kasten0f11b512014-01-31 16:18:54 -08001020void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001021{
1022 sp<ThreadBase> thread = mThread.promote();
1023 if (thread != 0) {
1024 thread->clearPowerManager();
1025 }
1026 ALOGW("power manager service died !!!");
1027}
1028
1029void AudioFlinger::ThreadBase::setEffectSuspended(
1030 const effect_uuid_t *type, bool suspend, int sessionId)
1031{
1032 Mutex::Autolock _l(mLock);
1033 setEffectSuspended_l(type, suspend, sessionId);
1034}
1035
1036void AudioFlinger::ThreadBase::setEffectSuspended_l(
1037 const effect_uuid_t *type, bool suspend, int sessionId)
1038{
1039 sp<EffectChain> chain = getEffectChain_l(sessionId);
1040 if (chain != 0) {
1041 if (type != NULL) {
1042 chain->setEffectSuspended_l(type, suspend);
1043 } else {
1044 chain->setEffectSuspendedAll_l(suspend);
1045 }
1046 }
1047
1048 updateSuspendedSessions_l(type, suspend, sessionId);
1049}
1050
1051void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1052{
1053 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1054 if (index < 0) {
1055 return;
1056 }
1057
1058 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1059 mSuspendedSessions.valueAt(index);
1060
1061 for (size_t i = 0; i < sessionEffects.size(); i++) {
1062 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
1063 for (int j = 0; j < desc->mRefCount; j++) {
1064 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1065 chain->setEffectSuspendedAll_l(true);
1066 } else {
1067 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1068 desc->mType.timeLow);
1069 chain->setEffectSuspended_l(&desc->mType, true);
1070 }
1071 }
1072 }
1073}
1074
1075void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1076 bool suspend,
1077 int sessionId)
1078{
1079 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1080
1081 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1082
1083 if (suspend) {
1084 if (index >= 0) {
1085 sessionEffects = mSuspendedSessions.valueAt(index);
1086 } else {
1087 mSuspendedSessions.add(sessionId, sessionEffects);
1088 }
1089 } else {
1090 if (index < 0) {
1091 return;
1092 }
1093 sessionEffects = mSuspendedSessions.valueAt(index);
1094 }
1095
1096
1097 int key = EffectChain::kKeyForSuspendAll;
1098 if (type != NULL) {
1099 key = type->timeLow;
1100 }
1101 index = sessionEffects.indexOfKey(key);
1102
1103 sp<SuspendedSessionDesc> desc;
1104 if (suspend) {
1105 if (index >= 0) {
1106 desc = sessionEffects.valueAt(index);
1107 } else {
1108 desc = new SuspendedSessionDesc();
1109 if (type != NULL) {
1110 desc->mType = *type;
1111 }
1112 sessionEffects.add(key, desc);
1113 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1114 }
1115 desc->mRefCount++;
1116 } else {
1117 if (index < 0) {
1118 return;
1119 }
1120 desc = sessionEffects.valueAt(index);
1121 if (--desc->mRefCount == 0) {
1122 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1123 sessionEffects.removeItemsAt(index);
1124 if (sessionEffects.isEmpty()) {
1125 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1126 sessionId);
1127 mSuspendedSessions.removeItem(sessionId);
1128 }
1129 }
1130 }
1131 if (!sessionEffects.isEmpty()) {
1132 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1133 }
1134}
1135
1136void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1137 bool enabled,
1138 int sessionId)
1139{
1140 Mutex::Autolock _l(mLock);
1141 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1142}
1143
1144void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1145 bool enabled,
1146 int sessionId)
1147{
1148 if (mType != RECORD) {
1149 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1150 // another session. This gives the priority to well behaved effect control panels
1151 // and applications not using global effects.
1152 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1153 // global effects
1154 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
1155 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1156 }
1157 }
1158
1159 sp<EffectChain> chain = getEffectChain_l(sessionId);
1160 if (chain != 0) {
1161 chain->checkSuspendOnEffectEnabled(effect, enabled);
1162 }
1163}
1164
1165// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1166sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1167 const sp<AudioFlinger::Client>& client,
1168 const sp<IEffectClient>& effectClient,
1169 int32_t priority,
1170 int sessionId,
1171 effect_descriptor_t *desc,
1172 int *enabled,
Glenn Kasten9156ef32013-08-06 15:39:08 -07001173 status_t *status)
Eric Laurent81784c32012-11-19 14:55:58 -08001174{
1175 sp<EffectModule> effect;
1176 sp<EffectHandle> handle;
1177 status_t lStatus;
1178 sp<EffectChain> chain;
1179 bool chainCreated = false;
1180 bool effectCreated = false;
1181 bool effectRegistered = false;
1182
1183 lStatus = initCheck();
1184 if (lStatus != NO_ERROR) {
1185 ALOGW("createEffect_l() Audio driver not initialized.");
1186 goto Exit;
1187 }
1188
Andy Hung98ef9782014-03-04 14:46:50 -08001189 // Reject any effect on Direct output threads for now, since the format of
1190 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1191 if (mType == DIRECT) {
1192 ALOGW("createEffect_l() Cannot add effect %s on Direct output type thread %s",
Glenn Kastend7dca052015-03-05 16:05:54 -08001193 desc->name, mThreadName);
Andy Hung98ef9782014-03-04 14:46:50 -08001194 lStatus = BAD_VALUE;
1195 goto Exit;
1196 }
1197
Andy Hung389cfdb2014-08-07 17:49:53 -07001198 // Reject any effect on mixer or duplicating multichannel sinks.
Andy Hung9a592762014-07-21 21:56:01 -07001199 // TODO: fix both format and multichannel issues with effects.
Andy Hung389cfdb2014-08-07 17:49:53 -07001200 if ((mType == MIXER || mType == DUPLICATING) && mChannelCount != FCC_2) {
1201 ALOGW("createEffect_l() Cannot add effect %s for multichannel(%d) %s threads",
1202 desc->name, mChannelCount, mType == MIXER ? "MIXER" : "DUPLICATING");
Andy Hung9a592762014-07-21 21:56:01 -07001203 lStatus = BAD_VALUE;
1204 goto Exit;
1205 }
1206
Eric Laurent5baf2af2013-09-12 17:37:00 -07001207 // Allow global effects only on offloaded and mixer threads
1208 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1209 switch (mType) {
1210 case MIXER:
1211 case OFFLOAD:
1212 break;
1213 case DIRECT:
1214 case DUPLICATING:
1215 case RECORD:
1216 default:
Glenn Kastend7dca052015-03-05 16:05:54 -08001217 ALOGW("createEffect_l() Cannot add global effect %s on thread %s",
1218 desc->name, mThreadName);
Eric Laurent5baf2af2013-09-12 17:37:00 -07001219 lStatus = BAD_VALUE;
1220 goto Exit;
1221 }
Eric Laurent81784c32012-11-19 14:55:58 -08001222 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07001223
Eric Laurent81784c32012-11-19 14:55:58 -08001224 // Only Pre processor effects are allowed on input threads and only on input threads
1225 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
1226 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
1227 desc->name, desc->flags, mType);
1228 lStatus = BAD_VALUE;
1229 goto Exit;
1230 }
1231
1232 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1233
1234 { // scope for mLock
1235 Mutex::Autolock _l(mLock);
1236
1237 // check for existing effect chain with the requested audio session
1238 chain = getEffectChain_l(sessionId);
1239 if (chain == 0) {
1240 // create a new chain for this session
1241 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1242 chain = new EffectChain(this, sessionId);
1243 addEffectChain_l(chain);
1244 chain->setStrategy(getStrategyForSession_l(sessionId));
1245 chainCreated = true;
1246 } else {
1247 effect = chain->getEffectFromDesc_l(desc);
1248 }
1249
1250 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1251
1252 if (effect == 0) {
1253 int id = mAudioFlinger->nextUniqueId();
1254 // Check CPU and memory usage
1255 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
1256 if (lStatus != NO_ERROR) {
1257 goto Exit;
1258 }
1259 effectRegistered = true;
1260 // create a new effect module if none present in the chain
1261 effect = new EffectModule(this, chain, desc, id, sessionId);
1262 lStatus = effect->status();
1263 if (lStatus != NO_ERROR) {
1264 goto Exit;
1265 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07001266 effect->setOffloaded(mType == OFFLOAD, mId);
1267
Eric Laurent81784c32012-11-19 14:55:58 -08001268 lStatus = chain->addEffect_l(effect);
1269 if (lStatus != NO_ERROR) {
1270 goto Exit;
1271 }
1272 effectCreated = true;
1273
1274 effect->setDevice(mOutDevice);
1275 effect->setDevice(mInDevice);
1276 effect->setMode(mAudioFlinger->getMode());
1277 effect->setAudioSource(mAudioSource);
1278 }
1279 // create effect handle and connect it to effect module
1280 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001281 lStatus = handle->initCheck();
1282 if (lStatus == OK) {
1283 lStatus = effect->addHandle(handle.get());
1284 }
Eric Laurent81784c32012-11-19 14:55:58 -08001285 if (enabled != NULL) {
1286 *enabled = (int)effect->isEnabled();
1287 }
1288 }
1289
1290Exit:
1291 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1292 Mutex::Autolock _l(mLock);
1293 if (effectCreated) {
1294 chain->removeEffect_l(effect);
1295 }
1296 if (effectRegistered) {
1297 AudioSystem::unregisterEffect(effect->id());
1298 }
1299 if (chainCreated) {
1300 removeEffectChain_l(chain);
1301 }
1302 handle.clear();
1303 }
1304
Glenn Kasten9156ef32013-08-06 15:39:08 -07001305 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001306 return handle;
1307}
1308
1309sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
1310{
1311 Mutex::Autolock _l(mLock);
1312 return getEffect_l(sessionId, effectId);
1313}
1314
1315sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
1316{
1317 sp<EffectChain> chain = getEffectChain_l(sessionId);
1318 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1319}
1320
1321// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1322// PlaybackThread::mLock held
1323status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1324{
1325 // check for existing effect chain with the requested audio session
1326 int sessionId = effect->sessionId();
1327 sp<EffectChain> chain = getEffectChain_l(sessionId);
1328 bool chainCreated = false;
1329
Eric Laurent5baf2af2013-09-12 17:37:00 -07001330 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
1331 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
1332 this, effect->desc().name, effect->desc().flags);
1333
Eric Laurent81784c32012-11-19 14:55:58 -08001334 if (chain == 0) {
1335 // create a new chain for this session
1336 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1337 chain = new EffectChain(this, sessionId);
1338 addEffectChain_l(chain);
1339 chain->setStrategy(getStrategyForSession_l(sessionId));
1340 chainCreated = true;
1341 }
1342 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1343
1344 if (chain->getEffectFromId_l(effect->id()) != 0) {
1345 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1346 this, effect->desc().name, chain.get());
1347 return BAD_VALUE;
1348 }
1349
Eric Laurent5baf2af2013-09-12 17:37:00 -07001350 effect->setOffloaded(mType == OFFLOAD, mId);
1351
Eric Laurent81784c32012-11-19 14:55:58 -08001352 status_t status = chain->addEffect_l(effect);
1353 if (status != NO_ERROR) {
1354 if (chainCreated) {
1355 removeEffectChain_l(chain);
1356 }
1357 return status;
1358 }
1359
1360 effect->setDevice(mOutDevice);
1361 effect->setDevice(mInDevice);
1362 effect->setMode(mAudioFlinger->getMode());
1363 effect->setAudioSource(mAudioSource);
1364 return NO_ERROR;
1365}
1366
1367void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
1368
1369 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
1370 effect_descriptor_t desc = effect->desc();
1371 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1372 detachAuxEffect_l(effect->id());
1373 }
1374
1375 sp<EffectChain> chain = effect->chain().promote();
1376 if (chain != 0) {
1377 // remove effect chain if removing last effect
1378 if (chain->removeEffect_l(effect) == 0) {
1379 removeEffectChain_l(chain);
1380 }
1381 } else {
1382 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1383 }
1384}
1385
1386void AudioFlinger::ThreadBase::lockEffectChains_l(
1387 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1388{
1389 effectChains = mEffectChains;
1390 for (size_t i = 0; i < mEffectChains.size(); i++) {
1391 mEffectChains[i]->lock();
1392 }
1393}
1394
1395void AudioFlinger::ThreadBase::unlockEffectChains(
1396 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1397{
1398 for (size_t i = 0; i < effectChains.size(); i++) {
1399 effectChains[i]->unlock();
1400 }
1401}
1402
1403sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
1404{
1405 Mutex::Autolock _l(mLock);
1406 return getEffectChain_l(sessionId);
1407}
1408
1409sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const
1410{
1411 size_t size = mEffectChains.size();
1412 for (size_t i = 0; i < size; i++) {
1413 if (mEffectChains[i]->sessionId() == sessionId) {
1414 return mEffectChains[i];
1415 }
1416 }
1417 return 0;
1418}
1419
1420void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1421{
1422 Mutex::Autolock _l(mLock);
1423 size_t size = mEffectChains.size();
1424 for (size_t i = 0; i < size; i++) {
1425 mEffectChains[i]->setMode_l(mode);
1426 }
1427}
1428
Eric Laurent83b88082014-06-20 18:31:16 -07001429void AudioFlinger::ThreadBase::getAudioPortConfig(struct audio_port_config *config)
1430{
1431 config->type = AUDIO_PORT_TYPE_MIX;
1432 config->ext.mix.handle = mId;
1433 config->sample_rate = mSampleRate;
1434 config->format = mFormat;
1435 config->channel_mask = mChannelMask;
1436 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1437 AUDIO_PORT_CONFIG_FORMAT;
1438}
1439
Eric Laurent72e3f392015-05-20 14:43:50 -07001440void AudioFlinger::ThreadBase::systemReady()
1441{
1442 Mutex::Autolock _l(mLock);
1443 if (mSystemReady) {
1444 return;
1445 }
1446 mSystemReady = true;
1447
1448 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1449 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1450 }
1451 mPendingConfigEvents.clear();
1452}
1453
Eric Laurent83b88082014-06-20 18:31:16 -07001454
Eric Laurent81784c32012-11-19 14:55:58 -08001455// ----------------------------------------------------------------------------
1456// Playback
1457// ----------------------------------------------------------------------------
1458
1459AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1460 AudioStreamOut* output,
1461 audio_io_handle_t id,
1462 audio_devices_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07001463 type_t type,
1464 bool systemReady)
1465 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type, systemReady),
Andy Hung2098f272014-02-27 14:00:06 -08001466 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001467 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001468 mMixerBuffer(NULL),
1469 mMixerBufferSize(0),
1470 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1471 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001472 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001473 mEffectBuffer(NULL),
1474 mEffectBufferSize(0),
1475 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1476 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001477 mSuspended(0), mBytesWritten(0),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001478 mActiveTracksGeneration(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001479 // mStreamTypes[] initialized in constructor body
1480 mOutput(output),
1481 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
1482 mMixerStatus(MIXER_IDLE),
1483 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001484 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001485 mBytesRemaining(0),
1486 mCurrentWriteLength(0),
1487 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001488 mWriteAckSequence(0),
1489 mDrainSequence(0),
Eric Laurentede6c3b2013-09-19 14:37:46 -07001490 mSignalPending(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001491 mScreenState(AudioFlinger::mScreenState),
1492 // index 0 is reserved for normal mixer's submix
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001493 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1),
Eric Laurentd1f69b02014-12-15 14:33:13 -08001494 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001495 // mLatchD, mLatchQ,
1496 mLatchDValid(false), mLatchQValid(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001497{
Glenn Kastend7dca052015-03-05 16:05:54 -08001498 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1499 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001500
1501 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1502 // it would be safer to explicitly pass initial masterVolume/masterMute as
1503 // parameter.
1504 //
1505 // If the HAL we are using has support for master volume or master mute,
1506 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1507 // and the mute set to false).
1508 mMasterVolume = audioFlinger->masterVolume_l();
1509 mMasterMute = audioFlinger->masterMute_l();
1510 if (mOutput && mOutput->audioHwDev) {
1511 if (mOutput->audioHwDev->canSetMasterVolume()) {
1512 mMasterVolume = 1.0;
1513 }
1514
1515 if (mOutput->audioHwDev->canSetMasterMute()) {
1516 mMasterMute = false;
1517 }
1518 }
1519
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001520 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001521
Eric Laurent223fd5c2014-11-11 13:43:36 -08001522 // ++ operator does not compile
Glenn Kasten66e46352014-01-16 17:44:23 -08001523 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001524 stream = (audio_stream_type_t) (stream + 1)) {
1525 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1526 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1527 }
Eric Laurent81784c32012-11-19 14:55:58 -08001528}
1529
1530AudioFlinger::PlaybackThread::~PlaybackThread()
1531{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001532 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001533 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001534 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001535 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001536}
1537
1538void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1539{
1540 dumpInternals(fd, args);
1541 dumpTracks(fd, args);
1542 dumpEffectChains(fd, args);
1543}
1544
Glenn Kasten0f11b512014-01-31 16:18:54 -08001545void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001546{
1547 const size_t SIZE = 256;
1548 char buffer[SIZE];
1549 String8 result;
1550
Marco Nelissenb2208842014-02-07 14:00:50 -08001551 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001552 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1553 const stream_type_t *st = &mStreamTypes[i];
1554 if (i > 0) {
1555 result.appendFormat(", ");
1556 }
1557 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1558 if (st->mute) {
1559 result.append("M");
1560 }
1561 }
1562 result.append("\n");
1563 write(fd, result.string(), result.length());
1564 result.clear();
1565
Eric Laurent81784c32012-11-19 14:55:58 -08001566 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1567 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001568 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001569 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001570
1571 size_t numtracks = mTracks.size();
1572 size_t numactive = mActiveTracks.size();
Elliott Hughes87cebad2014-05-22 10:14:43 -07001573 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001574 size_t numactiveseen = 0;
1575 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07001576 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08001577 Track::appendDumpHeader(result);
1578 for (size_t i = 0; i < numtracks; ++i) {
1579 sp<Track> track = mTracks[i];
1580 if (track != 0) {
1581 bool active = mActiveTracks.indexOf(track) >= 0;
1582 if (active) {
1583 numactiveseen++;
1584 }
1585 track->dump(buffer, SIZE, active);
1586 result.append(buffer);
1587 }
1588 }
1589 } else {
1590 result.append("\n");
1591 }
1592 if (numactiveseen != numactive) {
1593 // some tracks in the active list were not in the tracks list
1594 snprintf(buffer, SIZE, " The following tracks are in the active list but"
1595 " not in the track list\n");
1596 result.append(buffer);
1597 Track::appendDumpHeader(result);
1598 for (size_t i = 0; i < numactive; ++i) {
1599 sp<Track> track = mActiveTracks[i].promote();
1600 if (track != 0 && mTracks.indexOf(track) < 0) {
1601 track->dump(buffer, SIZE, true);
1602 result.append(buffer);
1603 }
1604 }
1605 }
1606
1607 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001608}
1609
1610void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1611{
Glenn Kasten97b7b752014-09-28 13:04:24 -07001612 dprintf(fd, "\nOutput thread %p type %d (%s):\n", this, type(), threadTypeToString(type()));
Glenn Kasten44182c22015-03-05 17:12:23 -08001613
1614 dumpBase(fd, args);
1615
Elliott Hughes87cebad2014-05-22 10:14:43 -07001616 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
1617 dprintf(fd, " Last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1618 dprintf(fd, " Total writes: %d\n", mNumWrites);
1619 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1620 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1621 dprintf(fd, " Suspend count: %d\n", mSuspended);
1622 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1623 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1624 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1625 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001626 AudioStreamOut *output = mOutput;
1627 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
1628 String8 flagsAsString = outputFlagsToString(flags);
1629 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n", output, flags, flagsAsString.string());
Eric Laurent81784c32012-11-19 14:55:58 -08001630}
1631
1632// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001633
1634void AudioFlinger::PlaybackThread::onFirstRef()
1635{
Glenn Kastend7dca052015-03-05 16:05:54 -08001636 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001637}
1638
1639// ThreadBase virtuals
1640void AudioFlinger::PlaybackThread::preExit()
1641{
1642 ALOGV(" preExit()");
1643 // FIXME this is using hard-coded strings but in the future, this functionality will be
1644 // converted to use audio HAL extensions required to support tunneling
1645 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1646}
1647
1648// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1649sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1650 const sp<AudioFlinger::Client>& client,
1651 audio_stream_type_t streamType,
1652 uint32_t sampleRate,
1653 audio_format_t format,
1654 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001655 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001656 const sp<IMemory>& sharedBuffer,
1657 int sessionId,
1658 IAudioFlinger::track_flags_t *flags,
1659 pid_t tid,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001660 int uid,
Eric Laurent81784c32012-11-19 14:55:58 -08001661 status_t *status)
1662{
Glenn Kasten74935e42013-12-19 08:56:45 -08001663 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001664 sp<Track> track;
1665 status_t lStatus;
1666
1667 bool isTimed = (*flags & IAudioFlinger::TRACK_TIMED) != 0;
1668
1669 // client expresses a preference for FAST, but we get the final say
1670 if (*flags & IAudioFlinger::TRACK_FAST) {
1671 if (
1672 // not timed
1673 (!isTimed) &&
1674 // either of these use cases:
1675 (
1676 // use case 1: shared buffer with any frame count
1677 (
1678 (sharedBuffer != 0)
1679 ) ||
Glenn Kasten1dfe2f92015-03-09 12:03:14 -07001680 // use case 2: frame count is default or at least as large as HAL
Eric Laurent81784c32012-11-19 14:55:58 -08001681 (
Glenn Kasten1dfe2f92015-03-09 12:03:14 -07001682 // we formerly checked for a callback handler (non-0 tid),
1683 // but that is no longer required for TRANSFER_OBTAIN mode
Eric Laurent81784c32012-11-19 14:55:58 -08001684 ((frameCount == 0) ||
Glenn Kastenb5fed682013-12-03 09:06:43 -08001685 (frameCount >= mFrameCount))
Eric Laurent81784c32012-11-19 14:55:58 -08001686 )
1687 ) &&
1688 // PCM data
1689 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07001690 // TODO: extract as a data library function that checks that a computationally
1691 // expensive downmixer is not required: isFastOutputChannelConversion()
Andy Hung9a592762014-07-21 21:56:01 -07001692 (channelMask == mChannelMask ||
Andy Hung1f439e12015-05-19 12:57:41 -07001693 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
1694 (channelMask == AUDIO_CHANNEL_OUT_MONO
1695 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001696 // hardware sample rate
1697 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001698 // normal mixer has an associated fast mixer
1699 hasFastMixer() &&
1700 // there are sufficient fast track slots available
1701 (mFastTrackAvailMask != 0)
1702 // FIXME test that MixerThread for this fast track has a capable output HAL
1703 // FIXME add a permission test also?
1704 ) {
1705 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1706 if (frameCount == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001707 // read the fast track multiplier property the first time it is needed
1708 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1709 if (ok != 0) {
1710 ALOGE("%s pthread_once failed: %d", __func__, ok);
1711 }
1712 frameCount = mFrameCount * sFastTrackMultiplier;
Eric Laurent81784c32012-11-19 14:55:58 -08001713 }
1714 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
1715 frameCount, mFrameCount);
1716 } else {
1717 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
Andy Hung6146c082014-03-18 11:56:15 -07001718 "mFrameCount=%d format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
1719 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001720 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Andy Hung6146c082014-03-18 11:56:15 -07001721 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001722 audio_is_linear_pcm(format),
1723 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
1724 *flags &= ~IAudioFlinger::TRACK_FAST;
Andy Hung0e48d252015-01-26 11:43:15 -08001725 }
1726 }
1727 // For normal PCM streaming tracks, update minimum frame count.
1728 // For compatibility with AudioTrack calculation, buffer depth is forced
1729 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1730 // This is probably too conservative, but legacy application code may depend on it.
1731 // If you change this calculation, also review the start threshold which is related.
1732 if (!(*flags & IAudioFlinger::TRACK_FAST)
1733 && audio_is_linear_pcm(format) && sharedBuffer == 0) {
Andy Hung8edb8dc2015-03-26 19:13:55 -07001734 // this must match AudioTrack.cpp calculateMinFrameCount().
1735 // TODO: Move to a common library
Eric Laurent81784c32012-11-19 14:55:58 -08001736 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1737 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1738 if (minBufCount < 2) {
1739 minBufCount = 2;
1740 }
Andy Hung8edb8dc2015-03-26 19:13:55 -07001741 // For normal mixing tracks, if speed is > 1.0f (normal), AudioTrack
1742 // or the client should compute and pass in a larger buffer request.
Andy Hung0e48d252015-01-26 11:43:15 -08001743 size_t minFrameCount =
Andy Hung8edb8dc2015-03-26 19:13:55 -07001744 minBufCount * sourceFramesNeededWithTimestretch(
1745 sampleRate, mNormalFrameCount,
1746 mSampleRate, AUDIO_TIMESTRETCH_SPEED_NORMAL /*speed*/);
Andy Hung0e48d252015-01-26 11:43:15 -08001747 if (frameCount < minFrameCount) { // including frameCount == 0
Eric Laurent81784c32012-11-19 14:55:58 -08001748 frameCount = minFrameCount;
1749 }
Eric Laurent81784c32012-11-19 14:55:58 -08001750 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001751 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001752
Glenn Kastenc3df8382014-03-13 15:05:25 -07001753 switch (mType) {
1754
1755 case DIRECT:
Glenn Kasten993fa062014-05-02 11:14:34 -07001756 if (audio_is_linear_pcm(format)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001757 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001758 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1759 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001760 sampleRate, format, channelMask, mOutput, mFormat);
1761 lStatus = BAD_VALUE;
1762 goto Exit;
1763 }
1764 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001765 break;
1766
1767 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001768 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001769 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1770 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001771 sampleRate, format, channelMask, mOutput, mFormat);
1772 lStatus = BAD_VALUE;
1773 goto Exit;
1774 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001775 break;
1776
1777 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07001778 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001779 ALOGE("createTrack_l() Bad parameter: format %#x \""
1780 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001781 format, mOutput, mFormat);
1782 lStatus = BAD_VALUE;
1783 goto Exit;
1784 }
Andy Hungcd044842014-08-07 11:04:34 -07001785 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08001786 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1787 lStatus = BAD_VALUE;
1788 goto Exit;
1789 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001790 break;
1791
Eric Laurent81784c32012-11-19 14:55:58 -08001792 }
1793
1794 lStatus = initCheck();
1795 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07001796 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08001797 goto Exit;
1798 }
1799
1800 { // scope for mLock
1801 Mutex::Autolock _l(mLock);
1802
1803 // all tracks in same audio session must share the same routing strategy otherwise
1804 // conflicts will happen when tracks are moved from one output to another by audio policy
1805 // manager
1806 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1807 for (size_t i = 0; i < mTracks.size(); ++i) {
1808 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07001809 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001810 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1811 if (sessionId == t->sessionId() && strategy != actual) {
1812 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1813 strategy, actual);
1814 lStatus = BAD_VALUE;
1815 goto Exit;
1816 }
1817 }
1818 }
1819
1820 if (!isTimed) {
1821 track = new Track(this, client, streamType, sampleRate, format,
Eric Laurent83b88082014-06-20 18:31:16 -07001822 channelMask, frameCount, NULL, sharedBuffer,
1823 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08001824 } else {
1825 track = TimedTrack::create(this, client, streamType, sampleRate, format,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001826 channelMask, frameCount, sharedBuffer, sessionId, uid);
Eric Laurent81784c32012-11-19 14:55:58 -08001827 }
Glenn Kasten03003332013-08-06 15:40:54 -07001828
1829 // new Track always returns non-NULL,
1830 // but TimedTrack::create() is a factory that could fail by returning NULL
1831 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
1832 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08001833 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001834 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08001835 goto Exit;
1836 }
1837 mTracks.add(track);
1838
1839 sp<EffectChain> chain = getEffectChain_l(sessionId);
1840 if (chain != 0) {
1841 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1842 track->setMainBuffer(chain->inBuffer());
1843 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1844 chain->incTrackCnt();
1845 }
1846
1847 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1848 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1849 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1850 // so ask activity manager to do this on our behalf
1851 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1852 }
1853 }
1854
1855 lStatus = NO_ERROR;
1856
1857Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001858 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001859 return track;
1860}
1861
1862uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1863{
1864 return latency;
1865}
1866
1867uint32_t AudioFlinger::PlaybackThread::latency() const
1868{
1869 Mutex::Autolock _l(mLock);
1870 return latency_l();
1871}
1872uint32_t AudioFlinger::PlaybackThread::latency_l() const
1873{
1874 if (initCheck() == NO_ERROR) {
1875 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
1876 } else {
1877 return 0;
1878 }
1879}
1880
1881void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1882{
1883 Mutex::Autolock _l(mLock);
1884 // Don't apply master volume in SW if our HAL can do it for us.
1885 if (mOutput && mOutput->audioHwDev &&
1886 mOutput->audioHwDev->canSetMasterVolume()) {
1887 mMasterVolume = 1.0;
1888 } else {
1889 mMasterVolume = value;
1890 }
1891}
1892
1893void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1894{
1895 Mutex::Autolock _l(mLock);
1896 // Don't apply master mute in SW if our HAL can do it for us.
1897 if (mOutput && mOutput->audioHwDev &&
1898 mOutput->audioHwDev->canSetMasterMute()) {
1899 mMasterMute = false;
1900 } else {
1901 mMasterMute = muted;
1902 }
1903}
1904
1905void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
1906{
1907 Mutex::Autolock _l(mLock);
1908 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001909 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001910}
1911
1912void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
1913{
1914 Mutex::Autolock _l(mLock);
1915 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001916 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001917}
1918
1919float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
1920{
1921 Mutex::Autolock _l(mLock);
1922 return mStreamTypes[stream].volume;
1923}
1924
1925// addTrack_l() must be called with ThreadBase::mLock held
1926status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1927{
1928 status_t status = ALREADY_EXISTS;
1929
1930 // set retry count for buffer fill
1931 track->mRetryCount = kMaxTrackStartupRetries;
1932 if (mActiveTracks.indexOf(track) < 0) {
1933 // the track is newly added, make sure it fills up all its
1934 // buffers before playing. This is to ensure the client will
1935 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07001936 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001937 TrackBase::track_state state = track->mState;
1938 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08001939 status = AudioSystem::startOutput(mId, track->streamType(),
1940 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001941 mLock.lock();
1942 // abort track was stopped/paused while we released the lock
1943 if (state != track->mState) {
1944 if (status == NO_ERROR) {
1945 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08001946 AudioSystem::stopOutput(mId, track->streamType(),
1947 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001948 mLock.lock();
1949 }
1950 return INVALID_OPERATION;
1951 }
1952 // abort if start is rejected by audio policy manager
1953 if (status != NO_ERROR) {
1954 return PERMISSION_DENIED;
1955 }
1956#ifdef ADD_BATTERY_DATA
1957 // to track the speaker usage
1958 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
1959#endif
1960 }
1961
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001962 track->mFillingUpStatus = track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent81784c32012-11-19 14:55:58 -08001963 track->mResetDone = false;
1964 track->mPresentationCompleteFrames = 0;
1965 mActiveTracks.add(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001966 mWakeLockUids.add(track->uid());
1967 mActiveTracksGeneration++;
Eric Laurentfd477972013-10-25 18:10:40 -07001968 mLatestActiveTrack = track;
Eric Laurentd0107bc2013-06-11 14:38:48 -07001969 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1970 if (chain != 0) {
1971 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
1972 track->sessionId());
1973 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08001974 }
1975
1976 status = NO_ERROR;
1977 }
1978
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08001979 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001980 return status;
1981}
1982
Eric Laurentbfb1b832013-01-07 09:53:42 -08001983bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08001984{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001985 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08001986 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001987 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
1988 track->mState = TrackBase::STOPPED;
1989 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08001990 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07001991 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001992 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08001993 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001994
1995 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08001996}
1997
1998void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1999{
2000 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
2001 mTracks.remove(track);
2002 deleteTrackName_l(track->name());
2003 // redundant as track is about to be destroyed, for dumpsys only
2004 track->mName = -1;
2005 if (track->isFastTrack()) {
2006 int index = track->mFastIndex;
2007 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
2008 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2009 mFastTrackAvailMask |= 1 << index;
2010 // redundant as track is about to be destroyed, for dumpsys only
2011 track->mFastIndex = -1;
2012 }
2013 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2014 if (chain != 0) {
2015 chain->decTrackCnt();
2016 }
2017}
2018
Eric Laurentede6c3b2013-09-19 14:37:46 -07002019void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002020{
2021 // Thread could be blocked waiting for async
2022 // so signal it to handle state changes immediately
2023 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
2024 // be lost so we also flag to prevent it blocking on mWaitWorkCV
2025 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002026 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002027}
2028
Eric Laurent81784c32012-11-19 14:55:58 -08002029String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2030{
Eric Laurent81784c32012-11-19 14:55:58 -08002031 Mutex::Autolock _l(mLock);
2032 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07002033 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002034 }
2035
Glenn Kastend8ea6992013-07-16 14:17:15 -07002036 char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
2037 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08002038 free(s);
2039 return out_s8;
2040}
2041
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002042void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002043 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2044 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002045
Eric Laurent73e26b62015-04-27 16:55:58 -07002046 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002047
2048 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002049 case AUDIO_OUTPUT_OPENED:
2050 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002051 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002052 desc->mChannelMask = mChannelMask;
2053 desc->mSamplingRate = mSampleRate;
2054 desc->mFormat = mFormat;
2055 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002056 // AudioFlinger::frameCount(audio_io_handle_t)
Eric Laurent73e26b62015-04-27 16:55:58 -07002057 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002058 break;
2059
Eric Laurent73e26b62015-04-27 16:55:58 -07002060 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002061 default:
2062 break;
2063 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002064 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002065}
2066
Eric Laurentbfb1b832013-01-07 09:53:42 -08002067void AudioFlinger::PlaybackThread::writeCallback()
2068{
2069 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002070 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002071}
2072
2073void AudioFlinger::PlaybackThread::drainCallback()
2074{
2075 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002076 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002077}
2078
Eric Laurent3b4529e2013-09-05 18:09:19 -07002079void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002080{
2081 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002082 // reject out of sequence requests
2083 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2084 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002085 mWaitWorkCV.signal();
2086 }
2087}
2088
Eric Laurent3b4529e2013-09-05 18:09:19 -07002089void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002090{
2091 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002092 // reject out of sequence requests
2093 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
2094 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002095 mWaitWorkCV.signal();
2096 }
2097}
2098
2099// static
2100int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
Glenn Kasten0f11b512014-01-31 16:18:54 -08002101 void *param __unused,
Eric Laurentbfb1b832013-01-07 09:53:42 -08002102 void *cookie)
2103{
2104 AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
2105 ALOGV("asyncCallback() event %d", event);
2106 switch (event) {
2107 case STREAM_CBK_EVENT_WRITE_READY:
2108 me->writeCallback();
2109 break;
2110 case STREAM_CBK_EVENT_DRAIN_READY:
2111 me->drainCallback();
2112 break;
2113 default:
2114 ALOGW("asyncCallback() unknown event %d", event);
2115 break;
2116 }
2117 return 0;
2118}
2119
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002120void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002121{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002122 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Phil Burkca5e6142015-07-14 09:42:29 -07002123 mSampleRate = mOutput->getSampleRate();
2124 mChannelMask = mOutput->getChannelMask();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002125 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002126 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002127 }
Andy Hung9a592762014-07-21 21:56:01 -07002128 if ((mType == MIXER || mType == DUPLICATING)
2129 && !isValidPcmSinkChannelMask(mChannelMask)) {
2130 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2131 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002132 }
Andy Hunge5412692014-05-16 11:25:07 -07002133 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002134
2135 // Get actual HAL format.
Andy Hung463be252014-07-10 16:56:07 -07002136 mHALFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Phil Burkca5e6142015-07-14 09:42:29 -07002137 // Get format from the shim, which will be different than the HAL format
2138 // if playing compressed audio over HDMI passthrough.
2139 mFormat = mOutput->getFormat();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002140 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002141 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002142 }
Andy Hung6146c082014-03-18 11:56:15 -07002143 if ((mType == MIXER || mType == DUPLICATING)
2144 && !isValidPcmSinkFormat(mFormat)) {
2145 LOG_FATAL("HAL format %#x not supported for mixed output",
2146 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002147 }
Phil Burk062e67a2015-02-11 13:40:50 -08002148 mFrameSize = mOutput->getFrameSize();
Glenn Kasten70949c42013-08-06 07:40:12 -07002149 mBufferSize = mOutput->stream->common.get_buffer_size(&mOutput->stream->common);
2150 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002151 if (mFrameCount & 15) {
2152 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
2153 mFrameCount);
2154 }
2155
Eric Laurentbfb1b832013-01-07 09:53:42 -08002156 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
2157 (mOutput->stream->set_callback != NULL)) {
2158 if (mOutput->stream->set_callback(mOutput->stream,
2159 AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
2160 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002161 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002162 }
2163 }
2164
Eric Laurentd1f69b02014-12-15 14:33:13 -08002165 mHwSupportsPause = false;
2166 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
2167 if (mOutput->stream->pause != NULL) {
2168 if (mOutput->stream->resume != NULL) {
2169 mHwSupportsPause = true;
2170 } else {
2171 ALOGW("direct output implements pause but not resume");
2172 }
2173 } else if (mOutput->stream->resume != NULL) {
2174 ALOGW("direct output implements resume but not pause");
2175 }
2176 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002177 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2178 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2179 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002180
Andy Hungfbfc3952015-01-15 13:33:51 -08002181 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2182 // For best precision, we use float instead of the associated output
2183 // device format (typically PCM 16 bit).
2184
2185 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2186 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2187 mBufferSize = mFrameSize * mFrameCount;
2188
2189 // TODO: We currently use the associated output device channel mask and sample rate.
2190 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2191 // (if a valid mask) to avoid premature downmix.
2192 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2193 // instead of the output device sample rate to avoid loss of high frequency information.
2194 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2195 }
2196
Andy Hung09a50072014-02-27 14:30:47 -08002197 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002198 double multiplier = 1.0;
2199 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2200 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002201 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2202 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Eric Laurent81784c32012-11-19 14:55:58 -08002203 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2204 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2205 maxNormalFrameCount = maxNormalFrameCount & ~15;
2206 if (maxNormalFrameCount < minNormalFrameCount) {
2207 maxNormalFrameCount = minNormalFrameCount;
2208 }
2209 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2210 if (multiplier <= 1.0) {
2211 multiplier = 1.0;
2212 } else if (multiplier <= 2.0) {
2213 if (2 * mFrameCount <= maxNormalFrameCount) {
2214 multiplier = 2.0;
2215 } else {
2216 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2217 }
2218 } else {
2219 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
Andy Hung09a50072014-02-27 14:30:47 -08002220 // 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 -08002221 // track, but we sometimes have to do this to satisfy the maximum frame count
2222 // constraint)
2223 // FIXME this rounding up should not be done if no HAL SRC
2224 uint32_t truncMult = (uint32_t) multiplier;
2225 if ((truncMult & 1)) {
2226 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
2227 ++truncMult;
2228 }
2229 }
2230 multiplier = (double) truncMult;
2231 }
2232 }
2233 mNormalFrameCount = multiplier * mFrameCount;
2234 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002235 if (mType == MIXER || mType == DUPLICATING) {
2236 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2237 }
Andy Hung09a50072014-02-27 14:30:47 -08002238 ALOGI("HAL output buffer size %u frames, normal sink buffer size %u frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002239 mNormalFrameCount);
2240
Andy Hung08fb1742015-05-31 23:22:10 -07002241 // Check if we want to throttle the processing to no more than 2x normal rate
2242 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002243 mThreadThrottleTimeMs = 0;
2244 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002245 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2246
Andy Hung010a1a12014-03-13 13:57:33 -07002247 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2248 // Originally this was int16_t[] array, need to remove legacy implications.
2249 free(mSinkBuffer);
2250 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002251 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2252 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2253 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002254 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002255
Andy Hung69aed5f2014-02-25 17:24:40 -08002256 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2257 // drives the output.
2258 free(mMixerBuffer);
2259 mMixerBuffer = NULL;
2260 if (mMixerBufferEnabled) {
2261 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2262 mMixerBufferSize = mNormalFrameCount * mChannelCount
2263 * audio_bytes_per_sample(mMixerBufferFormat);
2264 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2265 }
Andy Hung98ef9782014-03-04 14:46:50 -08002266 free(mEffectBuffer);
2267 mEffectBuffer = NULL;
2268 if (mEffectBufferEnabled) {
2269 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
2270 mEffectBufferSize = mNormalFrameCount * mChannelCount
2271 * audio_bytes_per_sample(mEffectBufferFormat);
2272 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2273 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002274
Eric Laurent81784c32012-11-19 14:55:58 -08002275 // force reconfiguration of effect chains and engines to take new buffer size and audio
2276 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002277 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002278 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2279 // matter.
2280 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2281 Vector< sp<EffectChain> > effectChains = mEffectChains;
2282 for (size_t i = 0; i < effectChains.size(); i ++) {
2283 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2284 }
2285}
2286
2287
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002288status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002289{
2290 if (halFrames == NULL || dspFrames == NULL) {
2291 return BAD_VALUE;
2292 }
2293 Mutex::Autolock _l(mLock);
2294 if (initCheck() != NO_ERROR) {
2295 return INVALID_OPERATION;
2296 }
2297 size_t framesWritten = mBytesWritten / mFrameSize;
2298 *halFrames = framesWritten;
2299
2300 if (isSuspended()) {
2301 // return an estimation of rendered frames when the output is suspended
2302 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
2303 *dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0;
2304 return NO_ERROR;
2305 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002306 status_t status;
2307 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002308 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002309 *dspFrames = (size_t)frames;
2310 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002311 }
2312}
2313
2314uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
2315{
2316 Mutex::Autolock _l(mLock);
2317 uint32_t result = 0;
2318 if (getEffectChain_l(sessionId) != 0) {
2319 result = EFFECT_SESSION;
2320 }
2321
2322 for (size_t i = 0; i < mTracks.size(); ++i) {
2323 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002324 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002325 result |= TRACK_SESSION;
2326 break;
2327 }
2328 }
2329
2330 return result;
2331}
2332
2333uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
2334{
2335 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2336 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2337 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2338 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2339 }
2340 for (size_t i = 0; i < mTracks.size(); i++) {
2341 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002342 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002343 return AudioSystem::getStrategyForStream(track->streamType());
2344 }
2345 }
2346 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2347}
2348
2349
Phil Burk062e67a2015-02-11 13:40:50 -08002350AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002351{
2352 Mutex::Autolock _l(mLock);
2353 return mOutput;
2354}
2355
Phil Burk062e67a2015-02-11 13:40:50 -08002356AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002357{
2358 Mutex::Autolock _l(mLock);
2359 AudioStreamOut *output = mOutput;
2360 mOutput = NULL;
2361 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2362 // must push a NULL and wait for ack
2363 mOutputSink.clear();
2364 mPipeSink.clear();
2365 mNormalSink.clear();
2366 return output;
2367}
2368
2369// this method must always be called either with ThreadBase mLock held or inside the thread loop
2370audio_stream_t* AudioFlinger::PlaybackThread::stream() const
2371{
2372 if (mOutput == NULL) {
2373 return NULL;
2374 }
2375 return &mOutput->stream->common;
2376}
2377
2378uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2379{
2380 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2381}
2382
2383status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2384{
2385 if (!isValidSyncEvent(event)) {
2386 return BAD_VALUE;
2387 }
2388
2389 Mutex::Autolock _l(mLock);
2390
2391 for (size_t i = 0; i < mTracks.size(); ++i) {
2392 sp<Track> track = mTracks[i];
2393 if (event->triggerSession() == track->sessionId()) {
2394 (void) track->setSyncEvent(event);
2395 return NO_ERROR;
2396 }
2397 }
2398
2399 return NAME_NOT_FOUND;
2400}
2401
2402bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2403{
2404 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2405}
2406
2407void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2408 const Vector< sp<Track> >& tracksToRemove)
2409{
2410 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002411 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002412 for (size_t i = 0 ; i < count ; i++) {
2413 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002414 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002415 AudioSystem::stopOutput(mId, track->streamType(),
2416 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002417#ifdef ADD_BATTERY_DATA
2418 // to track the speaker usage
2419 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2420#endif
2421 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002422 AudioSystem::releaseOutput(mId, track->streamType(),
2423 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002424 }
Eric Laurent81784c32012-11-19 14:55:58 -08002425 }
2426 }
2427 }
Eric Laurent81784c32012-11-19 14:55:58 -08002428}
2429
2430void AudioFlinger::PlaybackThread::checkSilentMode_l()
2431{
2432 if (!mMasterMute) {
2433 char value[PROPERTY_VALUE_MAX];
2434 if (property_get("ro.audio.silent", value, "0") > 0) {
2435 char *endptr;
2436 unsigned long ul = strtoul(value, &endptr, 0);
2437 if (*endptr == '\0' && ul != 0) {
2438 ALOGD("Silence is golden");
2439 // The setprop command will not allow a property to be changed after
2440 // the first time it is set, so we don't have to worry about un-muting.
2441 setMasterMute_l(true);
2442 }
2443 }
2444 }
2445}
2446
2447// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002448ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002449{
2450 // FIXME rewrite to reduce number of system calls
2451 mLastWriteTime = systemTime();
2452 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002453 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002454 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002455
2456 // If an NBAIO sink is present, use it to write the normal mixer's submix
2457 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002458
Andy Hung010a1a12014-03-13 13:57:33 -07002459 const size_t count = mBytesRemaining / mFrameSize;
2460
Simon Wilson2d590962012-11-29 15:18:50 -08002461 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002462 // update the setpoint when AudioFlinger::mScreenState changes
2463 uint32_t screenState = AudioFlinger::mScreenState;
2464 if (screenState != mScreenState) {
2465 mScreenState = screenState;
2466 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2467 if (pipe != NULL) {
2468 pipe->setAvgFrames((mScreenState & 1) ?
2469 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2470 }
2471 }
Andy Hung010a1a12014-03-13 13:57:33 -07002472 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002473 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002474 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002475 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002476 } else {
2477 bytesWritten = framesWritten;
2478 }
Glenn Kastenefaa7ab2014-08-20 08:48:54 -07002479 mLatchDValid = false;
Glenn Kasten767094d2013-08-23 13:51:43 -07002480 status_t status = mNormalSink->getTimestamp(mLatchD.mTimestamp);
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002481 if (status == NO_ERROR) {
2482 size_t totalFramesWritten = mNormalSink->framesWritten();
2483 if (totalFramesWritten >= mLatchD.mTimestamp.mPosition) {
2484 mLatchD.mUnpresentedFrames = totalFramesWritten - mLatchD.mTimestamp.mPosition;
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002485 // mLatchD.mFramesReleased is set immediately before D is clocked into Q
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002486 mLatchDValid = true;
2487 }
2488 }
Eric Laurent81784c32012-11-19 14:55:58 -08002489 // otherwise use the HAL / AudioStreamOut directly
2490 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002491 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002492
Eric Laurentbfb1b832013-01-07 09:53:42 -08002493 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002494 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2495 mWriteAckSequence += 2;
2496 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002497 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002498 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002499 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002500 // FIXME We should have an implementation of timestamps for direct output threads.
2501 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002502 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002503 if (mUseAsyncWrite &&
2504 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2505 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002506 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002507 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002508 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002509 }
Eric Laurent81784c32012-11-19 14:55:58 -08002510 }
2511
Eric Laurent81784c32012-11-19 14:55:58 -08002512 mNumWrites++;
2513 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002514 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002515 return bytesWritten;
2516}
2517
2518void AudioFlinger::PlaybackThread::threadLoop_drain()
2519{
2520 if (mOutput->stream->drain) {
2521 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2522 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002523 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2524 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002525 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002526 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002527 }
2528 mOutput->stream->drain(mOutput->stream,
2529 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
2530 : AUDIO_DRAIN_ALL);
2531 }
2532}
2533
2534void AudioFlinger::PlaybackThread::threadLoop_exit()
2535{
Eric Laurent275e8e92014-11-30 15:14:47 -08002536 {
2537 Mutex::Autolock _l(mLock);
2538 for (size_t i = 0; i < mTracks.size(); i++) {
2539 sp<Track> track = mTracks[i];
2540 track->invalidate();
2541 }
2542 }
Eric Laurent81784c32012-11-19 14:55:58 -08002543}
2544
2545/*
2546The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002547 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002548 - mActiveSleepTimeUs from activeSleepTimeUs()
2549 - mIdleSleepTimeUs from idleSleepTimeUs()
2550 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only)
Eric Laurent81784c32012-11-19 14:55:58 -08002551 - maxPeriod from frame count and sample rate (MIXER only)
2552
2553The parameters that affect these derived values are:
2554 - frame count
2555 - frame size
2556 - sample rate
2557 - device type: A2DP or not
2558 - device latency
2559 - format: PCM or not
2560 - active sleep time
2561 - idle sleep time
2562*/
2563
2564void AudioFlinger::PlaybackThread::cacheParameters_l()
2565{
Andy Hung25c2dac2014-02-27 14:56:00 -08002566 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002567 mActiveSleepTimeUs = activeSleepTimeUs();
2568 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent81784c32012-11-19 14:55:58 -08002569}
2570
2571void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2572{
Glenn Kasten7c027242012-12-26 14:43:16 -08002573 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurent81784c32012-11-19 14:55:58 -08002574 this, streamType, mTracks.size());
2575 Mutex::Autolock _l(mLock);
2576
2577 size_t size = mTracks.size();
2578 for (size_t i = 0; i < size; i++) {
2579 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07002580 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002581 t->invalidate();
Eric Laurent81784c32012-11-19 14:55:58 -08002582 }
2583 }
2584}
2585
2586status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2587{
2588 int session = chain->sessionId();
Andy Hung010a1a12014-03-13 13:57:33 -07002589 int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled
2590 ? mEffectBuffer : mSinkBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002591 bool ownsBuffer = false;
2592
2593 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
2594 if (session > 0) {
2595 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002596 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002597 if (mType != DIRECT) {
2598 size_t numSamples = mNormalFrameCount * mChannelCount;
2599 buffer = new int16_t[numSamples];
2600 memset(buffer, 0, numSamples * sizeof(int16_t));
2601 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2602 ownsBuffer = true;
2603 }
2604
2605 // Attach all tracks with same session ID to this chain.
2606 for (size_t i = 0; i < mTracks.size(); ++i) {
2607 sp<Track> track = mTracks[i];
2608 if (session == track->sessionId()) {
2609 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2610 buffer);
2611 track->setMainBuffer(buffer);
2612 chain->incTrackCnt();
2613 }
2614 }
2615
2616 // indicate all active tracks in the chain
2617 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2618 sp<Track> track = mActiveTracks[i].promote();
2619 if (track == 0) {
2620 continue;
2621 }
2622 if (session == track->sessionId()) {
2623 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2624 chain->incActiveTrackCnt();
2625 }
2626 }
2627 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002628 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08002629 chain->setInBuffer(buffer, ownsBuffer);
Andy Hung010a1a12014-03-13 13:57:33 -07002630 chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled
2631 ? mEffectBuffer : mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002632 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
2633 // chains list in order to be processed last as it contains output stage effects
2634 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2635 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
2636 // after track specific effects and before output stage
2637 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
2638 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
2639 // Effect chain for other sessions are inserted at beginning of effect
2640 // chains list to be processed before output mix effects. Relative order between other
2641 // sessions is not important
2642 size_t size = mEffectChains.size();
2643 size_t i = 0;
2644 for (i = 0; i < size; i++) {
2645 if (mEffectChains[i]->sessionId() < session) {
2646 break;
2647 }
2648 }
2649 mEffectChains.insertAt(chain, i);
2650 checkSuspendOnAddEffectChain_l(chain);
2651
2652 return NO_ERROR;
2653}
2654
2655size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2656{
2657 int session = chain->sessionId();
2658
2659 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2660
2661 for (size_t i = 0; i < mEffectChains.size(); i++) {
2662 if (chain == mEffectChains[i]) {
2663 mEffectChains.removeAt(i);
2664 // detach all active tracks from the chain
2665 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2666 sp<Track> track = mActiveTracks[i].promote();
2667 if (track == 0) {
2668 continue;
2669 }
2670 if (session == track->sessionId()) {
2671 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2672 chain.get(), session);
2673 chain->decActiveTrackCnt();
2674 }
2675 }
2676
2677 // detach all tracks with same session ID from this chain
2678 for (size_t i = 0; i < mTracks.size(); ++i) {
2679 sp<Track> track = mTracks[i];
2680 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002681 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002682 chain->decTrackCnt();
2683 }
2684 }
2685 break;
2686 }
2687 }
2688 return mEffectChains.size();
2689}
2690
2691status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2692 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2693{
2694 Mutex::Autolock _l(mLock);
2695 return attachAuxEffect_l(track, EffectId);
2696}
2697
2698status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2699 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2700{
2701 status_t status = NO_ERROR;
2702
2703 if (EffectId == 0) {
2704 track->setAuxBuffer(0, NULL);
2705 } else {
2706 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2707 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2708 if (effect != 0) {
2709 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2710 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2711 } else {
2712 status = INVALID_OPERATION;
2713 }
2714 } else {
2715 status = BAD_VALUE;
2716 }
2717 }
2718 return status;
2719}
2720
2721void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2722{
2723 for (size_t i = 0; i < mTracks.size(); ++i) {
2724 sp<Track> track = mTracks[i];
2725 if (track->auxEffectId() == effectId) {
2726 attachAuxEffect_l(track, 0);
2727 }
2728 }
2729}
2730
2731bool AudioFlinger::PlaybackThread::threadLoop()
2732{
2733 Vector< sp<Track> > tracksToRemove;
2734
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002735 mStandbyTimeNs = systemTime();
Eric Laurent81784c32012-11-19 14:55:58 -08002736
2737 // MIXER
2738 nsecs_t lastWarning = 0;
2739
2740 // DUPLICATING
2741 // FIXME could this be made local to while loop?
2742 writeFrames = 0;
2743
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002744 int lastGeneration = 0;
2745
Eric Laurent81784c32012-11-19 14:55:58 -08002746 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002747 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08002748
2749 if (mType == MIXER) {
2750 sleepTimeShift = 0;
2751 }
2752
2753 CpuStats cpuStats;
2754 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2755
2756 acquireWakeLock();
2757
Glenn Kasten9e58b552013-01-18 15:09:48 -08002758 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2759 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2760 // and then that string will be logged at the next convenient opportunity.
2761 const char *logString = NULL;
2762
Eric Laurent664539d2013-09-23 18:24:31 -07002763 checkSilentMode_l();
2764
Eric Laurent81784c32012-11-19 14:55:58 -08002765 while (!exitPending())
2766 {
2767 cpuStats.sample(myName);
2768
2769 Vector< sp<EffectChain> > effectChains;
2770
Eric Laurent81784c32012-11-19 14:55:58 -08002771 { // scope for mLock
2772
2773 Mutex::Autolock _l(mLock);
2774
Eric Laurent021cf962014-05-13 10:18:14 -07002775 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07002776
Glenn Kasten9e58b552013-01-18 15:09:48 -08002777 if (logString != NULL) {
2778 mNBLogWriter->logTimestamp();
2779 mNBLogWriter->log(logString);
2780 logString = NULL;
2781 }
2782
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002783 // Gather the framesReleased counters for all active tracks,
2784 // and latch them atomically with the timestamp.
2785 // FIXME We're using raw pointers as indices. A unique track ID would be a better index.
2786 mLatchD.mFramesReleased.clear();
2787 size_t size = mActiveTracks.size();
2788 for (size_t i = 0; i < size; i++) {
2789 sp<Track> t = mActiveTracks[i].promote();
2790 if (t != 0) {
2791 mLatchD.mFramesReleased.add(t.get(),
2792 t->mAudioTrackServerProxy->framesReleased());
2793 }
2794 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002795 if (mLatchDValid) {
2796 mLatchQ = mLatchD;
2797 mLatchDValid = false;
2798 mLatchQValid = true;
2799 }
2800
Eric Laurent81784c32012-11-19 14:55:58 -08002801 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002802 if (mSignalPending) {
2803 // A signal was raised while we were unlocked
2804 mSignalPending = false;
2805 } else if (waitingAsyncCallback_l()) {
2806 if (exitPending()) {
2807 break;
2808 }
Marco Nelissen078538c2015-05-12 09:17:57 -07002809 bool released = false;
2810 // The following works around a bug in the offload driver. Ideally we would release
2811 // the wake lock every time, but that causes the last offload buffer(s) to be
2812 // dropped while the device is on battery, so we need to hold a wake lock during
2813 // the drain phase.
2814 if (mBytesRemaining && !(mDrainSequence & 1)) {
2815 releaseWakeLock_l();
2816 released = true;
2817 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002818 mWakeLockUids.clear();
2819 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002820 ALOGV("wait async completion");
2821 mWaitWorkCV.wait(mLock);
2822 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07002823 if (released) {
2824 acquireWakeLock_l();
2825 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002826 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
2827 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002828
2829 continue;
2830 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002831 if ((!mActiveTracks.size() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08002832 isSuspended()) {
2833 // put audio hardware into standby after short delay
2834 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002835
2836 threadLoop_standby();
2837
2838 mStandby = true;
2839 }
2840
2841 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2842 // we're about to wait, flush the binder command buffer
2843 IPCThreadState::self()->flushCommands();
2844
2845 clearOutputTracks();
2846
2847 if (exitPending()) {
2848 break;
2849 }
2850
2851 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002852 mWakeLockUids.clear();
2853 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002854 // wait until we have something to do...
2855 ALOGV("%s going to sleep", myName.string());
2856 mWaitWorkCV.wait(mLock);
2857 ALOGV("%s waking up", myName.string());
2858 acquireWakeLock_l();
2859
2860 mMixerStatus = MIXER_IDLE;
2861 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2862 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002863 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002864 checkSilentMode_l();
2865
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002866 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
2867 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08002868 if (mType == MIXER) {
2869 sleepTimeShift = 0;
2870 }
2871
2872 continue;
2873 }
2874 }
Eric Laurent81784c32012-11-19 14:55:58 -08002875 // mMixerStatusIgnoringFastTracks is also updated internally
2876 mMixerStatus = prepareTracks_l(&tracksToRemove);
2877
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002878 // compare with previously applied list
2879 if (lastGeneration != mActiveTracksGeneration) {
2880 // update wakelock
2881 updateWakeLockUids_l(mWakeLockUids);
2882 lastGeneration = mActiveTracksGeneration;
2883 }
2884
Eric Laurent81784c32012-11-19 14:55:58 -08002885 // prevent any changes in effect chain list and in each effect chain
2886 // during mixing and effect process as the audio buffers could be deleted
2887 // or modified if an effect is created or deleted
2888 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002889 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08002890
Eric Laurentbfb1b832013-01-07 09:53:42 -08002891 if (mBytesRemaining == 0) {
2892 mCurrentWriteLength = 0;
2893 if (mMixerStatus == MIXER_TRACKS_READY) {
2894 // threadLoop_mix() sets mCurrentWriteLength
2895 threadLoop_mix();
2896 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
2897 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002898 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08002899 // must be written to HAL
2900 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002901 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08002902 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002903 }
2904 }
Andy Hung98ef9782014-03-04 14:46:50 -08002905 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002906 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08002907 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
2908 // or mSinkBuffer (if there are no effects).
2909 //
2910 // This is done pre-effects computation; if effects change to
2911 // support higher precision, this needs to move.
2912 //
2913 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002914 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08002915 if (mMixerBufferValid) {
2916 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
2917 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
2918
Andy Hung2ddee192015-12-18 17:34:44 -08002919 // mono blend occurs for mixer threads only (not direct or offloaded)
2920 // and is handled here if we're going directly to the sink.
2921 if (requireMonoBlend() && !mEffectBufferValid) {
2922 mono_blend(
2923 mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount);
2924 }
2925
Andy Hung98ef9782014-03-04 14:46:50 -08002926 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
2927 mNormalFrameCount * mChannelCount);
2928 }
2929
Eric Laurentbfb1b832013-01-07 09:53:42 -08002930 mBytesRemaining = mCurrentWriteLength;
2931 if (isSuspended()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002932 mSleepTimeUs = suspendSleepTimeUs();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002933 // simulate write to HAL when suspended
Andy Hung25c2dac2014-02-27 14:56:00 -08002934 mBytesWritten += mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002935 mBytesRemaining = 0;
2936 }
Eric Laurent81784c32012-11-19 14:55:58 -08002937
Eric Laurentbfb1b832013-01-07 09:53:42 -08002938 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002939 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002940 for (size_t i = 0; i < effectChains.size(); i ++) {
2941 effectChains[i]->process_l();
2942 }
Eric Laurent81784c32012-11-19 14:55:58 -08002943 }
2944 }
Eric Laurent59fe0102013-09-27 18:48:26 -07002945 // Process effect chains for offloaded thread even if no audio
2946 // was read from audio track: process only updates effect state
2947 // and thus does have to be synchronized with audio writes but may have
2948 // to be called while waiting for async write callback
2949 if (mType == OFFLOAD) {
2950 for (size_t i = 0; i < effectChains.size(); i ++) {
2951 effectChains[i]->process_l();
2952 }
2953 }
Eric Laurent81784c32012-11-19 14:55:58 -08002954
Andy Hung98ef9782014-03-04 14:46:50 -08002955 // Only if the Effects buffer is enabled and there is data in the
2956 // Effects buffer (buffer valid), we need to
2957 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002958 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08002959 if (mEffectBufferValid) {
2960 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08002961
2962 if (requireMonoBlend()) {
2963 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount);
2964 }
2965
Andy Hung98ef9782014-03-04 14:46:50 -08002966 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
2967 mNormalFrameCount * mChannelCount);
2968 }
2969
Eric Laurent81784c32012-11-19 14:55:58 -08002970 // enable changes in effect chain
2971 unlockEffectChains(effectChains);
2972
Eric Laurentbfb1b832013-01-07 09:53:42 -08002973 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002974 // mSleepTimeUs == 0 means we must write to audio hardware
2975 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07002976 ssize_t ret = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002977 if (mBytesRemaining) {
Andy Hung08fb1742015-05-31 23:22:10 -07002978 ret = threadLoop_write();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002979 if (ret < 0) {
2980 mBytesRemaining = 0;
2981 } else {
2982 mBytesWritten += ret;
2983 mBytesRemaining -= ret;
2984 }
2985 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
2986 (mMixerStatus == MIXER_DRAIN_ALL)) {
2987 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08002988 }
Andy Hung08fb1742015-05-31 23:22:10 -07002989 if (mType == MIXER && !mStandby) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07002990 // write blocked detection
2991 nsecs_t now = systemTime();
2992 nsecs_t delta = now - mLastWriteTime;
Andy Hung08fb1742015-05-31 23:22:10 -07002993 if (delta > maxPeriod) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07002994 mNumDelayedWrites++;
2995 if ((now - lastWarning) > kWarningThrottleNs) {
2996 ATRACE_NAME("underrun");
2997 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2998 ns2ms(delta), mNumDelayedWrites, this);
2999 lastWarning = now;
3000 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003001 }
Andy Hung08fb1742015-05-31 23:22:10 -07003002
3003 if (mThreadThrottle
3004 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
3005 && ret > 0) { // we wrote something
3006 // Limit MixerThread data processing to no more than twice the
3007 // expected processing rate.
3008 //
3009 // This helps prevent underruns with NuPlayer and other applications
3010 // which may set up buffers that are close to the minimum size, or use
3011 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3012 //
3013 // The throttle smooths out sudden large data drains from the device,
3014 // e.g. when it comes out of standby, which often causes problems with
3015 // (1) mixer threads without a fast mixer (which has its own warm-up)
3016 // (2) minimum buffer sized tracks (even if the track is full,
3017 // the app won't fill fast enough to handle the sudden draw).
3018
3019 const int32_t deltaMs = delta / 1000000;
3020 const int32_t throttleMs = mHalfBufferMs - deltaMs;
3021 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
3022 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003023 // notify of throttle start on verbose log
3024 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3025 "mixer(%p) throttle begin:"
3026 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003027 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07003028 mThreadThrottleTimeMs += throttleMs;
3029 } else {
3030 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3031 if (diff > 0) {
3032 // notify of throttle end on debug log
3033 ALOGD("mixer(%p) throttle end: throttle time(%u)", this, diff);
3034 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3035 }
Andy Hung08fb1742015-05-31 23:22:10 -07003036 }
3037 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003038 }
Eric Laurent81784c32012-11-19 14:55:58 -08003039
Eric Laurentbfb1b832013-01-07 09:53:42 -08003040 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003041 ATRACE_BEGIN("sleep");
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003042 usleep(mSleepTimeUs);
Glenn Kastene7754022014-10-31 12:11:26 -07003043 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003044 }
Eric Laurent81784c32012-11-19 14:55:58 -08003045 }
3046
3047 // Finally let go of removed track(s), without the lock held
3048 // since we can't guarantee the destructors won't acquire that
3049 // same lock. This will also mutate and push a new fast mixer state.
3050 threadLoop_removeTracks(tracksToRemove);
3051 tracksToRemove.clear();
3052
3053 // FIXME I don't understand the need for this here;
3054 // it was in the original code but maybe the
3055 // assignment in saveOutputTracks() makes this unnecessary?
3056 clearOutputTracks();
3057
3058 // Effect chains will be actually deleted here if they were removed from
3059 // mEffectChains list during mixing or effects processing
3060 effectChains.clear();
3061
3062 // FIXME Note that the above .clear() is no longer necessary since effectChains
3063 // is now local to this block, but will keep it for now (at least until merge done).
3064 }
3065
Eric Laurentbfb1b832013-01-07 09:53:42 -08003066 threadLoop_exit();
3067
Eric Laurentcf817a22014-08-04 20:36:31 -07003068 if (!mStandby) {
3069 threadLoop_standby();
3070 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003071 }
3072
3073 releaseWakeLock();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003074 mWakeLockUids.clear();
3075 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08003076
3077 ALOGV("Thread %p type %d exiting", this, mType);
3078 return false;
3079}
3080
Eric Laurentbfb1b832013-01-07 09:53:42 -08003081// removeTracks_l() must be called with ThreadBase::mLock held
3082void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3083{
3084 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07003085 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003086 for (size_t i=0 ; i<count ; i++) {
3087 const sp<Track>& track = tracksToRemove.itemAt(i);
3088 mActiveTracks.remove(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003089 mWakeLockUids.remove(track->uid());
3090 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003091 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
3092 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3093 if (chain != 0) {
3094 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
3095 track->sessionId());
3096 chain->decActiveTrackCnt();
3097 }
3098 if (track->isTerminated()) {
3099 removeTrack_l(track);
3100 }
3101 }
3102 }
3103
3104}
Eric Laurent81784c32012-11-19 14:55:58 -08003105
Eric Laurentaccc1472013-09-20 09:36:34 -07003106status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3107{
3108 if (mNormalSink != 0) {
3109 return mNormalSink->getTimestamp(timestamp);
3110 }
Andy Hung9a1c8892014-12-03 11:37:42 -08003111 if ((mType == OFFLOAD || mType == DIRECT)
3112 && mOutput != NULL && mOutput->stream->get_presentation_position) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003113 uint64_t position64;
Phil Burk062e67a2015-02-11 13:40:50 -08003114 int ret = mOutput->getPresentationPosition(&position64, &timestamp.mTime);
Eric Laurentaccc1472013-09-20 09:36:34 -07003115 if (ret == 0) {
3116 timestamp.mPosition = (uint32_t)position64;
3117 return NO_ERROR;
3118 }
3119 }
3120 return INVALID_OPERATION;
3121}
Eric Laurent1c333e22014-05-20 10:48:17 -07003122
Eric Laurent054d9d32015-04-24 08:48:48 -07003123status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
3124 audio_patch_handle_t *handle)
3125{
3126 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3127 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3128 if (mFastMixer != 0) {
3129 FastMixerStateQueue *sq = mFastMixer->sq();
3130 FastMixerState *state = sq->begin();
3131 if (!(state->mCommand & FastMixerState::IDLE)) {
3132 previousCommand = state->mCommand;
3133 state->mCommand = FastMixerState::HOT_IDLE;
3134 sq->end();
3135 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3136 } else {
3137 sq->end(false /*didModify*/);
3138 }
3139 }
3140 status_t status = PlaybackThread::createAudioPatch_l(patch, handle);
3141
3142 if (!(previousCommand & FastMixerState::IDLE)) {
3143 ALOG_ASSERT(mFastMixer != 0);
3144 FastMixerStateQueue *sq = mFastMixer->sq();
3145 FastMixerState *state = sq->begin();
3146 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3147 state->mCommand = previousCommand;
3148 sq->end();
3149 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3150 }
3151
3152 return status;
3153}
3154
Eric Laurent1c333e22014-05-20 10:48:17 -07003155status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3156 audio_patch_handle_t *handle)
3157{
3158 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003159
3160 // store new device and send to effects
3161 audio_devices_t type = AUDIO_DEVICE_NONE;
3162 for (unsigned int i = 0; i < patch->num_sinks; i++) {
3163 type |= patch->sinks[i].ext.device.type;
3164 }
3165
3166#ifdef ADD_BATTERY_DATA
3167 // when changing the audio output device, call addBatteryData to notify
3168 // the change
3169 if (mOutDevice != type) {
3170 uint32_t params = 0;
3171 // check whether speaker is on
3172 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3173 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003174 }
3175
Eric Laurent054d9d32015-04-24 08:48:48 -07003176 audio_devices_t deviceWithoutSpeaker
3177 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3178 // check if any other device (except speaker) is on
3179 if (type & deviceWithoutSpeaker) {
3180 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3181 }
3182
3183 if (params != 0) {
3184 addBatteryData(params);
3185 }
3186 }
3187#endif
3188
3189 for (size_t i = 0; i < mEffectChains.size(); i++) {
3190 mEffectChains[i]->setDevice_l(type);
3191 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003192
3193 // mPrevOutDevice is the latest device set by createAudioPatch_l(). It is not set when
3194 // the thread is created so that the first patch creation triggers an ioConfigChanged callback
3195 bool configChanged = mPrevOutDevice != type;
Eric Laurent054d9d32015-04-24 08:48:48 -07003196 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003197 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003198
3199 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003200 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
3201 status = hwDevice->create_audio_patch(hwDevice,
3202 patch->num_sources,
3203 patch->sources,
3204 patch->num_sinks,
3205 patch->sinks,
3206 handle);
3207 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003208 char *address;
3209 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3210 //FIXME: we only support address on first sink with HAL version < 3.0
3211 address = audio_device_address_to_parameter(
3212 patch->sinks[0].ext.device.type,
3213 patch->sinks[0].ext.device.address);
3214 } else {
3215 address = (char *)calloc(1, 1);
3216 }
3217 AudioParameter param = AudioParameter(String8(address));
3218 free(address);
3219 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), (int)type);
3220 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3221 param.toString().string());
3222 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003223 }
Eric Laurente8726fe2015-06-26 09:39:24 -07003224 if (configChanged) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003225 mPrevOutDevice = type;
Eric Laurente8726fe2015-06-26 09:39:24 -07003226 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
3227 }
Eric Laurent1c333e22014-05-20 10:48:17 -07003228 return status;
3229}
3230
Eric Laurent054d9d32015-04-24 08:48:48 -07003231status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3232{
3233 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3234 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3235 if (mFastMixer != 0) {
3236 FastMixerStateQueue *sq = mFastMixer->sq();
3237 FastMixerState *state = sq->begin();
3238 if (!(state->mCommand & FastMixerState::IDLE)) {
3239 previousCommand = state->mCommand;
3240 state->mCommand = FastMixerState::HOT_IDLE;
3241 sq->end();
3242 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3243 } else {
3244 sq->end(false /*didModify*/);
3245 }
3246 }
3247
3248 status_t status = PlaybackThread::releaseAudioPatch_l(handle);
3249
3250 if (!(previousCommand & FastMixerState::IDLE)) {
3251 ALOG_ASSERT(mFastMixer != 0);
3252 FastMixerStateQueue *sq = mFastMixer->sq();
3253 FastMixerState *state = sq->begin();
3254 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3255 state->mCommand = previousCommand;
3256 sq->end();
3257 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3258 }
3259
3260 return status;
3261}
3262
Eric Laurent1c333e22014-05-20 10:48:17 -07003263status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3264{
3265 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003266
3267 mOutDevice = AUDIO_DEVICE_NONE;
3268
Eric Laurent1c333e22014-05-20 10:48:17 -07003269 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
3270 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
3271 status = hwDevice->release_audio_patch(hwDevice, handle);
3272 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003273 AudioParameter param;
3274 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
3275 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3276 param.toString().string());
Eric Laurent1c333e22014-05-20 10:48:17 -07003277 }
3278 return status;
3279}
3280
Eric Laurent83b88082014-06-20 18:31:16 -07003281void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3282{
3283 Mutex::Autolock _l(mLock);
3284 mTracks.add(track);
3285}
3286
3287void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3288{
3289 Mutex::Autolock _l(mLock);
3290 destroyTrack_l(track);
3291}
3292
3293void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
3294{
3295 ThreadBase::getAudioPortConfig(config);
3296 config->role = AUDIO_PORT_ROLE_SOURCE;
3297 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3298 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
3299}
3300
Eric Laurent81784c32012-11-19 14:55:58 -08003301// ----------------------------------------------------------------------------
3302
3303AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurent72e3f392015-05-20 14:43:50 -07003304 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
3305 : PlaybackThread(audioFlinger, output, id, device, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08003306 // mAudioMixer below
3307 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08003308 mFastMixerFutex(0),
3309 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08003310 // mOutputSink below
3311 // mPipeSink below
3312 // mNormalSink below
3313{
3314 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07003315 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, "
Eric Laurent81784c32012-11-19 14:55:58 -08003316 "mFrameCount=%d, mNormalFrameCount=%d",
3317 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3318 mNormalFrameCount);
3319 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3320
Andy Hungfbfc3952015-01-15 13:33:51 -08003321 if (type == DUPLICATING) {
3322 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3323 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3324 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3325 return;
3326 }
Eric Laurent81784c32012-11-19 14:55:58 -08003327 // create an NBAIO sink for the HAL output stream, and negotiate
3328 mOutputSink = new AudioStreamOutSink(output->stream);
3329 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003330 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Eric Laurent81784c32012-11-19 14:55:58 -08003331 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
3332 ALOG_ASSERT(index == 0);
3333
3334 // initialize fast mixer depending on configuration
3335 bool initFastMixer;
3336 switch (kUseFastMixer) {
3337 case FastMixer_Never:
3338 initFastMixer = false;
3339 break;
3340 case FastMixer_Always:
3341 initFastMixer = true;
3342 break;
3343 case FastMixer_Static:
3344 case FastMixer_Dynamic:
3345 initFastMixer = mFrameCount < mNormalFrameCount;
3346 break;
3347 }
3348 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003349 audio_format_t fastMixerFormat;
3350 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3351 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3352 } else {
3353 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3354 }
3355 if (mFormat != fastMixerFormat) {
3356 // change our Sink format to accept our intermediate precision
3357 mFormat = fastMixerFormat;
3358 free(mSinkBuffer);
3359 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3360 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3361 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3362 }
Eric Laurent81784c32012-11-19 14:55:58 -08003363
3364 // create a MonoPipe to connect our submix to FastMixer
3365 NBAIO_Format format = mOutputSink->format();
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003366 NBAIO_Format origformat = format;
Andy Hung1258c1a2014-05-23 21:22:17 -07003367 // adjust format to match that of the Fast Mixer
Glenn Kasten97b7b752014-09-28 13:04:24 -07003368 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003369 format.mFormat = fastMixerFormat;
3370 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3371
Eric Laurent81784c32012-11-19 14:55:58 -08003372 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3373 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3374 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3375 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3376 const NBAIO_Format offers[1] = {format};
3377 size_t numCounterOffers = 0;
3378 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
3379 ALOG_ASSERT(index == 0);
3380 monoPipe->setAvgFrames((mScreenState & 1) ?
3381 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3382 mPipeSink = monoPipe;
3383
Glenn Kasten46909e72013-02-26 09:20:22 -08003384#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08003385 if (mTeeSinkOutputEnabled) {
3386 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003387 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
3388 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08003389 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003390 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003391 ALOG_ASSERT(index == 0);
3392 mTeeSink = teeSink;
3393 PipeReader *teeSource = new PipeReader(*teeSink);
3394 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003395 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003396 ALOG_ASSERT(index == 0);
3397 mTeeSource = teeSource;
3398 }
Glenn Kasten46909e72013-02-26 09:20:22 -08003399#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003400
3401 // create fast mixer and configure it initially with just one fast track for our submix
3402 mFastMixer = new FastMixer();
3403 FastMixerStateQueue *sq = mFastMixer->sq();
3404#ifdef STATE_QUEUE_DUMP
3405 sq->setObserverDump(&mStateQueueObserverDump);
3406 sq->setMutatorDump(&mStateQueueMutatorDump);
3407#endif
3408 FastMixerState *state = sq->begin();
3409 FastTrack *fastTrack = &state->mFastTracks[0];
3410 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3411 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3412 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003413 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3414 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003415 fastTrack->mGeneration++;
3416 state->mFastTracksGen++;
3417 state->mTrackMask = 1;
3418 // fast mixer will use the HAL output sink
3419 state->mOutputSink = mOutputSink.get();
3420 state->mOutputSinkGen++;
3421 state->mFrameCount = mFrameCount;
3422 state->mCommand = FastMixerState::COLD_IDLE;
3423 // already done in constructor initialization list
3424 //mFastMixerFutex = 0;
3425 state->mColdFutexAddr = &mFastMixerFutex;
3426 state->mColdGen++;
3427 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08003428#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003429 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08003430#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08003431 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3432 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003433 sq->end();
3434 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3435
3436 // start the fast mixer
3437 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3438 pid_t tid = mFastMixer->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003439 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003440
3441#ifdef AUDIO_WATCHDOG
3442 // create and start the watchdog
3443 mAudioWatchdog = new AudioWatchdog();
3444 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3445 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3446 tid = mAudioWatchdog->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003447 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003448#endif
3449
Eric Laurent81784c32012-11-19 14:55:58 -08003450 }
3451
3452 switch (kUseFastMixer) {
3453 case FastMixer_Never:
3454 case FastMixer_Dynamic:
3455 mNormalSink = mOutputSink;
3456 break;
3457 case FastMixer_Always:
3458 mNormalSink = mPipeSink;
3459 break;
3460 case FastMixer_Static:
3461 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3462 break;
3463 }
3464}
3465
3466AudioFlinger::MixerThread::~MixerThread()
3467{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003468 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003469 FastMixerStateQueue *sq = mFastMixer->sq();
3470 FastMixerState *state = sq->begin();
3471 if (state->mCommand == FastMixerState::COLD_IDLE) {
3472 int32_t old = android_atomic_inc(&mFastMixerFutex);
3473 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003474 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003475 }
3476 }
3477 state->mCommand = FastMixerState::EXIT;
3478 sq->end();
3479 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3480 mFastMixer->join();
3481 // Though the fast mixer thread has exited, it's state queue is still valid.
3482 // We'll use that extract the final state which contains one remaining fast track
3483 // corresponding to our sub-mix.
3484 state = sq->begin();
3485 ALOG_ASSERT(state->mTrackMask == 1);
3486 FastTrack *fastTrack = &state->mFastTracks[0];
3487 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3488 delete fastTrack->mBufferProvider;
3489 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003490 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003491#ifdef AUDIO_WATCHDOG
3492 if (mAudioWatchdog != 0) {
3493 mAudioWatchdog->requestExit();
3494 mAudioWatchdog->requestExitAndWait();
3495 mAudioWatchdog.clear();
3496 }
3497#endif
3498 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003499 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003500 delete mAudioMixer;
3501}
3502
3503
3504uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3505{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003506 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003507 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3508 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3509 }
3510 return latency;
3511}
3512
3513
3514void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3515{
3516 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3517}
3518
Eric Laurentbfb1b832013-01-07 09:53:42 -08003519ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003520{
3521 // FIXME we should only do one push per cycle; confirm this is true
3522 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003523 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003524 FastMixerStateQueue *sq = mFastMixer->sq();
3525 FastMixerState *state = sq->begin();
3526 if (state->mCommand != FastMixerState::MIX_WRITE &&
3527 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3528 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07003529
3530 // FIXME workaround for first HAL write being CPU bound on some devices
3531 ATRACE_BEGIN("write");
3532 mOutput->write((char *)mSinkBuffer, 0);
3533 ATRACE_END();
3534
Eric Laurent81784c32012-11-19 14:55:58 -08003535 int32_t old = android_atomic_inc(&mFastMixerFutex);
3536 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003537 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003538 }
3539#ifdef AUDIO_WATCHDOG
3540 if (mAudioWatchdog != 0) {
3541 mAudioWatchdog->resume();
3542 }
3543#endif
3544 }
3545 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08003546#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003547 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08003548 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08003549#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003550 sq->end();
3551 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3552 if (kUseFastMixer == FastMixer_Dynamic) {
3553 mNormalSink = mPipeSink;
3554 }
3555 } else {
3556 sq->end(false /*didModify*/);
3557 }
3558 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003559 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003560}
3561
3562void AudioFlinger::MixerThread::threadLoop_standby()
3563{
3564 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003565 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003566 FastMixerStateQueue *sq = mFastMixer->sq();
3567 FastMixerState *state = sq->begin();
3568 if (!(state->mCommand & FastMixerState::IDLE)) {
3569 state->mCommand = FastMixerState::COLD_IDLE;
3570 state->mColdFutexAddr = &mFastMixerFutex;
3571 state->mColdGen++;
3572 mFastMixerFutex = 0;
3573 sq->end();
3574 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3575 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3576 if (kUseFastMixer == FastMixer_Dynamic) {
3577 mNormalSink = mOutputSink;
3578 }
3579#ifdef AUDIO_WATCHDOG
3580 if (mAudioWatchdog != 0) {
3581 mAudioWatchdog->pause();
3582 }
3583#endif
3584 } else {
3585 sq->end(false /*didModify*/);
3586 }
3587 }
3588 PlaybackThread::threadLoop_standby();
3589}
3590
Eric Laurentbfb1b832013-01-07 09:53:42 -08003591bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3592{
3593 return false;
3594}
3595
3596bool AudioFlinger::PlaybackThread::shouldStandby_l()
3597{
3598 return !mStandby;
3599}
3600
3601bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3602{
3603 Mutex::Autolock _l(mLock);
3604 return waitingAsyncCallback_l();
3605}
3606
Eric Laurent81784c32012-11-19 14:55:58 -08003607// shared by MIXER and DIRECT, overridden by DUPLICATING
3608void AudioFlinger::PlaybackThread::threadLoop_standby()
3609{
3610 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08003611 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003612 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003613 // discard any pending drain or write ack by incrementing sequence
3614 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3615 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003616 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003617 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3618 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003619 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003620 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003621}
3622
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003623void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3624{
3625 ALOGV("signal playback thread");
3626 broadcast_l();
3627}
3628
Eric Laurent81784c32012-11-19 14:55:58 -08003629void AudioFlinger::MixerThread::threadLoop_mix()
3630{
3631 // obtain the presentation timestamp of the next output buffer
3632 int64_t pts;
3633 status_t status = INVALID_OPERATION;
3634
3635 if (mNormalSink != 0) {
3636 status = mNormalSink->getNextWriteTimestamp(&pts);
3637 } else {
3638 status = mOutputSink->getNextWriteTimestamp(&pts);
3639 }
3640
3641 if (status != NO_ERROR) {
3642 pts = AudioBufferProvider::kInvalidPTS;
3643 }
3644
3645 // mix buffers...
3646 mAudioMixer->process(pts);
Andy Hung25c2dac2014-02-27 14:56:00 -08003647 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003648 // increase sleep time progressively when application underrun condition clears.
3649 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3650 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3651 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003652 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003653 sleepTimeShift--;
3654 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003655 mSleepTimeUs = 0;
3656 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08003657 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003658
Eric Laurent81784c32012-11-19 14:55:58 -08003659}
3660
3661void AudioFlinger::MixerThread::threadLoop_sleepTime()
3662{
3663 // If no tracks are ready, sleep once for the duration of an output
3664 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003665 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003666 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003667 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
3668 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
3669 mSleepTimeUs = kMinThreadSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003670 }
3671 // reduce sleep time in case of consecutive application underruns to avoid
3672 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3673 // duration we would end up writing less data than needed by the audio HAL if
3674 // the condition persists.
3675 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3676 sleepTimeShift++;
3677 }
3678 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003679 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003680 }
3681 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003682 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3683 // before effects processing or output.
3684 if (mMixerBufferValid) {
3685 memset(mMixerBuffer, 0, mMixerBufferSize);
3686 } else {
3687 memset(mSinkBuffer, 0, mSinkBufferSize);
3688 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003689 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003690 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3691 "anticipated start");
3692 }
3693 // TODO add standby time extension fct of effect tail
3694}
3695
3696// prepareTracks_l() must be called with ThreadBase::mLock held
3697AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3698 Vector< sp<Track> > *tracksToRemove)
3699{
3700
3701 mixer_state mixerStatus = MIXER_IDLE;
3702 // find out which tracks need to be processed
3703 size_t count = mActiveTracks.size();
3704 size_t mixedTracks = 0;
3705 size_t tracksWithEffect = 0;
3706 // counts only _active_ fast tracks
3707 size_t fastTracks = 0;
3708 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
3709
3710 float masterVolume = mMasterVolume;
3711 bool masterMute = mMasterMute;
3712
3713 if (masterMute) {
3714 masterVolume = 0;
3715 }
3716 // Delegate master volume control to effect in output mix effect chain if needed
3717 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3718 if (chain != 0) {
3719 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
3720 chain->setVolume_l(&v, &v);
3721 masterVolume = (float)((v + (1 << 23)) >> 24);
3722 chain.clear();
3723 }
3724
3725 // prepare a new state to push
3726 FastMixerStateQueue *sq = NULL;
3727 FastMixerState *state = NULL;
3728 bool didModify = false;
3729 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003730 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003731 sq = mFastMixer->sq();
3732 state = sq->begin();
3733 }
3734
Andy Hung69aed5f2014-02-25 17:24:40 -08003735 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08003736 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08003737
Eric Laurent81784c32012-11-19 14:55:58 -08003738 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003739 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003740 if (t == 0) {
3741 continue;
3742 }
3743
3744 // this const just means the local variable doesn't change
3745 Track* const track = t.get();
3746
3747 // process fast tracks
3748 if (track->isFastTrack()) {
3749
3750 // It's theoretically possible (though unlikely) for a fast track to be created
3751 // and then removed within the same normal mix cycle. This is not a problem, as
3752 // the track never becomes active so it's fast mixer slot is never touched.
3753 // The converse, of removing an (active) track and then creating a new track
3754 // at the identical fast mixer slot within the same normal mix cycle,
3755 // is impossible because the slot isn't marked available until the end of each cycle.
3756 int j = track->mFastIndex;
3757 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
3758 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
3759 FastTrack *fastTrack = &state->mFastTracks[j];
3760
3761 // Determine whether the track is currently in underrun condition,
3762 // and whether it had a recent underrun.
3763 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
3764 FastTrackUnderruns underruns = ftDump->mUnderruns;
3765 uint32_t recentFull = (underruns.mBitFields.mFull -
3766 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
3767 uint32_t recentPartial = (underruns.mBitFields.mPartial -
3768 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
3769 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
3770 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
3771 uint32_t recentUnderruns = recentPartial + recentEmpty;
3772 track->mObservedUnderruns = underruns;
3773 // don't count underruns that occur while stopping or pausing
3774 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07003775 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
3776 recentUnderruns > 0) {
3777 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
3778 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003779 }
3780
3781 // This is similar to the state machine for normal tracks,
3782 // with a few modifications for fast tracks.
3783 bool isActive = true;
3784 switch (track->mState) {
3785 case TrackBase::STOPPING_1:
3786 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08003787 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003788 track->mState = TrackBase::STOPPING_2;
3789 }
3790 break;
3791 case TrackBase::PAUSING:
3792 // ramp down is not yet implemented
3793 track->setPaused();
3794 break;
3795 case TrackBase::RESUMING:
3796 // ramp up is not yet implemented
3797 track->mState = TrackBase::ACTIVE;
3798 break;
3799 case TrackBase::ACTIVE:
3800 if (recentFull > 0 || recentPartial > 0) {
3801 // track has provided at least some frames recently: reset retry count
3802 track->mRetryCount = kMaxTrackRetries;
3803 }
3804 if (recentUnderruns == 0) {
3805 // no recent underruns: stay active
3806 break;
3807 }
3808 // there has recently been an underrun of some kind
3809 if (track->sharedBuffer() == 0) {
3810 // were any of the recent underruns "empty" (no frames available)?
3811 if (recentEmpty == 0) {
3812 // no, then ignore the partial underruns as they are allowed indefinitely
3813 break;
3814 }
3815 // there has recently been an "empty" underrun: decrement the retry counter
3816 if (--(track->mRetryCount) > 0) {
3817 break;
3818 }
3819 // indicate to client process that the track was disabled because of underrun;
3820 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003821 android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003822 // remove from active list, but state remains ACTIVE [confusing but true]
3823 isActive = false;
3824 break;
3825 }
3826 // fall through
3827 case TrackBase::STOPPING_2:
3828 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003829 case TrackBase::STOPPED:
3830 case TrackBase::FLUSHED: // flush() while active
3831 // Check for presentation complete if track is inactive
3832 // We have consumed all the buffers of this track.
3833 // This would be incomplete if we auto-paused on underrun
3834 {
3835 size_t audioHALFrames =
3836 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3837 size_t framesWritten = mBytesWritten / mFrameSize;
3838 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
3839 // track stays in active list until presentation is complete
3840 break;
3841 }
3842 }
3843 if (track->isStopping_2()) {
3844 track->mState = TrackBase::STOPPED;
3845 }
3846 if (track->isStopped()) {
3847 // Can't reset directly, as fast mixer is still polling this track
3848 // track->reset();
3849 // So instead mark this track as needing to be reset after push with ack
3850 resetMask |= 1 << i;
3851 }
3852 isActive = false;
3853 break;
3854 case TrackBase::IDLE:
3855 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08003856 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08003857 }
3858
3859 if (isActive) {
3860 // was it previously inactive?
3861 if (!(state->mTrackMask & (1 << j))) {
3862 ExtendedAudioBufferProvider *eabp = track;
3863 VolumeProvider *vp = track;
3864 fastTrack->mBufferProvider = eabp;
3865 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08003866 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003867 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08003868 fastTrack->mGeneration++;
3869 state->mTrackMask |= 1 << j;
3870 didModify = true;
3871 // no acknowledgement required for newly active tracks
3872 }
3873 // cache the combined master volume and stream type volume for fast mixer; this
3874 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08003875 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08003876 ++fastTracks;
3877 } else {
3878 // was it previously active?
3879 if (state->mTrackMask & (1 << j)) {
3880 fastTrack->mBufferProvider = NULL;
3881 fastTrack->mGeneration++;
3882 state->mTrackMask &= ~(1 << j);
3883 didModify = true;
3884 // If any fast tracks were removed, we must wait for acknowledgement
3885 // because we're about to decrement the last sp<> on those tracks.
3886 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3887 } else {
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08003888 LOG_ALWAYS_FATAL("fast track %d should have been active; "
3889 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
3890 j, track->mState, state->mTrackMask, recentUnderruns,
3891 track->sharedBuffer() != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08003892 }
3893 tracksToRemove->add(track);
3894 // Avoids a misleading display in dumpsys
3895 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
3896 }
3897 continue;
3898 }
3899
3900 { // local variable scope to avoid goto warning
3901
3902 audio_track_cblk_t* cblk = track->cblk();
3903
3904 // The first time a track is added we wait
3905 // for all its buffers to be filled before processing it
3906 int name = track->name();
3907 // make sure that we have enough frames to mix one full buffer.
3908 // enforce this condition only once to enable draining the buffer in case the client
3909 // app does not call stop() and relies on underrun to stop:
3910 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
3911 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003912 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07003913 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07003914 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07003915
3916 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07003917 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07003918 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
3919 // add frames already consumed but not yet released by the resampler
3920 // because mAudioTrackServerProxy->framesReady() will include these frames
3921 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
3922
Eric Laurent81784c32012-11-19 14:55:58 -08003923 uint32_t minFrames = 1;
3924 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
3925 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003926 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08003927 }
Eric Laurent13e4c962013-12-20 17:36:01 -08003928
3929 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07003930 if (ATRACE_ENABLED()) {
3931 // I wish we had formatted trace names
3932 char traceName[16];
3933 strcpy(traceName, "nRdy");
3934 int name = track->name();
3935 if (AudioMixer::TRACK0 <= name &&
3936 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
3937 name -= AudioMixer::TRACK0;
3938 traceName[4] = (name / 10) + '0';
3939 traceName[5] = (name % 10) + '0';
3940 } else {
3941 traceName[4] = '?';
3942 traceName[5] = '?';
3943 }
3944 traceName[6] = '\0';
3945 ATRACE_INT(traceName, framesReady);
3946 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003947 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08003948 !track->isPaused() && !track->isTerminated())
3949 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003950 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003951
3952 mixedTracks++;
3953
Andy Hung69aed5f2014-02-25 17:24:40 -08003954 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
3955 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08003956 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08003957 if (track->mainBuffer() != mSinkBuffer &&
3958 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08003959 if (mEffectBufferEnabled) {
3960 mEffectBufferValid = true; // Later can set directly.
3961 }
Eric Laurent81784c32012-11-19 14:55:58 -08003962 chain = getEffectChain_l(track->sessionId());
3963 // Delegate volume control to effect in track effect chain if needed
3964 if (chain != 0) {
3965 tracksWithEffect++;
3966 } else {
3967 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
3968 "session %d",
3969 name, track->sessionId());
3970 }
3971 }
3972
3973
3974 int param = AudioMixer::VOLUME;
3975 if (track->mFillingUpStatus == Track::FS_FILLED) {
3976 // no ramp for the first volume setting
3977 track->mFillingUpStatus = Track::FS_ACTIVE;
3978 if (track->mState == TrackBase::RESUMING) {
3979 track->mState = TrackBase::ACTIVE;
3980 param = AudioMixer::RAMP_VOLUME;
3981 }
3982 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003983 // FIXME should not make a decision based on mServer
3984 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003985 // If the track is stopped before the first frame was mixed,
3986 // do not apply ramp
3987 param = AudioMixer::RAMP_VOLUME;
3988 }
3989
3990 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07003991 uint32_t vl, vr; // in U8.24 integer format
3992 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08003993 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07003994 vl = vr = 0;
3995 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08003996 if (track->isPausing()) {
3997 track->setPaused();
3998 }
3999 } else {
4000
4001 // read original volumes with volume control
4002 float typeVolume = mStreamTypes[track->streamType()].volume;
4003 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004004 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004005 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07004006 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
4007 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08004008 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07004009 if (vlf > GAIN_FLOAT_UNITY) {
4010 ALOGV("Track left volume out of range: %.3g", vlf);
4011 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004012 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07004013 if (vrf > GAIN_FLOAT_UNITY) {
4014 ALOGV("Track right volume out of range: %.3g", vrf);
4015 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004016 }
4017 // now apply the master volume and stream type volume
Andy Hung6be49402014-05-30 10:42:03 -07004018 vlf *= v;
4019 vrf *= v;
Eric Laurent81784c32012-11-19 14:55:58 -08004020 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07004021 // then derive vl and vr as U8.24 versions for the effect chain
4022 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
4023 vl = (uint32_t) (scaleto8_24 * vlf);
4024 vr = (uint32_t) (scaleto8_24 * vrf);
4025 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08004026 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08004027 // send level comes from shared memory and so may be corrupt
4028 if (sendLevel > MAX_GAIN_INT) {
4029 ALOGV("Track send level out of range: %04X", sendLevel);
4030 sendLevel = MAX_GAIN_INT;
4031 }
Andy Hung6be49402014-05-30 10:42:03 -07004032 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
4033 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08004034 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004035
Eric Laurent81784c32012-11-19 14:55:58 -08004036 // Delegate volume control to effect in track effect chain if needed
4037 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
4038 // Do not ramp volume if volume is controlled by effect
4039 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08004040 // Update remaining floating point volume levels
4041 vlf = (float)vl / (1 << 24);
4042 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08004043 track->mHasVolumeController = true;
4044 } else {
4045 // force no volume ramp when volume controller was just disabled or removed
4046 // from effect chain to avoid volume spike
4047 if (track->mHasVolumeController) {
4048 param = AudioMixer::VOLUME;
4049 }
4050 track->mHasVolumeController = false;
4051 }
4052
Eric Laurent81784c32012-11-19 14:55:58 -08004053 // XXX: these things DON'T need to be done each time
4054 mAudioMixer->setBufferProvider(name, track);
4055 mAudioMixer->enable(name);
4056
Andy Hung6be49402014-05-30 10:42:03 -07004057 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
4058 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
4059 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08004060 mAudioMixer->setParameter(
4061 name,
4062 AudioMixer::TRACK,
4063 AudioMixer::FORMAT, (void *)track->format());
4064 mAudioMixer->setParameter(
4065 name,
4066 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004067 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07004068 mAudioMixer->setParameter(
4069 name,
4070 AudioMixer::TRACK,
4071 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08004072 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07004073 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004074 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08004075 if (reqSampleRate == 0) {
4076 reqSampleRate = mSampleRate;
4077 } else if (reqSampleRate > maxSampleRate) {
4078 reqSampleRate = maxSampleRate;
4079 }
Eric Laurent81784c32012-11-19 14:55:58 -08004080 mAudioMixer->setParameter(
4081 name,
4082 AudioMixer::RESAMPLE,
4083 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004084 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004085
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004086 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004087 mAudioMixer->setParameter(
4088 name,
4089 AudioMixer::TIMESTRETCH,
4090 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004091 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004092
Andy Hung69aed5f2014-02-25 17:24:40 -08004093 /*
4094 * Select the appropriate output buffer for the track.
4095 *
Andy Hung98ef9782014-03-04 14:46:50 -08004096 * Tracks with effects go into their own effects chain buffer
4097 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08004098 *
4099 * Other tracks can use mMixerBuffer for higher precision
4100 * channel accumulation. If this buffer is enabled
4101 * (mMixerBufferEnabled true), then selected tracks will accumulate
4102 * into it.
4103 *
4104 */
4105 if (mMixerBufferEnabled
4106 && (track->mainBuffer() == mSinkBuffer
4107 || track->mainBuffer() == mMixerBuffer)) {
4108 mAudioMixer->setParameter(
4109 name,
4110 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004111 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08004112 mAudioMixer->setParameter(
4113 name,
4114 AudioMixer::TRACK,
4115 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
4116 // TODO: override track->mainBuffer()?
4117 mMixerBufferValid = true;
4118 } else {
4119 mAudioMixer->setParameter(
4120 name,
4121 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004122 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08004123 mAudioMixer->setParameter(
4124 name,
4125 AudioMixer::TRACK,
4126 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
4127 }
Eric Laurent81784c32012-11-19 14:55:58 -08004128 mAudioMixer->setParameter(
4129 name,
4130 AudioMixer::TRACK,
4131 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
4132
4133 // reset retry count
4134 track->mRetryCount = kMaxTrackRetries;
4135
4136 // If one track is ready, set the mixer ready if:
4137 // - the mixer was not ready during previous round OR
4138 // - no other track is not ready
4139 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
4140 mixerStatus != MIXER_TRACKS_ENABLED) {
4141 mixerStatus = MIXER_TRACKS_READY;
4142 }
4143 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004144 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hung08fb1742015-05-31 23:22:10 -07004145 ALOGV("track(%p) underrun, framesReady(%zu) < framesDesired(%zd)",
4146 track, framesReady, desiredFrames);
Glenn Kasten82aaf942013-07-17 16:05:07 -07004147 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004148 }
Eric Laurent81784c32012-11-19 14:55:58 -08004149 // clear effect chain input buffer if an active track underruns to avoid sending
4150 // previous audio buffer again to effects
4151 chain = getEffectChain_l(track->sessionId());
4152 if (chain != 0) {
4153 chain->clearInputBuffer();
4154 }
4155
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004156 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004157 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
4158 track->isStopped() || track->isPaused()) {
4159 // We have consumed all the buffers of this track.
4160 // Remove it from the list of active tracks.
4161 // TODO: use actual buffer filling status instead of latency when available from
4162 // audio HAL
4163 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
4164 size_t framesWritten = mBytesWritten / mFrameSize;
4165 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
4166 if (track->isStopped()) {
4167 track->reset();
4168 }
4169 tracksToRemove->add(track);
4170 }
4171 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08004172 // No buffers for this track. Give it a few chances to
4173 // fill a buffer, then remove it from active list.
4174 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004175 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004176 tracksToRemove->add(track);
4177 // indicate to client process that the track was disabled because of underrun;
4178 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07004179 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08004180 // If one track is not ready, mark the mixer also not ready if:
4181 // - the mixer was ready during previous round OR
4182 // - no other track is ready
4183 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
4184 mixerStatus != MIXER_TRACKS_READY) {
4185 mixerStatus = MIXER_TRACKS_ENABLED;
4186 }
4187 }
4188 mAudioMixer->disable(name);
4189 }
4190
4191 } // local variable scope to avoid goto warning
4192track_is_ready: ;
4193
4194 }
4195
4196 // Push the new FastMixer state if necessary
4197 bool pauseAudioWatchdog = false;
4198 if (didModify) {
4199 state->mFastTracksGen++;
4200 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4201 if (kUseFastMixer == FastMixer_Dynamic &&
4202 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4203 state->mCommand = FastMixerState::COLD_IDLE;
4204 state->mColdFutexAddr = &mFastMixerFutex;
4205 state->mColdGen++;
4206 mFastMixerFutex = 0;
4207 if (kUseFastMixer == FastMixer_Dynamic) {
4208 mNormalSink = mOutputSink;
4209 }
4210 // If we go into cold idle, need to wait for acknowledgement
4211 // so that fast mixer stops doing I/O.
4212 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4213 pauseAudioWatchdog = true;
4214 }
Eric Laurent81784c32012-11-19 14:55:58 -08004215 }
4216 if (sq != NULL) {
4217 sq->end(didModify);
4218 sq->push(block);
4219 }
4220#ifdef AUDIO_WATCHDOG
4221 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4222 mAudioWatchdog->pause();
4223 }
4224#endif
4225
4226 // Now perform the deferred reset on fast tracks that have stopped
4227 while (resetMask != 0) {
4228 size_t i = __builtin_ctz(resetMask);
4229 ALOG_ASSERT(i < count);
4230 resetMask &= ~(1 << i);
4231 sp<Track> t = mActiveTracks[i].promote();
4232 if (t == 0) {
4233 continue;
4234 }
4235 Track* track = t.get();
4236 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
4237 track->reset();
4238 }
4239
4240 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004241 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004242
Eric Laurent97d547d2014-09-02 14:45:53 -07004243 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
4244 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07004245 }
4246
4247 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07004248 // as long as there are effects we should clear the effects buffer, to avoid
4249 // passing a non-clean buffer to the effect chain
4250 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07004251 }
Andy Hung69aed5f2014-02-25 17:24:40 -08004252 // sink or mix buffer must be cleared if all tracks are connected to an
4253 // effect chain as in this case the mixer will not write to the sink or mix buffer
4254 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08004255 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4256 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08004257 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08004258 if (mMixerBufferValid) {
4259 memset(mMixerBuffer, 0, mMixerBufferSize);
4260 // TODO: In testing, mSinkBuffer below need not be cleared because
4261 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
4262 // after mixing.
4263 //
4264 // To enforce this guarantee:
4265 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4266 // (mixedTracks == 0 && fastTracks > 0))
4267 // must imply MIXER_TRACKS_READY.
4268 // Later, we may clear buffers regardless, and skip much of this logic.
4269 }
Andy Hung98ef9782014-03-04 14:46:50 -08004270 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07004271 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004272 }
4273
4274 // if any fast tracks, then status is ready
4275 mMixerStatusIgnoringFastTracks = mixerStatus;
4276 if (fastTracks > 0) {
4277 mixerStatus = MIXER_TRACKS_READY;
4278 }
4279 return mixerStatus;
4280}
4281
4282// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07004283int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
4284 audio_format_t format, int sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08004285{
Andy Hunge8a1ced2014-05-09 15:02:21 -07004286 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08004287}
4288
4289// deleteTrackName_l() must be called with ThreadBase::mLock held
4290void AudioFlinger::MixerThread::deleteTrackName_l(int name)
4291{
4292 ALOGV("remove track (%d) and delete from mixer", name);
4293 mAudioMixer->deleteTrackName(name);
4294}
4295
Eric Laurent10351942014-05-08 18:49:52 -07004296// checkForNewParameter_l() must be called with ThreadBase::mLock held
4297bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
4298 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004299{
Eric Laurent81784c32012-11-19 14:55:58 -08004300 bool reconfig = false;
4301
Eric Laurent10351942014-05-08 18:49:52 -07004302 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004303
Eric Laurent10351942014-05-08 18:49:52 -07004304 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
4305 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004306 if (mFastMixer != 0) {
Eric Laurent10351942014-05-08 18:49:52 -07004307 FastMixerStateQueue *sq = mFastMixer->sq();
4308 FastMixerState *state = sq->begin();
4309 if (!(state->mCommand & FastMixerState::IDLE)) {
4310 previousCommand = state->mCommand;
4311 state->mCommand = FastMixerState::HOT_IDLE;
4312 sq->end();
4313 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
4314 } else {
4315 sq->end(false /*didModify*/);
Eric Laurent81784c32012-11-19 14:55:58 -08004316 }
Eric Laurent10351942014-05-08 18:49:52 -07004317 }
Eric Laurent81784c32012-11-19 14:55:58 -08004318
Eric Laurent10351942014-05-08 18:49:52 -07004319 AudioParameter param = AudioParameter(keyValuePair);
4320 int value;
4321 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4322 reconfig = true;
4323 }
4324 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004325 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004326 status = BAD_VALUE;
4327 } else {
4328 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08004329 reconfig = true;
4330 }
Eric Laurent10351942014-05-08 18:49:52 -07004331 }
4332 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004333 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004334 status = BAD_VALUE;
4335 } else {
4336 // no need to save value, since it's constant
4337 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004338 }
Eric Laurent10351942014-05-08 18:49:52 -07004339 }
4340 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4341 // do not accept frame count changes if tracks are open as the track buffer
4342 // size depends on frame count and correct behavior would not be guaranteed
4343 // if frame count is changed after track creation
4344 if (!mTracks.isEmpty()) {
4345 status = INVALID_OPERATION;
4346 } else {
4347 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004348 }
Eric Laurent10351942014-05-08 18:49:52 -07004349 }
4350 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004351#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07004352 // when changing the audio output device, call addBatteryData to notify
4353 // the change
4354 if (mOutDevice != value) {
4355 uint32_t params = 0;
4356 // check whether speaker is on
4357 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
4358 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08004359 }
Eric Laurent10351942014-05-08 18:49:52 -07004360
4361 audio_devices_t deviceWithoutSpeaker
4362 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
4363 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07004364 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07004365 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4366 }
4367
4368 if (params != 0) {
4369 addBatteryData(params);
4370 }
4371 }
Eric Laurent81784c32012-11-19 14:55:58 -08004372#endif
4373
Eric Laurent10351942014-05-08 18:49:52 -07004374 // forward device change to effects that have requested to be
4375 // aware of attached audio device.
4376 if (value != AUDIO_DEVICE_NONE) {
4377 mOutDevice = value;
4378 for (size_t i = 0; i < mEffectChains.size(); i++) {
4379 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08004380 }
4381 }
Eric Laurent10351942014-05-08 18:49:52 -07004382 }
Eric Laurent81784c32012-11-19 14:55:58 -08004383
Eric Laurent10351942014-05-08 18:49:52 -07004384 if (status == NO_ERROR) {
4385 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4386 keyValuePair.string());
4387 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004388 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004389 mStandby = true;
4390 mBytesWritten = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004391 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Eric Laurent10351942014-05-08 18:49:52 -07004392 keyValuePair.string());
Eric Laurent81784c32012-11-19 14:55:58 -08004393 }
Eric Laurent10351942014-05-08 18:49:52 -07004394 if (status == NO_ERROR && reconfig) {
4395 readOutputParameters_l();
4396 delete mAudioMixer;
4397 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4398 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07004399 int name = getTrackName_l(mTracks[i]->mChannelMask,
4400 mTracks[i]->mFormat, mTracks[i]->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07004401 if (name < 0) {
4402 break;
4403 }
4404 mTracks[i]->mName = name;
4405 }
Eric Laurent73e26b62015-04-27 16:55:58 -07004406 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004407 }
Eric Laurent81784c32012-11-19 14:55:58 -08004408 }
4409
4410 if (!(previousCommand & FastMixerState::IDLE)) {
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004411 ALOG_ASSERT(mFastMixer != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08004412 FastMixerStateQueue *sq = mFastMixer->sq();
4413 FastMixerState *state = sq->begin();
4414 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
4415 state->mCommand = previousCommand;
4416 sq->end();
4417 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4418 }
4419
4420 return reconfig;
4421}
4422
4423
4424void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
4425{
4426 const size_t SIZE = 256;
4427 char buffer[SIZE];
4428 String8 result;
4429
4430 PlaybackThread::dumpInternals(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07004431 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Elliott Hughes87cebad2014-05-22 10:14:43 -07004432 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Andy Hung2ddee192015-12-18 17:34:44 -08004433 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Eric Laurent81784c32012-11-19 14:55:58 -08004434
4435 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten2f90c512015-12-02 11:40:09 -08004436 // while we are dumping it. It may be inconsistent, but it won't mutate!
4437 // This is a large object so we place it on the heap.
4438 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
4439 const FastMixerDumpState *copy = new FastMixerDumpState(mFastMixerDumpState);
4440 copy->dump(fd);
4441 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08004442
4443#ifdef STATE_QUEUE_DUMP
4444 // Similar for state queue
4445 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4446 observerCopy.dump(fd);
4447 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4448 mutatorCopy.dump(fd);
4449#endif
4450
Glenn Kasten46909e72013-02-26 09:20:22 -08004451#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08004452 // Write the tee output to a .wav file
4453 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08004454#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004455
4456#ifdef AUDIO_WATCHDOG
4457 if (mAudioWatchdog != 0) {
4458 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4459 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4460 wdCopy.dump(fd);
4461 }
4462#endif
4463}
4464
4465uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4466{
4467 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4468}
4469
4470uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4471{
4472 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4473}
4474
4475void AudioFlinger::MixerThread::cacheParameters_l()
4476{
4477 PlaybackThread::cacheParameters_l();
4478
4479 // FIXME: Relaxed timing because of a certain device that can't meet latency
4480 // Should be reduced to 2x after the vendor fixes the driver issue
4481 // increase threshold again due to low power audio mode. The way this warning
4482 // threshold is calculated and its usefulness should be reconsidered anyway.
4483 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4484}
4485
4486// ----------------------------------------------------------------------------
4487
4488AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07004489 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device, bool systemReady)
4490 : PlaybackThread(audioFlinger, output, id, device, DIRECT, systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08004491 // mLeftVolFloat, mRightVolFloat
4492{
4493}
4494
Eric Laurentbfb1b832013-01-07 09:53:42 -08004495AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4496 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07004497 ThreadBase::type_t type, bool systemReady)
4498 : PlaybackThread(audioFlinger, output, id, device, type, systemReady)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004499 // mLeftVolFloat, mRightVolFloat
4500{
4501}
4502
Eric Laurent81784c32012-11-19 14:55:58 -08004503AudioFlinger::DirectOutputThread::~DirectOutputThread()
4504{
4505}
4506
Eric Laurentbfb1b832013-01-07 09:53:42 -08004507void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
4508{
4509 audio_track_cblk_t* cblk = track->cblk();
4510 float left, right;
4511
4512 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4513 left = right = 0;
4514 } else {
4515 float typeVolume = mStreamTypes[track->streamType()].volume;
4516 float v = mMasterVolume * typeVolume;
4517 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004518 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4519 left = float_from_gain(gain_minifloat_unpack_left(vlr));
4520 if (left > GAIN_FLOAT_UNITY) {
4521 left = GAIN_FLOAT_UNITY;
4522 }
4523 left *= v;
4524 right = float_from_gain(gain_minifloat_unpack_right(vlr));
4525 if (right > GAIN_FLOAT_UNITY) {
4526 right = GAIN_FLOAT_UNITY;
4527 }
4528 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004529 }
4530
4531 if (lastTrack) {
4532 if (left != mLeftVolFloat || right != mRightVolFloat) {
4533 mLeftVolFloat = left;
4534 mRightVolFloat = right;
4535
4536 // Convert volumes from float to 8.24
4537 uint32_t vl = (uint32_t)(left * (1 << 24));
4538 uint32_t vr = (uint32_t)(right * (1 << 24));
4539
4540 // Delegate volume control to effect in track effect chain if needed
4541 // only one effect chain can be present on DirectOutputThread, so if
4542 // there is one, the track is connected to it
4543 if (!mEffectChains.isEmpty()) {
4544 mEffectChains[0]->setVolume_l(&vl, &vr);
4545 left = (float)vl / (1 << 24);
4546 right = (float)vr / (1 << 24);
4547 }
4548 if (mOutput->stream->set_volume) {
4549 mOutput->stream->set_volume(mOutput->stream, left, right);
4550 }
4551 }
4552 }
4553}
4554
Phil Burk43b4dcc2015-06-09 16:53:44 -07004555void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
4556{
4557 sp<Track> previousTrack = mPreviousTrack.promote();
4558 sp<Track> latestTrack = mLatestActiveTrack.promote();
4559
Eric Laurent0f0631e2015-07-06 18:01:25 -07004560 if (previousTrack != 0 && latestTrack != 0) {
4561 if (mType == DIRECT) {
4562 if (previousTrack.get() != latestTrack.get()) {
4563 mFlushPending = true;
4564 }
4565 } else /* mType == OFFLOAD */ {
4566 if (previousTrack->sessionId() != latestTrack->sessionId()) {
4567 mFlushPending = true;
4568 }
4569 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004570 }
4571 PlaybackThread::onAddNewTrack_l();
4572}
Eric Laurentbfb1b832013-01-07 09:53:42 -08004573
Eric Laurent81784c32012-11-19 14:55:58 -08004574AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4575 Vector< sp<Track> > *tracksToRemove
4576)
4577{
Eric Laurentd595b7c2013-04-03 17:27:56 -07004578 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08004579 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004580 bool doHwPause = false;
4581 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004582
4583 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07004584 for (size_t i = 0; i < count; i++) {
4585 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08004586 // The track died recently
4587 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004588 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08004589 }
4590
Phil Burk43b4dcc2015-06-09 16:53:44 -07004591 if (t->isInvalid()) {
4592 ALOGW("An invalidated track shouldn't be in active list");
4593 tracksToRemove->add(t);
4594 continue;
4595 }
4596
Eric Laurent81784c32012-11-19 14:55:58 -08004597 Track* const track = t.get();
4598 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07004599 // Only consider last track started for volume and mixer state control.
4600 // In theory an older track could underrun and restart after the new one starts
4601 // but as we only care about the transition phase between two tracks on a
4602 // direct output, it is not a problem to ignore the underrun case.
4603 sp<Track> l = mLatestActiveTrack.promote();
4604 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08004605
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004606 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004607 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004608 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004609 doHwPause = true;
4610 mHwPaused = true;
4611 }
4612 tracksToRemove->add(track);
4613 } else if (track->isFlushPending()) {
4614 track->flushAck();
4615 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004616 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004617 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004618 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004619 track->resumeAck();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004620 if (last && mHwPaused) {
4621 doHwResume = true;
4622 mHwPaused = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004623 }
4624 }
4625
Eric Laurent81784c32012-11-19 14:55:58 -08004626 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08004627 // for all its buffers to be filled before processing it.
4628 // Allow draining the buffer in case the client
4629 // app does not call stop() and relies on underrun to stop:
4630 // hence the test on (track->mRetryCount > 1).
4631 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07004632 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08004633 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08004634 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkca5e6142015-07-14 09:42:29 -07004635 && (track->mRetryCount > 1) && audio_is_linear_pcm(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004636 minFrames = mNormalFrameCount;
4637 } else {
4638 minFrames = 1;
4639 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004640
Eric Laurentab5cdba2014-06-09 17:22:27 -07004641 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4642 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08004643 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004644 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08004645
4646 if (track->mFillingUpStatus == Track::FS_FILLED) {
4647 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004648 // make sure processVolume_l() will apply new volume even if 0
4649 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004650 if (!mHwSupportsPause) {
4651 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08004652 }
4653 }
4654
4655 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004656 processVolume_l(track, last);
4657 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004658 sp<Track> previousTrack = mPreviousTrack.promote();
4659 if (previousTrack != 0) {
4660 if (track != previousTrack.get()) {
4661 // Flush any data still being written from last track
4662 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07004663 // Invalidate previous track to force a seek when resuming.
4664 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004665 }
4666 }
4667 mPreviousTrack = track;
4668
Eric Laurentd595b7c2013-04-03 17:27:56 -07004669 // reset retry count
4670 track->mRetryCount = kMaxTrackRetriesDirect;
4671 mActiveTrack = t;
4672 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07004673 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004674 doHwResume = true;
4675 mHwPaused = false;
4676 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004677 }
Eric Laurent81784c32012-11-19 14:55:58 -08004678 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004679 // clear effect chain input buffer if the last active track started underruns
4680 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07004681 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004682 mEffectChains[0]->clearInputBuffer();
4683 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004684 if (track->isStopping_1()) {
4685 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07004686 if (last && mHwPaused) {
4687 doHwResume = true;
4688 mHwPaused = false;
4689 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004690 }
4691 if ((track->sharedBuffer() != 0) || track->isStopped() ||
4692 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004693 // We have consumed all the buffers of this track.
4694 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07004695 size_t audioHALFrames;
4696 if (audio_is_linear_pcm(mFormat)) {
4697 audioHALFrames = (latency_l() * mSampleRate) / 1000;
4698 } else {
4699 audioHALFrames = 0;
4700 }
4701
Eric Laurent81784c32012-11-19 14:55:58 -08004702 size_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07004703 if (mStandby || !last ||
4704 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004705 if (track->isStopping_2()) {
4706 track->mState = TrackBase::STOPPED;
4707 }
Eric Laurent81784c32012-11-19 14:55:58 -08004708 if (track->isStopped()) {
4709 track->reset();
4710 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004711 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08004712 }
4713 } else {
4714 // No buffers for this track. Give it a few chances to
4715 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07004716 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08004717 if (--(track->mRetryCount) <= 0) {
4718 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07004719 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004720 // indicate to client process that the track was disabled because of underrun;
4721 // it will then automatically call start() when data is available
4722 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004723 } else if (last) {
Phil Burkca5e6142015-07-14 09:42:29 -07004724 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
4725 "minFrames = %u, mFormat = %#x",
4726 track->framesReady(), minFrames, mFormat);
Eric Laurent81784c32012-11-19 14:55:58 -08004727 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07004728 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004729 doHwPause = true;
4730 mHwPaused = true;
4731 }
Eric Laurent81784c32012-11-19 14:55:58 -08004732 }
4733 }
4734 }
4735 }
4736
Eric Laurentd1f69b02014-12-15 14:33:13 -08004737 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07004738 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004739 for (size_t i = 0; i < mTracks.size(); i++) {
4740 if (mTracks[i]->isFlushPending()) {
4741 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004742 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004743 }
4744 }
4745 }
4746
4747 // make sure the pause/flush/resume sequence is executed in the right order.
4748 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4749 // before flush and then resume HW. This can happen in case of pause/flush/resume
4750 // if resume is received before pause is executed.
4751 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07004752 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004753 mOutput->stream->pause(mOutput->stream);
4754 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004755 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004756 flushHw_l();
4757 }
4758 if (mHwSupportsPause && !mStandby && doHwResume) {
4759 mOutput->stream->resume(mOutput->stream);
4760 }
Eric Laurent81784c32012-11-19 14:55:58 -08004761 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004762 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004763
4764 return mixerStatus;
4765}
4766
4767void AudioFlinger::DirectOutputThread::threadLoop_mix()
4768{
Eric Laurent81784c32012-11-19 14:55:58 -08004769 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08004770 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004771 // output audio to hardware
4772 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07004773 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004774 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08004775 status_t status = mActiveTrack->getNextBuffer(&buffer);
4776 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08004777 memset(curBuf, 0, frameCount * mFrameSize);
4778 break;
4779 }
4780 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
4781 frameCount -= buffer.frameCount;
4782 curBuf += buffer.frameCount * mFrameSize;
4783 mActiveTrack->releaseBuffer(&buffer);
4784 }
Andy Hung2098f272014-02-27 14:00:06 -08004785 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004786 mSleepTimeUs = 0;
4787 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08004788 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004789}
4790
4791void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
4792{
Eric Laurentd1f69b02014-12-15 14:33:13 -08004793 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004794 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004795 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004796 return;
4797 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004798 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004799 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004800 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004801 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004802 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004803 }
4804 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08004805 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004806 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004807 }
4808}
4809
Eric Laurentd1f69b02014-12-15 14:33:13 -08004810void AudioFlinger::DirectOutputThread::threadLoop_exit()
4811{
4812 {
4813 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08004814 for (size_t i = 0; i < mTracks.size(); i++) {
4815 if (mTracks[i]->isFlushPending()) {
4816 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004817 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004818 }
4819 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004820 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004821 flushHw_l();
4822 }
4823 }
4824 PlaybackThread::threadLoop_exit();
4825}
4826
4827// must be called with thread mutex locked
4828bool AudioFlinger::DirectOutputThread::shouldStandby_l()
4829{
4830 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07004831 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004832
4833 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4834 // after a timeout and we will enter standby then.
4835 if (mTracks.size() > 0) {
4836 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07004837 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
4838 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004839 }
4840
Eric Laurent5cff4032015-05-26 13:49:58 -07004841 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08004842}
4843
Eric Laurent81784c32012-11-19 14:55:58 -08004844// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004845int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Andy Hunge8a1ced2014-05-09 15:02:21 -07004846 audio_format_t format __unused, int sessionId __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004847{
4848 return 0;
4849}
4850
4851// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004852void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004853{
4854}
4855
Eric Laurent10351942014-05-08 18:49:52 -07004856// checkForNewParameter_l() must be called with ThreadBase::mLock held
4857bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
4858 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004859{
4860 bool reconfig = false;
4861
Eric Laurent10351942014-05-08 18:49:52 -07004862 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004863
Eric Laurent10351942014-05-08 18:49:52 -07004864 AudioParameter param = AudioParameter(keyValuePair);
4865 int value;
4866 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4867 // forward device change to effects that have requested to be
4868 // aware of attached audio device.
4869 if (value != AUDIO_DEVICE_NONE) {
4870 mOutDevice = value;
4871 for (size_t i = 0; i < mEffectChains.size(); i++) {
4872 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07004873 }
4874 }
Eric Laurent81784c32012-11-19 14:55:58 -08004875 }
Eric Laurent10351942014-05-08 18:49:52 -07004876 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4877 // do not accept frame count changes if tracks are open as the track buffer
4878 // size depends on frame count and correct behavior would not be garantied
4879 // if frame count is changed after track creation
4880 if (!mTracks.isEmpty()) {
4881 status = INVALID_OPERATION;
4882 } else {
4883 reconfig = true;
4884 }
4885 }
4886 if (status == NO_ERROR) {
4887 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4888 keyValuePair.string());
4889 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004890 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004891 mStandby = true;
4892 mBytesWritten = 0;
4893 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4894 keyValuePair.string());
4895 }
4896 if (status == NO_ERROR && reconfig) {
4897 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07004898 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004899 }
4900 }
4901
Eric Laurent81784c32012-11-19 14:55:58 -08004902 return reconfig;
4903}
4904
4905uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
4906{
4907 uint32_t time;
4908 if (audio_is_linear_pcm(mFormat)) {
4909 time = PlaybackThread::activeSleepTimeUs();
4910 } else {
4911 time = 10000;
4912 }
4913 return time;
4914}
4915
4916uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
4917{
4918 uint32_t time;
4919 if (audio_is_linear_pcm(mFormat)) {
4920 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
4921 } else {
4922 time = 10000;
4923 }
4924 return time;
4925}
4926
4927uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
4928{
4929 uint32_t time;
4930 if (audio_is_linear_pcm(mFormat)) {
4931 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
4932 } else {
4933 time = 10000;
4934 }
4935 return time;
4936}
4937
4938void AudioFlinger::DirectOutputThread::cacheParameters_l()
4939{
4940 PlaybackThread::cacheParameters_l();
4941
4942 // use shorter standby delay as on normal output to release
4943 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07004944 // no delay on outputs with HW A/V sync
4945 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004946 mStandbyDelayNs = 0;
Eric Laurent5cff4032015-05-26 13:49:58 -07004947 } else if ((mType == OFFLOAD) && !audio_is_linear_pcm(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004948 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07004949 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004950 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07004951 }
Eric Laurent81784c32012-11-19 14:55:58 -08004952}
4953
Eric Laurente659ef42014-09-29 13:06:46 -07004954void AudioFlinger::DirectOutputThread::flushHw_l()
4955{
Phil Burk062e67a2015-02-11 13:40:50 -08004956 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08004957 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07004958 mFlushPending = false;
Eric Laurente659ef42014-09-29 13:06:46 -07004959}
4960
Eric Laurent81784c32012-11-19 14:55:58 -08004961// ----------------------------------------------------------------------------
4962
Eric Laurentbfb1b832013-01-07 09:53:42 -08004963AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07004964 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004965 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07004966 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07004967 mWriteAckSequence(0),
4968 mDrainSequence(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004969{
4970}
4971
4972AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
4973{
4974}
4975
4976void AudioFlinger::AsyncCallbackThread::onFirstRef()
4977{
4978 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
4979}
4980
4981bool AudioFlinger::AsyncCallbackThread::threadLoop()
4982{
4983 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004984 uint32_t writeAckSequence;
4985 uint32_t drainSequence;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004986
4987 {
4988 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08004989 while (!((mWriteAckSequence & 1) ||
4990 (mDrainSequence & 1) ||
4991 exitPending())) {
4992 mWaitWorkCV.wait(mLock);
4993 }
4994
Eric Laurentbfb1b832013-01-07 09:53:42 -08004995 if (exitPending()) {
4996 break;
4997 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004998 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
4999 mWriteAckSequence, mDrainSequence);
5000 writeAckSequence = mWriteAckSequence;
5001 mWriteAckSequence &= ~1;
5002 drainSequence = mDrainSequence;
5003 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005004 }
5005 {
Eric Laurent4de95592013-09-26 15:28:21 -07005006 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
5007 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005008 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005009 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005010 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005011 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005012 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005013 }
5014 }
5015 }
5016 }
5017 return false;
5018}
5019
5020void AudioFlinger::AsyncCallbackThread::exit()
5021{
5022 ALOGV("AsyncCallbackThread::exit");
5023 Mutex::Autolock _l(mLock);
5024 requestExit();
5025 mWaitWorkCV.broadcast();
5026}
5027
Eric Laurent3b4529e2013-09-05 18:09:19 -07005028void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005029{
5030 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005031 // bit 0 is cleared
5032 mWriteAckSequence = sequence << 1;
5033}
5034
5035void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
5036{
5037 Mutex::Autolock _l(mLock);
5038 // ignore unexpected callbacks
5039 if (mWriteAckSequence & 2) {
5040 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005041 mWaitWorkCV.signal();
5042 }
5043}
5044
Eric Laurent3b4529e2013-09-05 18:09:19 -07005045void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005046{
5047 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005048 // bit 0 is cleared
5049 mDrainSequence = sequence << 1;
5050}
5051
5052void AudioFlinger::AsyncCallbackThread::resetDraining()
5053{
5054 Mutex::Autolock _l(mLock);
5055 // ignore unexpected callbacks
5056 if (mDrainSequence & 2) {
5057 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005058 mWaitWorkCV.signal();
5059 }
5060}
5061
5062
5063// ----------------------------------------------------------------------------
5064AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07005065 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady)
5066 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady),
Eric Laurentd7e59222013-11-15 12:02:28 -08005067 mPausedBytesRemaining(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005068{
Eric Laurentfd477972013-10-25 18:10:40 -07005069 //FIXME: mStandby should be set to true by ThreadBase constructor
5070 mStandby = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005071}
5072
Eric Laurentbfb1b832013-01-07 09:53:42 -08005073void AudioFlinger::OffloadThread::threadLoop_exit()
5074{
5075 if (mFlushPending || mHwPaused) {
5076 // If a flush is pending or track was paused, just discard buffered data
5077 flushHw_l();
5078 } else {
5079 mMixerStatus = MIXER_DRAIN_ALL;
5080 threadLoop_drain();
5081 }
Uday Gupta56604aa2014-05-13 11:19:17 -07005082 if (mUseAsyncWrite) {
5083 ALOG_ASSERT(mCallbackThread != 0);
5084 mCallbackThread->exit();
5085 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005086 PlaybackThread::threadLoop_exit();
5087}
5088
5089AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
5090 Vector< sp<Track> > *tracksToRemove
5091)
5092{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005093 size_t count = mActiveTracks.size();
5094
5095 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07005096 bool doHwPause = false;
5097 bool doHwResume = false;
5098
Eric Laurentede6c3b2013-09-19 14:37:46 -07005099 ALOGV("OffloadThread::prepareTracks_l active tracks %d", count);
5100
Eric Laurentbfb1b832013-01-07 09:53:42 -08005101 // find out which tracks need to be processed
5102 for (size_t i = 0; i < count; i++) {
5103 sp<Track> t = mActiveTracks[i].promote();
5104 // The track died recently
5105 if (t == 0) {
5106 continue;
5107 }
5108 Track* const track = t.get();
5109 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07005110 // Only consider last track started for volume and mixer state control.
5111 // In theory an older track could underrun and restart after the new one starts
5112 // but as we only care about the transition phase between two tracks on a
5113 // direct output, it is not a problem to ignore the underrun case.
5114 sp<Track> l = mLatestActiveTrack.promote();
5115 bool last = l.get() == track;
5116
Haynes Mathew George7844f672014-01-15 12:32:55 -08005117 if (track->isInvalid()) {
5118 ALOGW("An invalidated track shouldn't be in active list");
5119 tracksToRemove->add(track);
5120 continue;
5121 }
5122
5123 if (track->mState == TrackBase::IDLE) {
5124 ALOGW("An idle track shouldn't be in active list");
5125 continue;
5126 }
5127
Eric Laurentbfb1b832013-01-07 09:53:42 -08005128 if (track->isPausing()) {
5129 track->setPaused();
5130 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07005131 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07005132 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005133 mHwPaused = true;
5134 }
5135 // If we were part way through writing the mixbuffer to
5136 // the HAL we must save this until we resume
5137 // BUG - this will be wrong if a different track is made active,
5138 // in that case we want to discard the pending data in the
5139 // mixbuffer and tell the client to present it again when the
5140 // track is resumed
5141 mPausedWriteLength = mCurrentWriteLength;
5142 mPausedBytesRemaining = mBytesRemaining;
5143 mBytesRemaining = 0; // stop writing
5144 }
5145 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08005146 } else if (track->isFlushPending()) {
5147 track->flushAck();
5148 if (last) {
5149 mFlushPending = true;
5150 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005151 } else if (track->isResumePending()){
5152 track->resumeAck();
5153 if (last) {
5154 if (mPausedBytesRemaining) {
5155 // Need to continue write that was interrupted
5156 mCurrentWriteLength = mPausedWriteLength;
5157 mBytesRemaining = mPausedBytesRemaining;
5158 mPausedBytesRemaining = 0;
5159 }
5160 if (mHwPaused) {
5161 doHwResume = true;
5162 mHwPaused = false;
5163 // threadLoop_mix() will handle the case that we need to
5164 // resume an interrupted write
5165 }
5166 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005167 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005168
5169 // Do not handle new data in this iteration even if track->framesReady()
5170 mixerStatus = MIXER_TRACKS_ENABLED;
5171 }
5172 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07005173 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005174 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005175 if (track->mFillingUpStatus == Track::FS_FILLED) {
5176 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07005177 // make sure processVolume_l() will apply new volume even if 0
5178 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005179 }
5180
5181 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08005182 sp<Track> previousTrack = mPreviousTrack.promote();
5183 if (previousTrack != 0) {
5184 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08005185 // Flush any data still being written from last track
5186 mBytesRemaining = 0;
5187 if (mPausedBytesRemaining) {
5188 // Last track was paused so we also need to flush saved
5189 // mixbuffer state and invalidate track so that it will
5190 // re-submit that unwritten data when it is next resumed
5191 mPausedBytesRemaining = 0;
5192 // Invalidate is a bit drastic - would be more efficient
5193 // to have a flag to tell client that some of the
5194 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08005195 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005196 }
5197 // flush data already sent to the DSP if changing audio session as audio
5198 // comes from a different source. Also invalidate previous track to force a
5199 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08005200 if (previousTrack->sessionId() != track->sessionId()) {
5201 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005202 }
5203 }
5204 }
5205 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005206 // reset retry count
5207 track->mRetryCount = kMaxTrackRetriesOffload;
5208 mActiveTrack = t;
5209 mixerStatus = MIXER_TRACKS_READY;
5210 }
5211 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005212 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005213 if (track->isStopping_1()) {
5214 // Hardware buffer can hold a large amount of audio so we must
5215 // wait for all current track's data to drain before we say
5216 // that the track is stopped.
5217 if (mBytesRemaining == 0) {
5218 // Only start draining when all data in mixbuffer
5219 // has been written
5220 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
5221 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005222 // do not drain if no data was ever sent to HAL (mStandby == true)
5223 if (last && !mStandby) {
Eric Laurent1b9f9b12013-11-12 19:10:17 -08005224 // do not modify drain sequence if we are already draining. This happens
5225 // when resuming from pause after drain.
5226 if ((mDrainSequence & 1) == 0) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005227 mSleepTimeUs = 0;
5228 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent1b9f9b12013-11-12 19:10:17 -08005229 mixerStatus = MIXER_DRAIN_TRACK;
5230 mDrainSequence += 2;
5231 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005232 if (mHwPaused) {
5233 // It is possible to move from PAUSED to STOPPING_1 without
5234 // a resume so we must ensure hardware is running
Eric Laurent1b9f9b12013-11-12 19:10:17 -08005235 doHwResume = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005236 mHwPaused = false;
5237 }
5238 }
5239 }
5240 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005241 // Drain has completed or we are in standby, signal presentation complete
5242 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005243 track->mState = TrackBase::STOPPED;
5244 size_t audioHALFrames =
5245 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
5246 size_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08005247 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005248 track->presentationComplete(framesWritten, audioHALFrames);
5249 track->reset();
5250 tracksToRemove->add(track);
5251 }
5252 } else {
5253 // No buffers for this track. Give it a few chances to
5254 // fill a buffer, then remove it from active list.
5255 if (--(track->mRetryCount) <= 0) {
5256 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
5257 track->name());
5258 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08005259 // indicate to client process that the track was disabled because of underrun;
5260 // it will then automatically call start() when data is available
5261 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005262 } else if (last){
5263 mixerStatus = MIXER_TRACKS_ENABLED;
5264 }
5265 }
5266 }
5267 // compute volume for this track
5268 processVolume_l(track, last);
5269 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005270
Eric Laurentea0fade2013-10-04 16:23:48 -07005271 // make sure the pause/flush/resume sequence is executed in the right order.
5272 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5273 // before flush and then resume HW. This can happen in case of pause/flush/resume
5274 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07005275 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurent972a1732013-09-04 09:42:59 -07005276 mOutput->stream->pause(mOutput->stream);
5277 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005278 if (mFlushPending) {
5279 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005280 }
Eric Laurentfd477972013-10-25 18:10:40 -07005281 if (!mStandby && doHwResume) {
Eric Laurent972a1732013-09-04 09:42:59 -07005282 mOutput->stream->resume(mOutput->stream);
5283 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005284
Eric Laurentbfb1b832013-01-07 09:53:42 -08005285 // remove all the tracks that need to be...
5286 removeTracks_l(*tracksToRemove);
5287
5288 return mixerStatus;
5289}
5290
Eric Laurentbfb1b832013-01-07 09:53:42 -08005291// must be called with thread mutex locked
5292bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
5293{
Eric Laurent3b4529e2013-09-05 18:09:19 -07005294 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
5295 mWriteAckSequence, mDrainSequence);
5296 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005297 return true;
5298 }
5299 return false;
5300}
5301
Eric Laurentbfb1b832013-01-07 09:53:42 -08005302bool AudioFlinger::OffloadThread::waitingAsyncCallback()
5303{
5304 Mutex::Autolock _l(mLock);
5305 return waitingAsyncCallback_l();
5306}
5307
5308void AudioFlinger::OffloadThread::flushHw_l()
5309{
Eric Laurente659ef42014-09-29 13:06:46 -07005310 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005311 // Flush anything still waiting in the mixbuffer
5312 mCurrentWriteLength = 0;
5313 mBytesRemaining = 0;
5314 mPausedWriteLength = 0;
5315 mPausedBytesRemaining = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08005316
Eric Laurentbfb1b832013-01-07 09:53:42 -08005317 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005318 // discard any pending drain or write ack by incrementing sequence
5319 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5320 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005321 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005322 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5323 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005324 }
5325}
5326
5327// ----------------------------------------------------------------------------
5328
Eric Laurent81784c32012-11-19 14:55:58 -08005329AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07005330 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08005331 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
Eric Laurent72e3f392015-05-20 14:43:50 -07005332 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08005333 mWaitTimeMs(UINT_MAX)
5334{
5335 addOutputTrack(mainThread);
5336}
5337
5338AudioFlinger::DuplicatingThread::~DuplicatingThread()
5339{
5340 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5341 mOutputTracks[i]->destroy();
5342 }
5343}
5344
5345void AudioFlinger::DuplicatingThread::threadLoop_mix()
5346{
5347 // mix buffers...
5348 if (outputsReady(outputTracks)) {
5349 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
5350 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08005351 if (mMixerBufferValid) {
5352 memset(mMixerBuffer, 0, mMixerBufferSize);
5353 } else {
5354 memset(mSinkBuffer, 0, mSinkBufferSize);
5355 }
Eric Laurent81784c32012-11-19 14:55:58 -08005356 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005357 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005358 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005359 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005360 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005361}
5362
5363void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
5364{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005365 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005366 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005367 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005368 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005369 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005370 }
5371 } else if (mBytesWritten != 0) {
5372 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5373 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005374 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005375 } else {
5376 // flush remaining overflow buffers in output tracks
5377 writeFrames = 0;
5378 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005379 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005380 }
5381}
5382
Eric Laurentbfb1b832013-01-07 09:53:42 -08005383ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005384{
5385 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08005386 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005387 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07005388 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08005389 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005390}
5391
5392void AudioFlinger::DuplicatingThread::threadLoop_standby()
5393{
5394 // DuplicatingThread implements standby by stopping all tracks
5395 for (size_t i = 0; i < outputTracks.size(); i++) {
5396 outputTracks[i]->stop();
5397 }
5398}
5399
5400void AudioFlinger::DuplicatingThread::saveOutputTracks()
5401{
5402 outputTracks = mOutputTracks;
5403}
5404
5405void AudioFlinger::DuplicatingThread::clearOutputTracks()
5406{
5407 outputTracks.clear();
5408}
5409
5410void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
5411{
5412 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08005413 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
5414 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
5415 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
5416 const size_t frameCount =
5417 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
5418 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
5419 // from different OutputTracks and their associated MixerThreads (e.g. one may
5420 // nearly empty and the other may be dropping data).
5421
5422 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08005423 this,
5424 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08005425 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08005426 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005427 frameCount,
5428 IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08005429 if (outputTrack->cblk() != NULL) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005430 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
Eric Laurent81784c32012-11-19 14:55:58 -08005431 mOutputTracks.add(outputTrack);
Andy Hungc25b84a2015-01-14 19:04:10 -08005432 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005433 updateWaitTime_l();
5434 }
5435}
5436
5437void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
5438{
5439 Mutex::Autolock _l(mLock);
5440 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5441 if (mOutputTracks[i]->thread() == thread) {
5442 mOutputTracks[i]->destroy();
5443 mOutputTracks.removeAt(i);
5444 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07005445 if (thread->getOutput() == mOutput) {
5446 mOutput = NULL;
5447 }
Eric Laurent81784c32012-11-19 14:55:58 -08005448 return;
5449 }
5450 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07005451 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005452}
5453
5454// caller must hold mLock
5455void AudioFlinger::DuplicatingThread::updateWaitTime_l()
5456{
5457 mWaitTimeMs = UINT_MAX;
5458 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5459 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
5460 if (strong != 0) {
5461 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
5462 if (waitTimeMs < mWaitTimeMs) {
5463 mWaitTimeMs = waitTimeMs;
5464 }
5465 }
5466 }
5467}
5468
5469
5470bool AudioFlinger::DuplicatingThread::outputsReady(
5471 const SortedVector< sp<OutputTrack> > &outputTracks)
5472{
5473 for (size_t i = 0; i < outputTracks.size(); i++) {
5474 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
5475 if (thread == 0) {
5476 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
5477 outputTracks[i].get());
5478 return false;
5479 }
5480 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5481 // see note at standby() declaration
5482 if (playbackThread->standby() && !playbackThread->isSuspended()) {
5483 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
5484 thread.get());
5485 return false;
5486 }
5487 }
5488 return true;
5489}
5490
5491uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
5492{
5493 return (mWaitTimeMs * 1000) / 2;
5494}
5495
5496void AudioFlinger::DuplicatingThread::cacheParameters_l()
5497{
5498 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
5499 updateWaitTime_l();
5500
5501 MixerThread::cacheParameters_l();
5502}
5503
5504// ----------------------------------------------------------------------------
5505// Record
5506// ----------------------------------------------------------------------------
5507
5508AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5509 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08005510 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08005511 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07005512 audio_devices_t inDevice,
5513 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08005514#ifdef TEE_SINK
5515 , const sp<NBAIO_Sink>& teeSink
5516#endif
5517 ) :
Eric Laurent72e3f392015-05-20 14:43:50 -07005518 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005519 mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005520 // mRsmpInFrames and mRsmpInFramesP2 are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005521 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08005522#ifdef TEE_SINK
5523 , mTeeSink(teeSink)
5524#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07005525 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
5526 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005527 // mFastCapture below
5528 , mFastCaptureFutex(0)
5529 // mInputSource
5530 // mPipeSink
5531 // mPipeSource
5532 , mPipeFramesP2(0)
5533 // mPipeMemory
5534 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005535 , mFastTrackAvail(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005536{
Glenn Kastend7dca052015-03-05 16:05:54 -08005537 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
5538 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08005539
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005540 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005541
5542 // create an NBAIO source for the HAL input stream, and negotiate
5543 mInputSource = new AudioStreamInSource(input->stream);
5544 size_t numCounterOffers = 0;
5545 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
5546 ssize_t index = mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
5547 ALOG_ASSERT(index == 0);
5548
5549 // initialize fast capture depending on configuration
5550 bool initFastCapture;
5551 switch (kUseFastCapture) {
5552 case FastCapture_Never:
5553 initFastCapture = false;
5554 break;
5555 case FastCapture_Always:
5556 initFastCapture = true;
5557 break;
5558 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07005559 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005560 break;
5561 // case FastCapture_Dynamic:
5562 }
5563
5564 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07005565 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005566 NBAIO_Format format = mInputSource->format();
Glenn Kasten49d00ad2014-07-21 11:22:03 -07005567 size_t pipeFramesP2 = roundup(mSampleRate / 25); // double-buffering of 20 ms each
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005568 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
5569 void *pipeBuffer;
5570 const sp<MemoryDealer> roHeap(readOnlyHeap());
5571 sp<IMemory> pipeMemory;
5572 if ((roHeap == 0) ||
5573 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
5574 (pipeBuffer = pipeMemory->pointer()) == NULL) {
5575 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
5576 goto failed;
5577 }
5578 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
5579 memset(pipeBuffer, 0, pipeSize);
5580 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
5581 const NBAIO_Format offers[1] = {format};
5582 size_t numCounterOffers = 0;
5583 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
5584 ALOG_ASSERT(index == 0);
5585 mPipeSink = pipe;
5586 PipeReader *pipeReader = new PipeReader(*pipe);
5587 numCounterOffers = 0;
5588 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
5589 ALOG_ASSERT(index == 0);
5590 mPipeSource = pipeReader;
5591 mPipeFramesP2 = pipeFramesP2;
5592 mPipeMemory = pipeMemory;
5593
5594 // create fast capture
5595 mFastCapture = new FastCapture();
5596 FastCaptureStateQueue *sq = mFastCapture->sq();
5597#ifdef STATE_QUEUE_DUMP
5598 // FIXME
5599#endif
5600 FastCaptureState *state = sq->begin();
5601 state->mCblk = NULL;
5602 state->mInputSource = mInputSource.get();
5603 state->mInputSourceGen++;
5604 state->mPipeSink = pipe;
5605 state->mPipeSinkGen++;
5606 state->mFrameCount = mFrameCount;
5607 state->mCommand = FastCaptureState::COLD_IDLE;
5608 // already done in constructor initialization list
5609 //mFastCaptureFutex = 0;
5610 state->mColdFutexAddr = &mFastCaptureFutex;
5611 state->mColdGen++;
5612 state->mDumpState = &mFastCaptureDumpState;
5613#ifdef TEE_SINK
5614 // FIXME
5615#endif
5616 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
5617 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
5618 sq->end();
5619 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5620
5621 // start the fast capture
5622 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
5623 pid_t tid = mFastCapture->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07005624 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005625#ifdef AUDIO_WATCHDOG
5626 // FIXME
5627#endif
5628
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005629 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005630 }
5631failed: ;
5632
5633 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08005634}
5635
Eric Laurent81784c32012-11-19 14:55:58 -08005636AudioFlinger::RecordThread::~RecordThread()
5637{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005638 if (mFastCapture != 0) {
5639 FastCaptureStateQueue *sq = mFastCapture->sq();
5640 FastCaptureState *state = sq->begin();
5641 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5642 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5643 if (old == -1) {
5644 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5645 }
5646 }
5647 state->mCommand = FastCaptureState::EXIT;
5648 sq->end();
5649 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5650 mFastCapture->join();
5651 mFastCapture.clear();
5652 }
5653 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07005654 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07005655 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08005656}
5657
5658void AudioFlinger::RecordThread::onFirstRef()
5659{
Glenn Kastend7dca052015-03-05 16:05:54 -08005660 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08005661}
5662
Eric Laurent81784c32012-11-19 14:55:58 -08005663bool AudioFlinger::RecordThread::threadLoop()
5664{
Eric Laurent81784c32012-11-19 14:55:58 -08005665 nsecs_t lastWarning = 0;
5666
5667 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08005668
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005669reacquire_wakelock:
5670 sp<RecordTrack> activeTrack;
Glenn Kasten2b806402013-11-20 16:37:38 -08005671 int activeTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005672 {
5673 Mutex::Autolock _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005674 size_t size = mActiveTracks.size();
5675 activeTracksGen = mActiveTracksGen;
5676 if (size > 0) {
5677 // FIXME an arbitrary choice
5678 activeTrack = mActiveTracks[0];
5679 acquireWakeLock_l(activeTrack->uid());
5680 if (size > 1) {
5681 SortedVector<int> tmp;
5682 for (size_t i = 0; i < size; i++) {
5683 tmp.add(mActiveTracks[i]->uid());
5684 }
5685 updateWakeLockUids_l(tmp);
5686 }
5687 } else {
5688 acquireWakeLock_l(-1);
5689 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005690 }
5691
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005692 // used to request a deferred sleep, to be executed later while mutex is unlocked
5693 uint32_t sleepUs = 0;
5694
5695 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005696 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005697 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07005698
Glenn Kasten5edadd42013-08-14 16:30:49 -07005699 // sleep with mutex unlocked
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005700 if (sleepUs > 0) {
Glenn Kastene7754022014-10-31 12:11:26 -07005701 ATRACE_BEGIN("sleep");
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005702 usleep(sleepUs);
Glenn Kastene7754022014-10-31 12:11:26 -07005703 ATRACE_END();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005704 sleepUs = 0;
Glenn Kasten5edadd42013-08-14 16:30:49 -07005705 }
5706
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005707 // activeTracks accumulates a copy of a subset of mActiveTracks
5708 Vector< sp<RecordTrack> > activeTracks;
5709
Glenn Kasten735f45f2014-08-18 15:51:59 -07005710 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005711 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07005712
Glenn Kasten735f45f2014-08-18 15:51:59 -07005713 // reference to a fast track which is about to be removed
5714 sp<RecordTrack> fastTrackToRemove;
5715
Eric Laurent81784c32012-11-19 14:55:58 -08005716 { // scope for mLock
5717 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08005718
Eric Laurent021cf962014-05-13 10:18:14 -07005719 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005720
Eric Laurent000a4192014-01-29 15:17:32 -08005721 // check exitPending here because checkForNewParameters_l() and
5722 // checkForNewParameters_l() can temporarily release mLock
5723 if (exitPending()) {
5724 break;
5725 }
5726
Glenn Kasten2b806402013-11-20 16:37:38 -08005727 // if no active track(s), then standby and release wakelock
5728 size_t size = mActiveTracks.size();
5729 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07005730 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005731 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08005732 releaseWakeLock_l();
5733 ALOGV("RecordThread: loop stopping");
5734 // go to sleep
5735 mWaitWorkCV.wait(mLock);
5736 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005737 goto reacquire_wakelock;
5738 }
5739
Glenn Kasten2b806402013-11-20 16:37:38 -08005740 if (mActiveTracksGen != activeTracksGen) {
5741 activeTracksGen = mActiveTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005742 SortedVector<int> tmp;
Glenn Kasten2b806402013-11-20 16:37:38 -08005743 for (size_t i = 0; i < size; i++) {
5744 tmp.add(mActiveTracks[i]->uid());
5745 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005746 updateWakeLockUids_l(tmp);
Eric Laurent81784c32012-11-19 14:55:58 -08005747 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005748
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005749 bool doBroadcast = false;
5750 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07005751
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005752 activeTrack = mActiveTracks[i];
5753 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07005754 if (activeTrack->isFastTrack()) {
5755 ALOG_ASSERT(fastTrackToRemove == 0);
5756 fastTrackToRemove = activeTrack;
5757 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005758 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08005759 mActiveTracks.remove(activeTrack);
5760 mActiveTracksGen++;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005761 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07005762 continue;
5763 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005764
5765 TrackBase::track_state activeTrackState = activeTrack->mState;
5766 switch (activeTrackState) {
5767
5768 case TrackBase::PAUSING:
5769 mActiveTracks.remove(activeTrack);
5770 mActiveTracksGen++;
5771 doBroadcast = true;
5772 size--;
5773 continue;
5774
5775 case TrackBase::STARTING_1:
5776 sleepUs = 10000;
5777 i++;
5778 continue;
5779
5780 case TrackBase::STARTING_2:
5781 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005782 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07005783 activeTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005784 break;
5785
5786 case TrackBase::ACTIVE:
5787 break;
5788
5789 case TrackBase::IDLE:
5790 i++;
5791 continue;
5792
5793 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08005794 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07005795 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005796
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005797 activeTracks.add(activeTrack);
5798 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07005799
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005800 if (activeTrack->isFastTrack()) {
5801 ALOG_ASSERT(!mFastTrackAvail);
5802 ALOG_ASSERT(fastTrack == 0);
5803 fastTrack = activeTrack;
5804 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005805 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005806 if (doBroadcast) {
5807 mStartStopCond.broadcast();
5808 }
5809
5810 // sleep if there are no active tracks to process
5811 if (activeTracks.size() == 0) {
5812 if (sleepUs == 0) {
5813 sleepUs = kRecordThreadSleepUs;
5814 }
5815 continue;
5816 }
5817 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07005818
Eric Laurent81784c32012-11-19 14:55:58 -08005819 lockEffectChains_l(effectChains);
5820 }
5821
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005822 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07005823
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005824 size_t size = effectChains.size();
5825 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005826 // thread mutex is not locked, but effect chain is locked
5827 effectChains[i]->process_l();
5828 }
5829
Glenn Kasten735f45f2014-08-18 15:51:59 -07005830 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005831 if (mFastCapture != 0) {
5832 FastCaptureStateQueue *sq = mFastCapture->sq();
5833 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07005834 bool didModify = false;
5835 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005836 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
5837 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
5838 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5839 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5840 if (old == -1) {
5841 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5842 }
5843 }
5844 state->mCommand = FastCaptureState::READ_WRITE;
5845#if 0 // FIXME
5846 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08005847 FastThreadDumpState::kSamplingNforLowRamDevice :
5848 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005849#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07005850 didModify = true;
5851 }
5852 audio_track_cblk_t *cblkOld = state->mCblk;
5853 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
5854 if (cblkNew != cblkOld) {
5855 state->mCblk = cblkNew;
5856 // block until acked if removing a fast track
5857 if (cblkOld != NULL) {
5858 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
5859 }
5860 didModify = true;
5861 }
5862 sq->end(didModify);
5863 if (didModify) {
5864 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005865#if 0
5866 if (kUseFastCapture == FastCapture_Dynamic) {
5867 mNormalSource = mPipeSource;
5868 }
5869#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005870 }
5871 }
5872
Glenn Kasten735f45f2014-08-18 15:51:59 -07005873 // now run the fast track destructor with thread mutex unlocked
5874 fastTrackToRemove.clear();
5875
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005876 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
5877 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
5878 // slow, then this RecordThread will overrun by not calling HAL read often enough.
5879 // If destination is non-contiguous, first read past the nominal end of buffer, then
5880 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005881
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005882 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005883 ssize_t framesRead;
5884
5885 // If an NBAIO source is present, use it to read the normal capture's data
5886 if (mPipeSource != 0) {
5887 size_t framesToRead = mBufferSize / mFrameSize;
Andy Hung57446612015-04-19 23:56:46 -07005888 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005889 framesToRead, AudioBufferProvider::kInvalidPTS);
5890 if (framesRead == 0) {
5891 // since pipe is non-blocking, simulate blocking input
5892 sleepUs = (framesToRead * 1000000LL) / mSampleRate;
5893 }
5894 // otherwise use the HAL / AudioStreamIn directly
5895 } else {
5896 ssize_t bytesRead = mInput->stream->read(mInput->stream,
Andy Hung57446612015-04-19 23:56:46 -07005897 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005898 if (bytesRead < 0) {
5899 framesRead = bytesRead;
5900 } else {
5901 framesRead = bytesRead / mFrameSize;
5902 }
5903 }
5904
5905 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
5906 ALOGE("read failed: framesRead=%d", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005907 // Force input into standby so that it tries to recover at next read attempt
5908 inputStandBy();
5909 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005910 }
5911 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005912 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005913 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005914 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005915
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005916 if (mTeeSink != 0) {
Andy Hung57446612015-04-19 23:56:46 -07005917 (void) mTeeSink->write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005918 }
5919 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005920 {
5921 size_t part1 = mRsmpInFramesP2 - rear;
5922 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07005923 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005924 (framesRead - part1) * mFrameSize);
5925 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005926 }
5927 rear = mRsmpInRear += framesRead;
5928
5929 size = activeTracks.size();
5930 // loop over each active track
5931 for (size_t i = 0; i < size; i++) {
5932 activeTrack = activeTracks[i];
5933
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005934 // skip fast tracks, as those are handled directly by FastCapture
5935 if (activeTrack->isFastTrack()) {
5936 continue;
5937 }
5938
Andy Hung73c02e42015-03-29 01:13:58 -07005939 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07005940 // TODO: Update the activeTrack buffer converter in case of reconfigure.
5941
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005942 enum {
5943 OVERRUN_UNKNOWN,
5944 OVERRUN_TRUE,
5945 OVERRUN_FALSE
5946 } overrun = OVERRUN_UNKNOWN;
5947
5948 // loop over getNextBuffer to handle circular sink
5949 for (;;) {
5950
5951 activeTrack->mSink.frameCount = ~0;
5952 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
5953 size_t framesOut = activeTrack->mSink.frameCount;
5954 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
5955
Andy Hung73c02e42015-03-29 01:13:58 -07005956 // check available frames and handle overrun conditions
5957 // if the record track isn't draining fast enough.
5958 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005959 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07005960 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
5961 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005962 overrun = OVERRUN_TRUE;
5963 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005964 if (framesOut == 0 || framesIn == 0) {
5965 break;
5966 }
5967
Andy Hung6770c6f2015-04-07 13:43:36 -07005968 // Don't allow framesOut to be larger than what is possible with resampling
5969 // from framesIn.
5970 // This isn't strictly necessary but helps limit buffer resizing in
5971 // RecordBufferConverter. TODO: remove when no longer needed.
5972 framesOut = min(framesOut,
5973 destinationFramesPossible(
5974 framesIn, mSampleRate, activeTrack->mSampleRate));
Andy Hung97a893e2015-03-29 01:03:07 -07005975 // process frames from the RecordThread buffer provider to the RecordTrack buffer
5976 framesOut = activeTrack->mRecordBufferConverter->convert(
5977 activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005978
5979 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
5980 overrun = OVERRUN_FALSE;
5981 }
5982
5983 if (activeTrack->mFramesToDrop == 0) {
5984 if (framesOut > 0) {
5985 activeTrack->mSink.frameCount = framesOut;
5986 activeTrack->releaseBuffer(&activeTrack->mSink);
5987 }
5988 } else {
5989 // FIXME could do a partial drop of framesOut
5990 if (activeTrack->mFramesToDrop > 0) {
5991 activeTrack->mFramesToDrop -= framesOut;
5992 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005993 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005994 }
5995 } else {
5996 activeTrack->mFramesToDrop += framesOut;
5997 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
5998 activeTrack->mSyncStartEvent->isCancelled()) {
5999 ALOGW("Synced record %s, session %d, trigger session %d",
6000 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
6001 activeTrack->sessionId(),
6002 (activeTrack->mSyncStartEvent != 0) ?
6003 activeTrack->mSyncStartEvent->triggerSession() : 0);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006004 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006005 }
6006 }
6007 }
6008
6009 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006010 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006011 }
6012 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006013
6014 switch (overrun) {
6015 case OVERRUN_TRUE:
6016 // client isn't retrieving buffers fast enough
6017 if (!activeTrack->setOverflow()) {
6018 nsecs_t now = systemTime();
6019 // FIXME should lastWarning per track?
6020 if ((now - lastWarning) > kWarningThrottleNs) {
6021 ALOGW("RecordThread: buffer overflow");
6022 lastWarning = now;
6023 }
6024 }
6025 break;
6026 case OVERRUN_FALSE:
6027 activeTrack->clearOverflow();
6028 break;
6029 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006030 break;
6031 }
6032
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006033 }
6034
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006035unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08006036 // enable changes in effect chain
6037 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006038 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08006039 }
6040
Glenn Kasten93e471f2013-08-19 08:40:07 -07006041 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08006042
6043 {
6044 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07006045 for (size_t i = 0; i < mTracks.size(); i++) {
6046 sp<RecordTrack> track = mTracks[i];
6047 track->invalidate();
6048 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006049 mActiveTracks.clear();
6050 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08006051 mStartStopCond.broadcast();
6052 }
6053
6054 releaseWakeLock();
6055
6056 ALOGV("RecordThread %p exiting", this);
6057 return false;
6058}
6059
Glenn Kasten93e471f2013-08-19 08:40:07 -07006060void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08006061{
6062 if (!mStandby) {
6063 inputStandBy();
6064 mStandby = true;
6065 }
6066}
6067
6068void AudioFlinger::RecordThread::inputStandBy()
6069{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006070 // Idle the fast capture if it's currently running
6071 if (mFastCapture != 0) {
6072 FastCaptureStateQueue *sq = mFastCapture->sq();
6073 FastCaptureState *state = sq->begin();
6074 if (!(state->mCommand & FastCaptureState::IDLE)) {
6075 state->mCommand = FastCaptureState::COLD_IDLE;
6076 state->mColdFutexAddr = &mFastCaptureFutex;
6077 state->mColdGen++;
6078 mFastCaptureFutex = 0;
6079 sq->end();
6080 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
6081 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
6082#if 0
6083 if (kUseFastCapture == FastCapture_Dynamic) {
6084 // FIXME
6085 }
6086#endif
6087#ifdef AUDIO_WATCHDOG
6088 // FIXME
6089#endif
6090 } else {
6091 sq->end(false /*didModify*/);
6092 }
6093 }
Eric Laurent81784c32012-11-19 14:55:58 -08006094 mInput->stream->common.standby(&mInput->stream->common);
6095}
6096
Glenn Kasten05997e22014-03-13 15:08:33 -07006097// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07006098sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08006099 const sp<AudioFlinger::Client>& client,
6100 uint32_t sampleRate,
6101 audio_format_t format,
6102 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08006103 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08006104 int sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07006105 size_t *notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08006106 int uid,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07006107 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08006108 pid_t tid,
6109 status_t *status)
6110{
Glenn Kasten74935e42013-12-19 08:56:45 -08006111 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08006112 sp<RecordTrack> track;
6113 status_t lStatus;
6114
Glenn Kasten90e58b12013-07-31 16:16:02 -07006115 // client expresses a preference for FAST, but we get the final say
6116 if (*flags & IAudioFlinger::TRACK_FAST) {
6117 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07006118 // we formerly checked for a callback handler (non-0 tid),
6119 // but that is no longer required for TRANSFER_OBTAIN mode
6120 //
Glenn Kasten74105912014-07-03 12:28:53 -07006121 // frame count is not specified, or is exactly the pipe depth
6122 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006123 // PCM data
6124 audio_is_linear_pcm(format) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006125 // native format
6126 (format == mFormat) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006127 // native channel mask
6128 (channelMask == mChannelMask) &&
6129 // native hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07006130 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006131 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006132 hasFastCapture() &&
6133 // there are sufficient fast track slots available
6134 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07006135 ) {
Glenn Kasten74105912014-07-03 12:28:53 -07006136 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%u mFrameCount=%u",
Glenn Kasten90e58b12013-07-31 16:16:02 -07006137 frameCount, mFrameCount);
6138 } else {
Glenn Kasten74105912014-07-03 12:28:53 -07006139 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%u mFrameCount=%u mPipeFramesP2=%u "
6140 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006141 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Glenn Kasten74105912014-07-03 12:28:53 -07006142 frameCount, mFrameCount, mPipeFramesP2,
6143 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
6144 hasFastCapture(), tid, mFastTrackAvail);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006145 *flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kasten74105912014-07-03 12:28:53 -07006146 }
6147 }
6148
6149 // compute track buffer size in frames, and suggest the notification frame count
6150 if (*flags & IAudioFlinger::TRACK_FAST) {
6151 // fast track: frame count is exactly the pipe depth
6152 frameCount = mPipeFramesP2;
6153 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
6154 *notificationFrames = mFrameCount;
6155 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006156 // not fast track: max notification period is resampled equivalent of one HAL buffer time
6157 // or 20 ms if there is a fast capture
6158 // TODO This could be a roundupRatio inline, and const
6159 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
6160 * sampleRate + mSampleRate - 1) / mSampleRate;
6161 // minimum number of notification periods is at least kMinNotifications,
6162 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
6163 static const size_t kMinNotifications = 3;
6164 static const uint32_t kMinMs = 30;
6165 // TODO This could be a roundupRatio inline
6166 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
6167 // TODO This could be a roundupRatio inline
6168 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
6169 maxNotificationFrames;
6170 const size_t minFrameCount = maxNotificationFrames *
6171 max(kMinNotifications, minNotificationsByMs);
6172 frameCount = max(frameCount, minFrameCount);
6173 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
6174 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07006175 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07006176 }
Glenn Kasten74935e42013-12-19 08:56:45 -08006177 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07006178
Glenn Kasten15e57982013-09-24 11:52:37 -07006179 lStatus = initCheck();
6180 if (lStatus != NO_ERROR) {
6181 ALOGE("createRecordTrack_l() audio driver not initialized");
6182 goto Exit;
6183 }
Eric Laurent81784c32012-11-19 14:55:58 -08006184
6185 { // scope for mLock
6186 Mutex::Autolock _l(mLock);
6187
6188 track = new RecordTrack(this, client, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07006189 format, channelMask, frameCount, NULL, sessionId, uid,
6190 *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08006191
Glenn Kasten03003332013-08-06 15:40:54 -07006192 lStatus = track->initCheck();
6193 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07006194 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08006195 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08006196 goto Exit;
6197 }
6198 mTracks.add(track);
6199
6200 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6201 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6202 mAudioFlinger->btNrecIsOff();
6203 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6204 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006205
6206 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
6207 pid_t callingPid = IPCThreadState::self()->getCallingPid();
6208 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
6209 // so ask activity manager to do this on our behalf
6210 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
6211 }
Eric Laurent81784c32012-11-19 14:55:58 -08006212 }
Glenn Kasten05997e22014-03-13 15:08:33 -07006213
Eric Laurent81784c32012-11-19 14:55:58 -08006214 lStatus = NO_ERROR;
6215
6216Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07006217 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08006218 return track;
6219}
6220
6221status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
6222 AudioSystem::sync_event_t event,
6223 int triggerSession)
6224{
6225 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
6226 sp<ThreadBase> strongMe = this;
6227 status_t status = NO_ERROR;
6228
6229 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006230 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006231 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006232 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08006233 triggerSession,
6234 recordTrack->sessionId(),
6235 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006236 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08006237 // Sync event can be cancelled by the trigger session if the track is not in a
6238 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006239 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006240 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006241 } else {
6242 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006243 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006244 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08006245 }
6246 }
6247
6248 {
Glenn Kasten47c20702013-08-13 15:37:35 -07006249 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08006250 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006251 if (mActiveTracks.indexOf(recordTrack) >= 0) {
6252 if (recordTrack->mState == TrackBase::PAUSING) {
6253 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006254 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006255 } else {
6256 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08006257 }
6258 return status;
6259 }
6260
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006261 // TODO consider other ways of handling this, such as changing the state to :STARTING and
6262 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
6263 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006264 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08006265 mActiveTracks.add(recordTrack);
6266 mActiveTracksGen++;
Eric Laurent83b88082014-06-20 18:31:16 -07006267 status_t status = NO_ERROR;
6268 if (recordTrack->isExternalTrack()) {
6269 mLock.unlock();
Eric Laurent4dc68062014-07-28 17:26:49 -07006270 status = AudioSystem::startInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006271 mLock.lock();
6272 // FIXME should verify that recordTrack is still in mActiveTracks
6273 if (status != NO_ERROR) {
6274 mActiveTracks.remove(recordTrack);
6275 mActiveTracksGen++;
6276 recordTrack->clearSyncStartEvent();
6277 ALOGV("RecordThread::start error %d", status);
6278 return status;
6279 }
Eric Laurent81784c32012-11-19 14:55:58 -08006280 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006281 // Catch up with current buffer indices if thread is already running.
6282 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
6283 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
6284 // see previously buffered data before it called start(), but with greater risk of overrun.
6285
Andy Hung73c02e42015-03-29 01:13:58 -07006286 recordTrack->mResamplerBufferProvider->reset();
Andy Hung97a893e2015-03-29 01:03:07 -07006287 // clear any converter state as new data will be discontinuous
6288 recordTrack->mRecordBufferConverter->reset();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006289 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08006290 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08006291 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08006292 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006293 ALOGV("Record failed to start");
6294 status = BAD_VALUE;
6295 goto startError;
6296 }
Eric Laurent81784c32012-11-19 14:55:58 -08006297 return status;
6298 }
Glenn Kasten7c027242012-12-26 14:43:16 -08006299
Eric Laurent81784c32012-11-19 14:55:58 -08006300startError:
Eric Laurent83b88082014-06-20 18:31:16 -07006301 if (recordTrack->isExternalTrack()) {
Eric Laurent4dc68062014-07-28 17:26:49 -07006302 AudioSystem::stopInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006303 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006304 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006305 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08006306 return status;
6307}
6308
Eric Laurent81784c32012-11-19 14:55:58 -08006309void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6310{
6311 sp<SyncEvent> strongEvent = event.promote();
6312
6313 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08006314 sp<RefBase> ptr = strongEvent->cookie().promote();
6315 if (ptr != 0) {
6316 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
6317 recordTrack->handleSyncStartEvent(strongEvent);
6318 }
Eric Laurent81784c32012-11-19 14:55:58 -08006319 }
6320}
6321
Glenn Kastena8356f62013-07-25 14:37:52 -07006322bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08006323 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07006324 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006325 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08006326 return false;
6327 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006328 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08006329 recordTrack->mState = TrackBase::PAUSING;
6330 // do not wait for mStartStopCond if exiting
6331 if (exitPending()) {
6332 return true;
6333 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006334 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08006335 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006336 // if we have been restarted, recordTrack is in mActiveTracks here
6337 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006338 ALOGV("Record stopped OK");
6339 return true;
6340 }
6341 return false;
6342}
6343
Glenn Kasten0f11b512014-01-31 16:18:54 -08006344bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08006345{
6346 return false;
6347}
6348
Glenn Kasten0f11b512014-01-31 16:18:54 -08006349status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006350{
6351#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
6352 if (!isValidSyncEvent(event)) {
6353 return BAD_VALUE;
6354 }
6355
6356 int eventSession = event->triggerSession();
6357 status_t ret = NAME_NOT_FOUND;
6358
6359 Mutex::Autolock _l(mLock);
6360
6361 for (size_t i = 0; i < mTracks.size(); i++) {
6362 sp<RecordTrack> track = mTracks[i];
6363 if (eventSession == track->sessionId()) {
6364 (void) track->setSyncEvent(event);
6365 ret = NO_ERROR;
6366 }
6367 }
6368 return ret;
6369#else
6370 return BAD_VALUE;
6371#endif
6372}
6373
6374// destroyTrack_l() must be called with ThreadBase::mLock held
6375void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6376{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006377 track->terminate();
6378 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08006379 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08006380 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006381 removeTrack_l(track);
6382 }
6383}
6384
6385void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6386{
6387 mTracks.remove(track);
6388 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006389 if (track->isFastTrack()) {
6390 ALOG_ASSERT(!mFastTrackAvail);
6391 mFastTrackAvail = true;
6392 }
Eric Laurent81784c32012-11-19 14:55:58 -08006393}
6394
6395void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6396{
6397 dumpInternals(fd, args);
6398 dumpTracks(fd, args);
6399 dumpEffectChains(fd, args);
6400}
6401
6402void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6403{
Elliott Hughes87cebad2014-05-22 10:14:43 -07006404 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08006405
Glenn Kasten44182c22015-03-05 17:12:23 -08006406 dumpBase(fd, args);
6407
6408 if (mActiveTracks.size() == 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006409 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006410 }
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006411 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006412 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08006413
Glenn Kasten2f90c512015-12-02 11:40:09 -08006414 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
6415 // while we are dumping it. It may be inconsistent, but it won't mutate!
6416 // This is a large object so we place it on the heap.
6417 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
6418 const FastCaptureDumpState *copy = new FastCaptureDumpState(mFastCaptureDumpState);
6419 copy->dump(fd);
6420 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08006421}
6422
Glenn Kasten0f11b512014-01-31 16:18:54 -08006423void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006424{
6425 const size_t SIZE = 256;
6426 char buffer[SIZE];
6427 String8 result;
6428
Marco Nelissenb2208842014-02-07 14:00:50 -08006429 size_t numtracks = mTracks.size();
6430 size_t numactive = mActiveTracks.size();
6431 size_t numactiveseen = 0;
Elliott Hughes87cebad2014-05-22 10:14:43 -07006432 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08006433 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006434 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08006435 RecordTrack::appendDumpHeader(result);
6436 for (size_t i = 0; i < numtracks ; ++i) {
6437 sp<RecordTrack> track = mTracks[i];
6438 if (track != 0) {
6439 bool active = mActiveTracks.indexOf(track) >= 0;
6440 if (active) {
6441 numactiveseen++;
6442 }
6443 track->dump(buffer, SIZE, active);
6444 result.append(buffer);
6445 }
Eric Laurent81784c32012-11-19 14:55:58 -08006446 }
Marco Nelissenb2208842014-02-07 14:00:50 -08006447 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006448 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006449 }
6450
Marco Nelissenb2208842014-02-07 14:00:50 -08006451 if (numactiveseen != numactive) {
6452 snprintf(buffer, SIZE, " The following tracks are in the active list but"
6453 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006454 result.append(buffer);
6455 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08006456 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08006457 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08006458 if (mTracks.indexOf(track) < 0) {
6459 track->dump(buffer, SIZE, true);
6460 result.append(buffer);
6461 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006462 }
Eric Laurent81784c32012-11-19 14:55:58 -08006463
6464 }
6465 write(fd, result.string(), result.size());
6466}
6467
Andy Hung73c02e42015-03-29 01:13:58 -07006468
6469void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
6470{
6471 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6472 RecordThread *recordThread = (RecordThread *) threadBase.get();
6473 mRsmpInFront = recordThread->mRsmpInRear;
6474 mRsmpInUnrel = 0;
6475}
6476
6477void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
6478 size_t *framesAvailable, bool *hasOverrun)
6479{
6480 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6481 RecordThread *recordThread = (RecordThread *) threadBase.get();
6482 const int32_t rear = recordThread->mRsmpInRear;
6483 const int32_t front = mRsmpInFront;
6484 const ssize_t filled = rear - front;
6485
6486 size_t framesIn;
6487 bool overrun = false;
6488 if (filled < 0) {
6489 // should not happen, but treat like a massive overrun and re-sync
6490 framesIn = 0;
6491 mRsmpInFront = rear;
6492 overrun = true;
6493 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
6494 framesIn = (size_t) filled;
6495 } else {
6496 // client is not keeping up with server, but give it latest data
6497 framesIn = recordThread->mRsmpInFrames;
6498 mRsmpInFront = /* front = */ rear - framesIn;
6499 overrun = true;
6500 }
6501 if (framesAvailable != NULL) {
6502 *framesAvailable = framesIn;
6503 }
6504 if (hasOverrun != NULL) {
6505 *hasOverrun = overrun;
6506 }
6507}
6508
Eric Laurent81784c32012-11-19 14:55:58 -08006509// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006510status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
6511 AudioBufferProvider::Buffer* buffer, int64_t pts __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006512{
Andy Hung73c02e42015-03-29 01:13:58 -07006513 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006514 if (threadBase == 0) {
6515 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006516 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006517 return NOT_ENOUGH_DATA;
6518 }
6519 RecordThread *recordThread = (RecordThread *) threadBase.get();
6520 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07006521 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07006522 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006523 // FIXME should not be P2 (don't want to increase latency)
6524 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006525 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07006526 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006527 front &= recordThread->mRsmpInFramesP2 - 1;
6528 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07006529 if (part1 > (size_t) filled) {
6530 part1 = filled;
6531 }
6532 size_t ask = buffer->frameCount;
6533 ALOG_ASSERT(ask > 0);
6534 if (part1 > ask) {
6535 part1 = ask;
6536 }
6537 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07006538 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07006539 buffer->raw = NULL;
6540 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07006541 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07006542 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08006543 }
6544
Andy Hung57446612015-04-19 23:56:46 -07006545 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07006546 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07006547 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08006548 return NO_ERROR;
6549}
6550
6551// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006552void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
6553 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006554{
Glenn Kasten85948432013-08-19 12:09:05 -07006555 size_t stepCount = buffer->frameCount;
6556 if (stepCount == 0) {
6557 return;
6558 }
Andy Hung73c02e42015-03-29 01:13:58 -07006559 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
6560 mRsmpInUnrel -= stepCount;
6561 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07006562 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006563 buffer->frameCount = 0;
6564}
6565
Andy Hung97a893e2015-03-29 01:03:07 -07006566AudioFlinger::RecordThread::RecordBufferConverter::RecordBufferConverter(
6567 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6568 uint32_t srcSampleRate,
6569 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6570 uint32_t dstSampleRate) :
6571 mSrcChannelMask(AUDIO_CHANNEL_INVALID), // updateParameters will set following vars
6572 // mSrcFormat
6573 // mSrcSampleRate
6574 // mDstChannelMask
6575 // mDstFormat
6576 // mDstSampleRate
6577 // mSrcChannelCount
6578 // mDstChannelCount
6579 // mDstFrameSize
6580 mBuf(NULL), mBufFrames(0), mBufFrameSize(0),
Andy Hungd330ee42015-04-20 13:23:41 -07006581 mResampler(NULL),
6582 mIsLegacyDownmix(false),
6583 mIsLegacyUpmix(false),
6584 mRequiresFloat(false),
6585 mInputConverterProvider(NULL)
Andy Hung97a893e2015-03-29 01:03:07 -07006586{
6587 (void)updateParameters(srcChannelMask, srcFormat, srcSampleRate,
6588 dstChannelMask, dstFormat, dstSampleRate);
6589}
6590
6591AudioFlinger::RecordThread::RecordBufferConverter::~RecordBufferConverter() {
6592 free(mBuf);
6593 delete mResampler;
Andy Hungd330ee42015-04-20 13:23:41 -07006594 delete mInputConverterProvider;
Andy Hung97a893e2015-03-29 01:03:07 -07006595}
6596
6597size_t AudioFlinger::RecordThread::RecordBufferConverter::convert(void *dst,
6598 AudioBufferProvider *provider, size_t frames)
6599{
Andy Hungd330ee42015-04-20 13:23:41 -07006600 if (mInputConverterProvider != NULL) {
6601 mInputConverterProvider->setBufferProvider(provider);
6602 provider = mInputConverterProvider;
6603 }
6604
6605 if (mResampler == NULL) {
Andy Hung97a893e2015-03-29 01:03:07 -07006606 ALOGVV("NO RESAMPLING sampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6607 mSrcSampleRate, mSrcFormat, mDstFormat);
6608
6609 AudioBufferProvider::Buffer buffer;
6610 for (size_t i = frames; i > 0; ) {
6611 buffer.frameCount = i;
6612 status_t status = provider->getNextBuffer(&buffer, 0);
6613 if (status != OK || buffer.frameCount == 0) {
6614 frames -= i; // cannot fill request.
6615 break;
6616 }
Andy Hungd330ee42015-04-20 13:23:41 -07006617 // format convert to destination buffer
6618 convertNoResampler(dst, buffer.raw, buffer.frameCount);
Andy Hung97a893e2015-03-29 01:03:07 -07006619
6620 dst = (int8_t*)dst + buffer.frameCount * mDstFrameSize;
6621 i -= buffer.frameCount;
6622 provider->releaseBuffer(&buffer);
6623 }
6624 } else {
6625 ALOGVV("RESAMPLING mSrcSampleRate:%u mDstSampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6626 mSrcSampleRate, mDstSampleRate, mSrcFormat, mDstFormat);
6627
Andy Hungd330ee42015-04-20 13:23:41 -07006628 // reallocate buffer if needed
6629 if (mBufFrameSize != 0 && mBufFrames < frames) {
6630 free(mBuf);
6631 mBufFrames = frames;
6632 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
6633 }
Andy Hung97a893e2015-03-29 01:03:07 -07006634 // resampler accumulates, but we only have one source track
Andy Hungd330ee42015-04-20 13:23:41 -07006635 memset(mBuf, 0, frames * mBufFrameSize);
6636 frames = mResampler->resample((int32_t*)mBuf, frames, provider);
6637 // format convert to destination buffer
6638 convertResampler(dst, mBuf, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006639 }
6640 return frames;
6641}
6642
6643status_t AudioFlinger::RecordThread::RecordBufferConverter::updateParameters(
6644 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6645 uint32_t srcSampleRate,
6646 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6647 uint32_t dstSampleRate)
6648{
6649 // quick evaluation if there is any change.
6650 if (mSrcFormat == srcFormat
6651 && mSrcChannelMask == srcChannelMask
6652 && mSrcSampleRate == srcSampleRate
6653 && mDstFormat == dstFormat
6654 && mDstChannelMask == dstChannelMask
6655 && mDstSampleRate == dstSampleRate) {
6656 return NO_ERROR;
6657 }
6658
Andy Hungdb4c0312015-05-06 08:46:52 -07006659 ALOGV("RecordBufferConverter updateParameters srcMask:%#x dstMask:%#x"
6660 " srcFormat:%#x dstFormat:%#x srcRate:%u dstRate:%u",
6661 srcChannelMask, dstChannelMask, srcFormat, dstFormat, srcSampleRate, dstSampleRate);
Andy Hung97a893e2015-03-29 01:03:07 -07006662 const bool valid =
6663 audio_is_input_channel(srcChannelMask)
6664 && audio_is_input_channel(dstChannelMask)
6665 && audio_is_valid_format(srcFormat) && audio_is_linear_pcm(srcFormat)
6666 && audio_is_valid_format(dstFormat) && audio_is_linear_pcm(dstFormat)
6667 && (srcSampleRate <= dstSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX)
6668 ; // no upsampling checks for now
6669 if (!valid) {
6670 return BAD_VALUE;
6671 }
6672
6673 mSrcFormat = srcFormat;
6674 mSrcChannelMask = srcChannelMask;
6675 mSrcSampleRate = srcSampleRate;
6676 mDstFormat = dstFormat;
6677 mDstChannelMask = dstChannelMask;
6678 mDstSampleRate = dstSampleRate;
6679
6680 // compute derived parameters
6681 mSrcChannelCount = audio_channel_count_from_in_mask(srcChannelMask);
6682 mDstChannelCount = audio_channel_count_from_in_mask(dstChannelMask);
6683 mDstFrameSize = mDstChannelCount * audio_bytes_per_sample(mDstFormat);
6684
Andy Hungd330ee42015-04-20 13:23:41 -07006685 // do we need to resample?
6686 delete mResampler;
6687 mResampler = NULL;
6688 if (mSrcSampleRate != mDstSampleRate) {
6689 mResampler = AudioResampler::create(AUDIO_FORMAT_PCM_FLOAT,
6690 mSrcChannelCount, mDstSampleRate);
6691 mResampler->setSampleRate(mSrcSampleRate);
6692 mResampler->setVolume(AudioMixer::UNITY_GAIN_FLOAT, AudioMixer::UNITY_GAIN_FLOAT);
6693 }
6694
6695 // are we running legacy channel conversion modes?
6696 mIsLegacyDownmix = (mSrcChannelMask == AUDIO_CHANNEL_IN_STEREO
6697 || mSrcChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK)
6698 && mDstChannelMask == AUDIO_CHANNEL_IN_MONO;
6699 mIsLegacyUpmix = mSrcChannelMask == AUDIO_CHANNEL_IN_MONO
6700 && (mDstChannelMask == AUDIO_CHANNEL_IN_STEREO
6701 || mDstChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK);
6702
6703 // do we need to process in float?
6704 mRequiresFloat = mResampler != NULL || mIsLegacyDownmix || mIsLegacyUpmix;
6705
6706 // do we need a staging buffer to convert for destination (we can still optimize this)?
6707 // we use mBufFrameSize > 0 to indicate both frame size as well as buffer necessity
6708 if (mResampler != NULL) {
6709 mBufFrameSize = max(mSrcChannelCount, FCC_2)
6710 * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
Andy Hunga97630b2015-07-22 23:27:24 -07006711 } else if (mIsLegacyUpmix || mIsLegacyDownmix) { // legacy modes always float
Andy Hungd330ee42015-04-20 13:23:41 -07006712 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
6713 } else if (mSrcChannelMask != mDstChannelMask && mDstFormat != mSrcFormat) {
Andy Hung97a893e2015-03-29 01:03:07 -07006714 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(mSrcFormat);
6715 } else {
6716 mBufFrameSize = 0;
6717 }
6718 mBufFrames = 0; // force the buffer to be resized.
6719
Andy Hungd330ee42015-04-20 13:23:41 -07006720 // do we need an input converter buffer provider to give us float?
6721 delete mInputConverterProvider;
6722 mInputConverterProvider = NULL;
6723 if (mRequiresFloat && mSrcFormat != AUDIO_FORMAT_PCM_FLOAT) {
6724 mInputConverterProvider = new ReformatBufferProvider(
6725 audio_channel_count_from_in_mask(mSrcChannelMask),
6726 mSrcFormat,
6727 AUDIO_FORMAT_PCM_FLOAT,
6728 256 /* provider buffer frame count */);
6729 }
6730
6731 // do we need a remixer to do channel mask conversion
6732 if (!mIsLegacyDownmix && !mIsLegacyUpmix && mSrcChannelMask != mDstChannelMask) {
6733 (void) memcpy_by_index_array_initialization_from_channel_mask(
6734 mIdxAry, ARRAY_SIZE(mIdxAry), mDstChannelMask, mSrcChannelMask);
Andy Hung97a893e2015-03-29 01:03:07 -07006735 }
6736 return NO_ERROR;
6737}
6738
Andy Hungd330ee42015-04-20 13:23:41 -07006739void AudioFlinger::RecordThread::RecordBufferConverter::convertNoResampler(
6740 void *dst, const void *src, size_t frames)
Andy Hung97a893e2015-03-29 01:03:07 -07006741{
Andy Hungd330ee42015-04-20 13:23:41 -07006742 // src is native type unless there is legacy upmix or downmix, whereupon it is float.
Andy Hung97a893e2015-03-29 01:03:07 -07006743 if (mBufFrameSize != 0 && mBufFrames < frames) {
6744 free(mBuf);
6745 mBufFrames = frames;
6746 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
6747 }
Andy Hungd330ee42015-04-20 13:23:41 -07006748 // do we need to do legacy upmix and downmix?
6749 if (mIsLegacyUpmix || mIsLegacyDownmix) {
Andy Hung97a893e2015-03-29 01:03:07 -07006750 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07006751 if (mIsLegacyUpmix) {
6752 upmix_to_stereo_float_from_mono_float((float *)dstBuf,
6753 (const float *)src, frames);
6754 } else /*mIsLegacyDownmix */ {
6755 downmix_to_mono_float_from_stereo_float((float *)dstBuf,
6756 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006757 }
Andy Hungd330ee42015-04-20 13:23:41 -07006758 if (mBuf != NULL) {
6759 memcpy_by_audio_format(dst, mDstFormat, mBuf, AUDIO_FORMAT_PCM_FLOAT,
6760 frames * mDstChannelCount);
6761 }
6762 return;
6763 }
6764 // do we need to do channel mask conversion?
6765 if (mSrcChannelMask != mDstChannelMask) {
Andy Hung97a893e2015-03-29 01:03:07 -07006766 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07006767 memcpy_by_index_array(dstBuf, mDstChannelCount,
6768 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mSrcFormat), frames);
6769 if (dstBuf == dst) {
6770 return; // format is the same
6771 }
6772 }
6773 // convert to destination buffer
6774 const void *convertBuf = mBuf != NULL ? mBuf : src;
6775 memcpy_by_audio_format(dst, mDstFormat, convertBuf, mSrcFormat,
6776 frames * mDstChannelCount);
6777}
6778
6779void AudioFlinger::RecordThread::RecordBufferConverter::convertResampler(
6780 void *dst, /*not-a-const*/ void *src, size_t frames)
6781{
6782 // src buffer format is ALWAYS float when entering this routine
6783 if (mIsLegacyUpmix) {
6784 ; // mono to stereo already handled by resampler
6785 } else if (mIsLegacyDownmix
6786 || (mSrcChannelMask == mDstChannelMask && mSrcChannelCount == 1)) {
6787 // the resampler outputs stereo for mono input channel (a feature?)
6788 // must convert to mono
6789 downmix_to_mono_float_from_stereo_float((float *)src,
6790 (const float *)src, frames);
6791 } else if (mSrcChannelMask != mDstChannelMask) {
6792 // convert to mono channel again for channel mask conversion (could be skipped
6793 // with further optimization).
Andy Hung97a893e2015-03-29 01:03:07 -07006794 if (mSrcChannelCount == 1) {
Andy Hungd330ee42015-04-20 13:23:41 -07006795 downmix_to_mono_float_from_stereo_float((float *)src,
6796 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006797 }
Andy Hungd330ee42015-04-20 13:23:41 -07006798 // convert to destination format (in place, OK as float is larger than other types)
6799 if (mDstFormat != AUDIO_FORMAT_PCM_FLOAT) {
6800 memcpy_by_audio_format(src, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
6801 frames * mSrcChannelCount);
6802 }
6803 // channel convert and save to dst
6804 memcpy_by_index_array(dst, mDstChannelCount,
6805 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mDstFormat), frames);
6806 return;
Andy Hung97a893e2015-03-29 01:03:07 -07006807 }
Andy Hungd330ee42015-04-20 13:23:41 -07006808 // convert to destination format and save to dst
6809 memcpy_by_audio_format(dst, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
6810 frames * mDstChannelCount);
Andy Hung97a893e2015-03-29 01:03:07 -07006811}
6812
Eric Laurent10351942014-05-08 18:49:52 -07006813bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
6814 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006815{
6816 bool reconfig = false;
6817
Eric Laurent10351942014-05-08 18:49:52 -07006818 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006819
Eric Laurent10351942014-05-08 18:49:52 -07006820 audio_format_t reqFormat = mFormat;
6821 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07006822 // 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 -07006823 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
6824
6825 AudioParameter param = AudioParameter(keyValuePair);
6826 int value;
6827 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
6828 // channel count change can be requested. Do we mandate the first client defines the
6829 // HAL sampling rate and channel count or do we allow changes on the fly?
6830 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6831 samplingRate = value;
6832 reconfig = true;
6833 }
6834 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07006835 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07006836 status = BAD_VALUE;
6837 } else {
6838 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08006839 reconfig = true;
6840 }
Eric Laurent10351942014-05-08 18:49:52 -07006841 }
6842 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
6843 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07006844 if (!audio_is_input_channel(mask) ||
6845 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07006846 status = BAD_VALUE;
6847 } else {
6848 channelMask = mask;
6849 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006850 }
Eric Laurent10351942014-05-08 18:49:52 -07006851 }
6852 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6853 // do not accept frame count changes if tracks are open as the track buffer
6854 // size depends on frame count and correct behavior would not be guaranteed
6855 // if frame count is changed after track creation
6856 if (mActiveTracks.size() > 0) {
6857 status = INVALID_OPERATION;
6858 } else {
6859 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006860 }
Eric Laurent10351942014-05-08 18:49:52 -07006861 }
6862 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6863 // forward device change to effects that have requested to be
6864 // aware of attached audio device.
6865 for (size_t i = 0; i < mEffectChains.size(); i++) {
6866 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08006867 }
Eric Laurent81784c32012-11-19 14:55:58 -08006868
Eric Laurent10351942014-05-08 18:49:52 -07006869 // store input device and output device but do not forward output device to audio HAL.
6870 // Note that status is ignored by the caller for output device
6871 // (see AudioFlinger::setParameters()
6872 if (audio_is_output_devices(value)) {
6873 mOutDevice = value;
6874 status = BAD_VALUE;
6875 } else {
6876 mInDevice = value;
Eric Laurente8726fe2015-06-26 09:39:24 -07006877 if (value != AUDIO_DEVICE_NONE) {
6878 mPrevInDevice = value;
6879 }
Eric Laurent10351942014-05-08 18:49:52 -07006880 // disable AEC and NS if the device is a BT SCO headset supporting those
6881 // pre processings
6882 if (mTracks.size() > 0) {
6883 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6884 mAudioFlinger->btNrecIsOff();
6885 for (size_t i = 0; i < mTracks.size(); i++) {
6886 sp<RecordTrack> track = mTracks[i];
6887 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
6888 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08006889 }
6890 }
6891 }
Eric Laurent10351942014-05-08 18:49:52 -07006892 }
6893 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
6894 mAudioSource != (audio_source_t)value) {
6895 // forward device change to effects that have requested to be
6896 // aware of attached audio device.
6897 for (size_t i = 0; i < mEffectChains.size(); i++) {
6898 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08006899 }
Eric Laurent10351942014-05-08 18:49:52 -07006900 mAudioSource = (audio_source_t)value;
6901 }
Glenn Kastene198c362013-08-13 09:13:36 -07006902
Eric Laurent10351942014-05-08 18:49:52 -07006903 if (status == NO_ERROR) {
6904 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6905 keyValuePair.string());
6906 if (status == INVALID_OPERATION) {
6907 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006908 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6909 keyValuePair.string());
Eric Laurent10351942014-05-08 18:49:52 -07006910 }
6911 if (reconfig) {
6912 if (status == BAD_VALUE &&
Andy Hung97a893e2015-03-29 01:03:07 -07006913 audio_is_linear_pcm(mInput->stream->common.get_format(&mInput->stream->common)) &&
6914 audio_is_linear_pcm(reqFormat) &&
Eric Laurent10351942014-05-08 18:49:52 -07006915 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
Andy Hung97a893e2015-03-29 01:03:07 -07006916 <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate)) &&
Andy Hunge5412692014-05-16 11:25:07 -07006917 audio_channel_count_from_in_mask(
Andy Hungd1abb8f2015-05-05 23:42:34 -07006918 mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07006919 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006920 }
Eric Laurent10351942014-05-08 18:49:52 -07006921 if (status == NO_ERROR) {
6922 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07006923 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08006924 }
6925 }
Eric Laurent81784c32012-11-19 14:55:58 -08006926 }
Eric Laurent10351942014-05-08 18:49:52 -07006927
Eric Laurent81784c32012-11-19 14:55:58 -08006928 return reconfig;
6929}
6930
6931String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6932{
Eric Laurent81784c32012-11-19 14:55:58 -08006933 Mutex::Autolock _l(mLock);
6934 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07006935 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08006936 }
6937
Glenn Kastend8ea6992013-07-16 14:17:15 -07006938 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
6939 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08006940 free(s);
6941 return out_s8;
6942}
6943
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07006944void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07006945 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
6946
6947 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08006948
6949 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07006950 case AUDIO_INPUT_OPENED:
6951 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07006952 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07006953 desc->mChannelMask = mChannelMask;
6954 desc->mSamplingRate = mSampleRate;
6955 desc->mFormat = mFormat;
6956 desc->mFrameCount = mFrameCount;
6957 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006958 break;
6959
Eric Laurent73e26b62015-04-27 16:55:58 -07006960 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08006961 default:
6962 break;
6963 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07006964 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08006965}
6966
Glenn Kastendeca2ae2014-02-07 10:25:56 -08006967void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006968{
Eric Laurent81784c32012-11-19 14:55:58 -08006969 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
6970 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Andy Hunge5412692014-05-16 11:25:07 -07006971 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Andy Hungd330ee42015-04-20 13:23:41 -07006972 if (mChannelCount > FCC_8) {
6973 ALOGE("HAL channel count %d > %d", mChannelCount, FCC_8);
6974 }
Andy Hung463be252014-07-10 16:56:07 -07006975 mHALFormat = mInput->stream->common.get_format(&mInput->stream->common);
6976 mFormat = mHALFormat;
Andy Hungd330ee42015-04-20 13:23:41 -07006977 if (!audio_is_linear_pcm(mFormat)) {
6978 ALOGE("HAL format %#x is not linear pcm", mFormat);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07006979 }
Eric Laurent665470b2014-07-03 16:37:08 -07006980 mFrameSize = audio_stream_in_frame_size(mInput->stream);
Glenn Kasten548efc92012-11-29 08:48:51 -08006981 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
6982 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006983 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08006984 // 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 -07006985 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08006986 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006987 // A larger value should allow more old data to be read after a track calls start(),
6988 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07006989 //
6990 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08006991 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07006992 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07006993 free(mRsmpInBuffer);
Andy Hung0a01c2f2015-09-21 12:44:54 -07006994 mRsmpInBuffer = NULL;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006995
6996 // TODO optimize audio capture buffer sizes ...
6997 // Here we calculate the size of the sliding buffer used as a source
6998 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
6999 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
7000 // be better to have it derived from the pipe depth in the long term.
7001 // The current value is higher than necessary. However it should not add to latency.
7002
Glenn Kasten85948432013-08-19 12:09:05 -07007003 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Andy Hung0a01c2f2015-09-21 12:44:54 -07007004 size_t bufferSize = (mRsmpInFramesP2 + mFrameCount - 1) * mFrameSize;
7005 (void)posix_memalign(&mRsmpInBuffer, 32, bufferSize);
7006 memset(mRsmpInBuffer, 0, bufferSize); // if posix_memalign fails, will segv here.
Eric Laurent81784c32012-11-19 14:55:58 -08007007
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007008 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
7009 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08007010}
7011
Glenn Kasten5f972c02014-01-13 09:59:31 -08007012uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08007013{
7014 Mutex::Autolock _l(mLock);
7015 if (initCheck() != NO_ERROR) {
7016 return 0;
7017 }
7018
7019 return mInput->stream->get_input_frames_lost(mInput->stream);
7020}
7021
7022uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
7023{
7024 Mutex::Autolock _l(mLock);
7025 uint32_t result = 0;
7026 if (getEffectChain_l(sessionId) != 0) {
7027 result = EFFECT_SESSION;
7028 }
7029
7030 for (size_t i = 0; i < mTracks.size(); ++i) {
7031 if (sessionId == mTracks[i]->sessionId()) {
7032 result |= TRACK_SESSION;
7033 break;
7034 }
7035 }
7036
7037 return result;
7038}
7039
7040KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
7041{
7042 KeyedVector<int, bool> ids;
7043 Mutex::Autolock _l(mLock);
7044 for (size_t j = 0; j < mTracks.size(); ++j) {
7045 sp<RecordThread::RecordTrack> track = mTracks[j];
7046 int sessionId = track->sessionId();
7047 if (ids.indexOfKey(sessionId) < 0) {
7048 ids.add(sessionId, true);
7049 }
7050 }
7051 return ids;
7052}
7053
7054AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
7055{
7056 Mutex::Autolock _l(mLock);
7057 AudioStreamIn *input = mInput;
7058 mInput = NULL;
7059 return input;
7060}
7061
7062// this method must always be called either with ThreadBase mLock held or inside the thread loop
7063audio_stream_t* AudioFlinger::RecordThread::stream() const
7064{
7065 if (mInput == NULL) {
7066 return NULL;
7067 }
7068 return &mInput->stream->common;
7069}
7070
7071status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7072{
7073 // only one chain per input thread
7074 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07007075 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08007076 return INVALID_OPERATION;
7077 }
7078 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07007079 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08007080 chain->setInBuffer(NULL);
7081 chain->setOutBuffer(NULL);
7082
7083 checkSuspendOnAddEffectChain_l(chain);
7084
Eric Laurent1b928682014-10-02 19:41:47 -07007085 // make sure enabled pre processing effects state is communicated to the HAL as we
7086 // just moved them to a new input stream.
7087 chain->syncHalEffectsState();
7088
Eric Laurent81784c32012-11-19 14:55:58 -08007089 mEffectChains.add(chain);
7090
7091 return NO_ERROR;
7092}
7093
7094size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7095{
7096 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
7097 ALOGW_IF(mEffectChains.size() != 1,
7098 "removeEffectChain_l() %p invalid chain size %d on thread %p",
7099 chain.get(), mEffectChains.size(), this);
7100 if (mEffectChains.size() == 1) {
7101 mEffectChains.removeAt(0);
7102 }
7103 return 0;
7104}
7105
Eric Laurent1c333e22014-05-20 10:48:17 -07007106status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
7107 audio_patch_handle_t *handle)
7108{
7109 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007110
7111 // store new device and send to effects
7112 mInDevice = patch->sources[0].ext.device.type;
Eric Laurent296fb132015-05-01 11:38:42 -07007113 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07007114 for (size_t i = 0; i < mEffectChains.size(); i++) {
7115 mEffectChains[i]->setDevice_l(mInDevice);
7116 }
7117
7118 // disable AEC and NS if the device is a BT SCO headset supporting those
7119 // pre processings
7120 if (mTracks.size() > 0) {
7121 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7122 mAudioFlinger->btNrecIsOff();
7123 for (size_t i = 0; i < mTracks.size(); i++) {
7124 sp<RecordTrack> track = mTracks[i];
7125 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7126 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
7127 }
7128 }
7129
7130 // store new source and send to effects
7131 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7132 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07007133 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07007134 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07007135 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007136 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007137
Eric Laurent054d9d32015-04-24 08:48:48 -07007138 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007139 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
7140 status = hwDevice->create_audio_patch(hwDevice,
7141 patch->num_sources,
7142 patch->sources,
7143 patch->num_sinks,
7144 patch->sinks,
7145 handle);
7146 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007147 char *address;
7148 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
7149 address = audio_device_address_to_parameter(
7150 patch->sources[0].ext.device.type,
7151 patch->sources[0].ext.device.address);
7152 } else {
7153 address = (char *)calloc(1, 1);
7154 }
7155 AudioParameter param = AudioParameter(String8(address));
7156 free(address);
7157 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING),
7158 (int)patch->sources[0].ext.device.type);
7159 param.addInt(String8(AUDIO_PARAMETER_STREAM_INPUT_SOURCE),
7160 (int)patch->sinks[0].ext.mix.usecase.source);
7161 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7162 param.toString().string());
7163 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07007164 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007165
Eric Laurente8726fe2015-06-26 09:39:24 -07007166 if (mInDevice != mPrevInDevice) {
7167 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
7168 mPrevInDevice = mInDevice;
7169 }
Eric Laurent296fb132015-05-01 11:38:42 -07007170
Eric Laurent1c333e22014-05-20 10:48:17 -07007171 return status;
7172}
7173
7174status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
7175{
7176 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007177
7178 mInDevice = AUDIO_DEVICE_NONE;
7179
Eric Laurent1c333e22014-05-20 10:48:17 -07007180 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
7181 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
7182 status = hwDevice->release_audio_patch(hwDevice, handle);
7183 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007184 AudioParameter param;
7185 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
7186 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7187 param.toString().string());
Eric Laurent1c333e22014-05-20 10:48:17 -07007188 }
7189 return status;
7190}
7191
Eric Laurent83b88082014-06-20 18:31:16 -07007192void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
7193{
7194 Mutex::Autolock _l(mLock);
7195 mTracks.add(record);
7196}
7197
7198void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
7199{
7200 Mutex::Autolock _l(mLock);
7201 destroyTrack_l(record);
7202}
7203
7204void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
7205{
7206 ThreadBase::getAudioPortConfig(config);
7207 config->role = AUDIO_PORT_ROLE_SINK;
7208 config->ext.mix.hw_module = mInput->audioHwDev->handle();
7209 config->ext.mix.usecase.source = mAudioSource;
7210}
Eric Laurent1c333e22014-05-20 10:48:17 -07007211
Glenn Kasten63238ef2015-03-02 15:50:29 -08007212} // namespace android