blob: 65166b04ca6cda589890db4c621f24505e9eac07 [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";
rago8a397d52015-12-02 11:27:57 -0800531 case AUDIO_SOURCE_UNPROCESSED: return "unprocessed";
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800532 case AUDIO_SOURCE_FM_TUNER: return "FM tuner";
533 case AUDIO_SOURCE_HOTWORD: return "hotword";
534 default: return "unknown";
535 }
536}
537
Eric Laurent81784c32012-11-19 14:55:58 -0800538AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -0700539 audio_devices_t outDevice, audio_devices_t inDevice, type_t type, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -0800540 : Thread(false /*canCallJava*/),
541 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700542 mAudioFlinger(audioFlinger),
Glenn Kasten70949c42013-08-06 07:40:12 -0700543 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800544 // are set by PlaybackThread::readOutputParameters_l() or
545 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700546 //FIXME: mStandby should be true here. Is this some kind of hack?
Eric Laurent81784c32012-11-19 14:55:58 -0800547 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700548 mPrevOutDevice(AUDIO_DEVICE_NONE), mPrevInDevice(AUDIO_DEVICE_NONE),
549 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Eric Laurent81784c32012-11-19 14:55:58 -0800550 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700551 mDeathRecipient(new PMDeathRecipient(this)),
Wei Jia3f273d12015-11-24 09:06:49 -0800552 mSystemReady(systemReady),
553 mNotifiedBatteryStart(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800554{
Eric Laurent296fb132015-05-01 11:38:42 -0700555 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800556}
557
558AudioFlinger::ThreadBase::~ThreadBase()
559{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700560 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700561 mConfigEvents.clear();
562
Eric Laurent81784c32012-11-19 14:55:58 -0800563 // do not lock the mutex in destructor
564 releaseWakeLock_l();
565 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800566 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800567 binder->unlinkToDeath(mDeathRecipient);
568 }
569}
570
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700571status_t AudioFlinger::ThreadBase::readyToRun()
572{
573 status_t status = initCheck();
574 if (status == NO_ERROR) {
575 ALOGI("AudioFlinger's thread %p ready to run", this);
576 } else {
577 ALOGE("No working audio driver found.");
578 }
579 return status;
580}
581
Eric Laurent81784c32012-11-19 14:55:58 -0800582void AudioFlinger::ThreadBase::exit()
583{
584 ALOGV("ThreadBase::exit");
585 // do any cleanup required for exit to succeed
586 preExit();
587 {
588 // This lock prevents the following race in thread (uniprocessor for illustration):
589 // if (!exitPending()) {
590 // // context switch from here to exit()
591 // // exit() calls requestExit(), what exitPending() observes
592 // // exit() calls signal(), which is dropped since no waiters
593 // // context switch back from exit() to here
594 // mWaitWorkCV.wait(...);
595 // // now thread is hung
596 // }
597 AutoMutex lock(mLock);
598 requestExit();
599 mWaitWorkCV.broadcast();
600 }
601 // When Thread::requestExitAndWait is made virtual and this method is renamed to
602 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
603 requestExitAndWait();
604}
605
606status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
607{
608 status_t status;
609
610 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
611 Mutex::Autolock _l(mLock);
612
Eric Laurent10351942014-05-08 18:49:52 -0700613 return sendSetParameterConfigEvent_l(keyValuePairs);
614}
615
616// sendConfigEvent_l() must be called with ThreadBase::mLock held
617// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
618status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
619{
620 status_t status = NO_ERROR;
621
Eric Laurent72e3f392015-05-20 14:43:50 -0700622 if (event->mRequiresSystemReady && !mSystemReady) {
623 event->mWaitStatus = false;
624 mPendingConfigEvents.add(event);
625 return status;
626 }
Eric Laurent10351942014-05-08 18:49:52 -0700627 mConfigEvents.add(event);
628 ALOGV("sendConfigEvent_l() num events %d event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800629 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700630 mLock.unlock();
631 {
632 Mutex::Autolock _l(event->mLock);
633 while (event->mWaitStatus) {
634 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
635 event->mStatus = TIMED_OUT;
636 event->mWaitStatus = false;
637 }
638 }
639 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800640 }
Eric Laurent10351942014-05-08 18:49:52 -0700641 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800642 return status;
643}
644
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700645void AudioFlinger::ThreadBase::sendIoConfigEvent(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800646{
647 Mutex::Autolock _l(mLock);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700648 sendIoConfigEvent_l(event, pid);
Eric Laurent81784c32012-11-19 14:55:58 -0800649}
650
651// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700652void AudioFlinger::ThreadBase::sendIoConfigEvent_l(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800653{
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700654 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid);
Eric Laurent10351942014-05-08 18:49:52 -0700655 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800656}
657
Eric Laurent72e3f392015-05-20 14:43:50 -0700658void AudioFlinger::ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio)
659{
660 Mutex::Autolock _l(mLock);
661 sendPrioConfigEvent_l(pid, tid, prio);
662}
663
Eric Laurent81784c32012-11-19 14:55:58 -0800664// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
665void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
666{
Eric Laurent10351942014-05-08 18:49:52 -0700667 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio);
668 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800669}
670
Eric Laurent10351942014-05-08 18:49:52 -0700671// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
672status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800673{
Andy Hung2ddee192015-12-18 17:34:44 -0800674 sp<ConfigEvent> configEvent;
675 AudioParameter param(keyValuePair);
676 int value;
677 if (param.getInt(String8(AUDIO_PARAMETER_MONO_OUTPUT), value) == NO_ERROR) {
678 setMasterMono_l(value != 0);
679 if (param.size() == 1) {
680 return NO_ERROR; // should be a solo parameter - we don't pass down
681 }
682 param.remove(String8(AUDIO_PARAMETER_MONO_OUTPUT));
683 configEvent = new SetParameterConfigEvent(param.toString());
684 } else {
685 configEvent = new SetParameterConfigEvent(keyValuePair);
686 }
Eric Laurent10351942014-05-08 18:49:52 -0700687 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700688}
689
Eric Laurent1c333e22014-05-20 10:48:17 -0700690status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
691 const struct audio_patch *patch,
692 audio_patch_handle_t *handle)
693{
694 Mutex::Autolock _l(mLock);
695 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
696 status_t status = sendConfigEvent_l(configEvent);
697 if (status == NO_ERROR) {
698 CreateAudioPatchConfigEventData *data =
699 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
700 *handle = data->mHandle;
701 }
702 return status;
703}
704
705status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
706 const audio_patch_handle_t handle)
707{
708 Mutex::Autolock _l(mLock);
709 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
710 return sendConfigEvent_l(configEvent);
711}
712
713
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700714// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700715void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700716{
Eric Laurent10351942014-05-08 18:49:52 -0700717 bool configChanged = false;
718
Eric Laurent81784c32012-11-19 14:55:58 -0800719 while (!mConfigEvents.isEmpty()) {
Eric Laurent10351942014-05-08 18:49:52 -0700720 ALOGV("processConfigEvents_l() remaining events %d", mConfigEvents.size());
721 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800722 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700723 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700724 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700725 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
726 // FIXME Need to understand why this has to be done asynchronously
727 int err = requestPriority(data->mPid, data->mTid, data->mPrio,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700728 true /*asynchronous*/);
729 if (err != 0) {
730 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700731 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700732 }
733 } break;
734 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700735 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700736 ioConfigChanged(data->mEvent, data->mPid);
Eric Laurent10351942014-05-08 18:49:52 -0700737 } break;
738 case CFG_EVENT_SET_PARAMETER: {
739 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
740 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
741 configChanged = true;
Glenn Kastend5418eb2013-08-14 13:11:06 -0700742 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700743 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700744 case CFG_EVENT_CREATE_AUDIO_PATCH: {
745 CreateAudioPatchConfigEventData *data =
746 (CreateAudioPatchConfigEventData *)event->mData.get();
747 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
748 } break;
749 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
750 ReleaseAudioPatchConfigEventData *data =
751 (ReleaseAudioPatchConfigEventData *)event->mData.get();
752 event->mStatus = releaseAudioPatch_l(data->mHandle);
753 } break;
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700754 default:
Eric Laurent10351942014-05-08 18:49:52 -0700755 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700756 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800757 }
Eric Laurent10351942014-05-08 18:49:52 -0700758 {
759 Mutex::Autolock _l(event->mLock);
760 if (event->mWaitStatus) {
761 event->mWaitStatus = false;
762 event->mCond.signal();
763 }
764 }
765 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
766 }
767
768 if (configChanged) {
769 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800770 }
Eric Laurent81784c32012-11-19 14:55:58 -0800771}
772
Marco Nelissenb2208842014-02-07 14:00:50 -0800773String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
774 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700775 const audio_channel_representation_t representation =
776 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700777
778 switch (representation) {
779 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
780 if (output) {
781 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
782 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
783 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
784 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
785 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
786 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
787 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
788 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
789 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
790 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
791 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
792 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
793 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
794 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
795 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
796 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
797 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
798 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
799 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
800 } else {
801 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
802 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
803 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
804 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
805 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
806 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
807 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
808 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
809 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
810 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
811 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
812 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
813 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
814 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
815 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
816 }
817 const int len = s.length();
818 if (len > 2) {
819 char *str = s.lockBuffer(len); // needed?
820 s.unlockBuffer(len - 2); // remove trailing ", "
821 }
822 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800823 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700824 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
825 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
826 return s;
827 default:
828 s.appendFormat("unknown mask, representation:%d bits:%#x",
829 representation, audio_channel_mask_get_bits(mask));
830 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800831 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800832}
833
Glenn Kasten0f11b512014-01-31 16:18:54 -0800834void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800835{
836 const size_t SIZE = 256;
837 char buffer[SIZE];
838 String8 result;
839
840 bool locked = AudioFlinger::dumpTryLock(mLock);
841 if (!locked) {
Glenn Kasten97b7b752014-09-28 13:04:24 -0700842 dprintf(fd, "thread %p may be deadlocked\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -0800843 }
844
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800845 dprintf(fd, " Thread name: %s\n", mThreadName);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700846 dprintf(fd, " I/O handle: %d\n", mId);
847 dprintf(fd, " TID: %d\n", getTid());
848 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700849 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700850 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700851 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat));
Elliott Hughes87cebad2014-05-22 10:14:43 -0700852 dprintf(fd, " HAL buffer size: %u bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700853 dprintf(fd, " Channel count: %u\n", mChannelCount);
854 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800855 channelMaskToString(mChannelMask, mType != RECORD).string());
Glenn Kastenf87c2f52015-08-21 08:03:57 -0700856 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat, formatToString(mFormat));
857 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700858 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800859 size_t numConfig = mConfigEvents.size();
860 if (numConfig) {
861 for (size_t i = 0; i < numConfig; i++) {
862 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700863 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800864 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700865 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800866 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700867 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800868 }
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800869 dprintf(fd, " Output device: %#x (%s)\n", mOutDevice, devicesToString(mOutDevice).string());
870 dprintf(fd, " Input device: %#x (%s)\n", mInDevice, devicesToString(mInDevice).string());
871 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, sourceToString(mAudioSource));
Eric Laurent81784c32012-11-19 14:55:58 -0800872
873 if (locked) {
874 mLock.unlock();
875 }
876}
877
878void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
879{
880 const size_t SIZE = 256;
881 char buffer[SIZE];
882 String8 result;
883
Marco Nelissenb2208842014-02-07 14:00:50 -0800884 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000885 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800886 write(fd, buffer, strlen(buffer));
887
Marco Nelissenb2208842014-02-07 14:00:50 -0800888 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800889 sp<EffectChain> chain = mEffectChains[i];
890 if (chain != 0) {
891 chain->dump(fd, args);
892 }
893 }
894}
895
Marco Nelissene14a5d62013-10-03 08:51:24 -0700896void AudioFlinger::ThreadBase::acquireWakeLock(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800897{
898 Mutex::Autolock _l(mLock);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700899 acquireWakeLock_l(uid);
Eric Laurent81784c32012-11-19 14:55:58 -0800900}
901
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100902String16 AudioFlinger::ThreadBase::getWakeLockTag()
903{
904 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -0800905 case MIXER:
906 return String16("AudioMix");
907 case DIRECT:
908 return String16("AudioDirectOut");
909 case DUPLICATING:
910 return String16("AudioDup");
911 case RECORD:
912 return String16("AudioIn");
913 case OFFLOAD:
914 return String16("AudioOffload");
915 default:
916 ALOG_ASSERT(false);
917 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100918 }
919}
920
Marco Nelissene14a5d62013-10-03 08:51:24 -0700921void AudioFlinger::ThreadBase::acquireWakeLock_l(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800922{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800923 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800924 if (mPowerManager != 0) {
925 sp<IBinder> binder = new BBinder();
Marco Nelissene14a5d62013-10-03 08:51:24 -0700926 status_t status;
927 if (uid >= 0) {
Eric Laurent547789d2013-10-04 11:46:55 -0700928 status = mPowerManager->acquireWakeLockWithUid(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700929 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100930 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -0700931 String16("audioserver"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700932 uid,
933 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700934 } else {
Eric Laurent547789d2013-10-04 11:46:55 -0700935 status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700936 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100937 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -0700938 String16("audioserver"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700939 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700940 }
Eric Laurent81784c32012-11-19 14:55:58 -0800941 if (status == NO_ERROR) {
942 mWakeLockToken = binder;
943 }
Glenn Kastend7dca052015-03-05 16:05:54 -0800944 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Eric Laurent81784c32012-11-19 14:55:58 -0800945 }
Wei Jia3f273d12015-11-24 09:06:49 -0800946
947 if (!mNotifiedBatteryStart) {
948 BatteryNotifier::getInstance().noteStartAudio();
949 mNotifiedBatteryStart = true;
950 }
Eric Laurent81784c32012-11-19 14:55:58 -0800951}
952
953void AudioFlinger::ThreadBase::releaseWakeLock()
954{
955 Mutex::Autolock _l(mLock);
956 releaseWakeLock_l();
957}
958
959void AudioFlinger::ThreadBase::releaseWakeLock_l()
960{
961 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800962 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -0800963 if (mPowerManager != 0) {
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700964 mPowerManager->releaseWakeLock(mWakeLockToken, 0,
965 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800966 }
967 mWakeLockToken.clear();
968 }
Wei Jia3f273d12015-11-24 09:06:49 -0800969
970 if (mNotifiedBatteryStart) {
971 BatteryNotifier::getInstance().noteStopAudio();
972 mNotifiedBatteryStart = false;
973 }
Eric Laurent81784c32012-11-19 14:55:58 -0800974}
975
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800976void AudioFlinger::ThreadBase::updateWakeLockUids(const SortedVector<int> &uids) {
977 Mutex::Autolock _l(mLock);
978 updateWakeLockUids_l(uids);
979}
980
981void AudioFlinger::ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -0700982 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800983 // use checkService() to avoid blocking if power service is not up yet
984 sp<IBinder> binder =
985 defaultServiceManager()->checkService(String16("power"));
986 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800987 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800988 } else {
989 mPowerManager = interface_cast<IPowerManager>(binder);
990 binder->linkToDeath(mDeathRecipient);
991 }
992 }
993}
994
995void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<int> &uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800996 getPowerManager_l();
Andy Hung438e7572015-12-14 15:51:17 -0800997 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
998 if (mSystemReady) {
999 ALOGE("no wake lock to update, but system ready!");
1000 } else {
1001 ALOGW("no wake lock to update, system not ready yet");
1002 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001003 return;
1004 }
1005 if (mPowerManager != 0) {
1006 sp<IBinder> binder = new BBinder();
1007 status_t status;
Glenn Kasten3abc2de2014-09-05 16:45:52 -07001008 status = mPowerManager->updateWakeLockUids(mWakeLockToken, uids.size(), uids.array(),
1009 true /* FIXME force oneway contrary to .aidl */);
Glenn Kastend7dca052015-03-05 16:05:54 -08001010 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001011 }
1012}
1013
Eric Laurent81784c32012-11-19 14:55:58 -08001014void AudioFlinger::ThreadBase::clearPowerManager()
1015{
1016 Mutex::Autolock _l(mLock);
1017 releaseWakeLock_l();
1018 mPowerManager.clear();
1019}
1020
Glenn Kasten0f11b512014-01-31 16:18:54 -08001021void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001022{
1023 sp<ThreadBase> thread = mThread.promote();
1024 if (thread != 0) {
1025 thread->clearPowerManager();
1026 }
1027 ALOGW("power manager service died !!!");
1028}
1029
1030void AudioFlinger::ThreadBase::setEffectSuspended(
1031 const effect_uuid_t *type, bool suspend, int sessionId)
1032{
1033 Mutex::Autolock _l(mLock);
1034 setEffectSuspended_l(type, suspend, sessionId);
1035}
1036
1037void AudioFlinger::ThreadBase::setEffectSuspended_l(
1038 const effect_uuid_t *type, bool suspend, int sessionId)
1039{
1040 sp<EffectChain> chain = getEffectChain_l(sessionId);
1041 if (chain != 0) {
1042 if (type != NULL) {
1043 chain->setEffectSuspended_l(type, suspend);
1044 } else {
1045 chain->setEffectSuspendedAll_l(suspend);
1046 }
1047 }
1048
1049 updateSuspendedSessions_l(type, suspend, sessionId);
1050}
1051
1052void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1053{
1054 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1055 if (index < 0) {
1056 return;
1057 }
1058
1059 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1060 mSuspendedSessions.valueAt(index);
1061
1062 for (size_t i = 0; i < sessionEffects.size(); i++) {
1063 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
1064 for (int j = 0; j < desc->mRefCount; j++) {
1065 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1066 chain->setEffectSuspendedAll_l(true);
1067 } else {
1068 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1069 desc->mType.timeLow);
1070 chain->setEffectSuspended_l(&desc->mType, true);
1071 }
1072 }
1073 }
1074}
1075
1076void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1077 bool suspend,
1078 int sessionId)
1079{
1080 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1081
1082 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1083
1084 if (suspend) {
1085 if (index >= 0) {
1086 sessionEffects = mSuspendedSessions.valueAt(index);
1087 } else {
1088 mSuspendedSessions.add(sessionId, sessionEffects);
1089 }
1090 } else {
1091 if (index < 0) {
1092 return;
1093 }
1094 sessionEffects = mSuspendedSessions.valueAt(index);
1095 }
1096
1097
1098 int key = EffectChain::kKeyForSuspendAll;
1099 if (type != NULL) {
1100 key = type->timeLow;
1101 }
1102 index = sessionEffects.indexOfKey(key);
1103
1104 sp<SuspendedSessionDesc> desc;
1105 if (suspend) {
1106 if (index >= 0) {
1107 desc = sessionEffects.valueAt(index);
1108 } else {
1109 desc = new SuspendedSessionDesc();
1110 if (type != NULL) {
1111 desc->mType = *type;
1112 }
1113 sessionEffects.add(key, desc);
1114 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1115 }
1116 desc->mRefCount++;
1117 } else {
1118 if (index < 0) {
1119 return;
1120 }
1121 desc = sessionEffects.valueAt(index);
1122 if (--desc->mRefCount == 0) {
1123 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1124 sessionEffects.removeItemsAt(index);
1125 if (sessionEffects.isEmpty()) {
1126 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1127 sessionId);
1128 mSuspendedSessions.removeItem(sessionId);
1129 }
1130 }
1131 }
1132 if (!sessionEffects.isEmpty()) {
1133 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1134 }
1135}
1136
1137void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1138 bool enabled,
1139 int sessionId)
1140{
1141 Mutex::Autolock _l(mLock);
1142 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1143}
1144
1145void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1146 bool enabled,
1147 int sessionId)
1148{
1149 if (mType != RECORD) {
1150 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1151 // another session. This gives the priority to well behaved effect control panels
1152 // and applications not using global effects.
1153 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1154 // global effects
1155 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
1156 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1157 }
1158 }
1159
1160 sp<EffectChain> chain = getEffectChain_l(sessionId);
1161 if (chain != 0) {
1162 chain->checkSuspendOnEffectEnabled(effect, enabled);
1163 }
1164}
1165
1166// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1167sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1168 const sp<AudioFlinger::Client>& client,
1169 const sp<IEffectClient>& effectClient,
1170 int32_t priority,
1171 int sessionId,
1172 effect_descriptor_t *desc,
1173 int *enabled,
Glenn Kasten9156ef32013-08-06 15:39:08 -07001174 status_t *status)
Eric Laurent81784c32012-11-19 14:55:58 -08001175{
1176 sp<EffectModule> effect;
1177 sp<EffectHandle> handle;
1178 status_t lStatus;
1179 sp<EffectChain> chain;
1180 bool chainCreated = false;
1181 bool effectCreated = false;
1182 bool effectRegistered = false;
1183
1184 lStatus = initCheck();
1185 if (lStatus != NO_ERROR) {
1186 ALOGW("createEffect_l() Audio driver not initialized.");
1187 goto Exit;
1188 }
1189
Andy Hung98ef9782014-03-04 14:46:50 -08001190 // Reject any effect on Direct output threads for now, since the format of
1191 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1192 if (mType == DIRECT) {
1193 ALOGW("createEffect_l() Cannot add effect %s on Direct output type thread %s",
Glenn Kastend7dca052015-03-05 16:05:54 -08001194 desc->name, mThreadName);
Andy Hung98ef9782014-03-04 14:46:50 -08001195 lStatus = BAD_VALUE;
1196 goto Exit;
1197 }
1198
Andy Hung389cfdb2014-08-07 17:49:53 -07001199 // Reject any effect on mixer or duplicating multichannel sinks.
Andy Hung9a592762014-07-21 21:56:01 -07001200 // TODO: fix both format and multichannel issues with effects.
Andy Hung389cfdb2014-08-07 17:49:53 -07001201 if ((mType == MIXER || mType == DUPLICATING) && mChannelCount != FCC_2) {
1202 ALOGW("createEffect_l() Cannot add effect %s for multichannel(%d) %s threads",
1203 desc->name, mChannelCount, mType == MIXER ? "MIXER" : "DUPLICATING");
Andy Hung9a592762014-07-21 21:56:01 -07001204 lStatus = BAD_VALUE;
1205 goto Exit;
1206 }
1207
Eric Laurent5baf2af2013-09-12 17:37:00 -07001208 // Allow global effects only on offloaded and mixer threads
1209 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1210 switch (mType) {
1211 case MIXER:
1212 case OFFLOAD:
1213 break;
1214 case DIRECT:
1215 case DUPLICATING:
1216 case RECORD:
1217 default:
Glenn Kastend7dca052015-03-05 16:05:54 -08001218 ALOGW("createEffect_l() Cannot add global effect %s on thread %s",
1219 desc->name, mThreadName);
Eric Laurent5baf2af2013-09-12 17:37:00 -07001220 lStatus = BAD_VALUE;
1221 goto Exit;
1222 }
Eric Laurent81784c32012-11-19 14:55:58 -08001223 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07001224
Eric Laurent81784c32012-11-19 14:55:58 -08001225 // Only Pre processor effects are allowed on input threads and only on input threads
1226 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
1227 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
1228 desc->name, desc->flags, mType);
1229 lStatus = BAD_VALUE;
1230 goto Exit;
1231 }
1232
1233 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1234
1235 { // scope for mLock
1236 Mutex::Autolock _l(mLock);
1237
1238 // check for existing effect chain with the requested audio session
1239 chain = getEffectChain_l(sessionId);
1240 if (chain == 0) {
1241 // create a new chain for this session
1242 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1243 chain = new EffectChain(this, sessionId);
1244 addEffectChain_l(chain);
1245 chain->setStrategy(getStrategyForSession_l(sessionId));
1246 chainCreated = true;
1247 } else {
1248 effect = chain->getEffectFromDesc_l(desc);
1249 }
1250
1251 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1252
1253 if (effect == 0) {
1254 int id = mAudioFlinger->nextUniqueId();
1255 // Check CPU and memory usage
1256 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
1257 if (lStatus != NO_ERROR) {
1258 goto Exit;
1259 }
1260 effectRegistered = true;
1261 // create a new effect module if none present in the chain
1262 effect = new EffectModule(this, chain, desc, id, sessionId);
1263 lStatus = effect->status();
1264 if (lStatus != NO_ERROR) {
1265 goto Exit;
1266 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07001267 effect->setOffloaded(mType == OFFLOAD, mId);
1268
Eric Laurent81784c32012-11-19 14:55:58 -08001269 lStatus = chain->addEffect_l(effect);
1270 if (lStatus != NO_ERROR) {
1271 goto Exit;
1272 }
1273 effectCreated = true;
1274
1275 effect->setDevice(mOutDevice);
1276 effect->setDevice(mInDevice);
1277 effect->setMode(mAudioFlinger->getMode());
1278 effect->setAudioSource(mAudioSource);
1279 }
1280 // create effect handle and connect it to effect module
1281 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001282 lStatus = handle->initCheck();
1283 if (lStatus == OK) {
1284 lStatus = effect->addHandle(handle.get());
1285 }
Eric Laurent81784c32012-11-19 14:55:58 -08001286 if (enabled != NULL) {
1287 *enabled = (int)effect->isEnabled();
1288 }
1289 }
1290
1291Exit:
1292 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1293 Mutex::Autolock _l(mLock);
1294 if (effectCreated) {
1295 chain->removeEffect_l(effect);
1296 }
1297 if (effectRegistered) {
1298 AudioSystem::unregisterEffect(effect->id());
1299 }
1300 if (chainCreated) {
1301 removeEffectChain_l(chain);
1302 }
1303 handle.clear();
1304 }
1305
Glenn Kasten9156ef32013-08-06 15:39:08 -07001306 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001307 return handle;
1308}
1309
1310sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
1311{
1312 Mutex::Autolock _l(mLock);
1313 return getEffect_l(sessionId, effectId);
1314}
1315
1316sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
1317{
1318 sp<EffectChain> chain = getEffectChain_l(sessionId);
1319 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1320}
1321
1322// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1323// PlaybackThread::mLock held
1324status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1325{
1326 // check for existing effect chain with the requested audio session
1327 int sessionId = effect->sessionId();
1328 sp<EffectChain> chain = getEffectChain_l(sessionId);
1329 bool chainCreated = false;
1330
Eric Laurent5baf2af2013-09-12 17:37:00 -07001331 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
1332 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
1333 this, effect->desc().name, effect->desc().flags);
1334
Eric Laurent81784c32012-11-19 14:55:58 -08001335 if (chain == 0) {
1336 // create a new chain for this session
1337 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1338 chain = new EffectChain(this, sessionId);
1339 addEffectChain_l(chain);
1340 chain->setStrategy(getStrategyForSession_l(sessionId));
1341 chainCreated = true;
1342 }
1343 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1344
1345 if (chain->getEffectFromId_l(effect->id()) != 0) {
1346 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1347 this, effect->desc().name, chain.get());
1348 return BAD_VALUE;
1349 }
1350
Eric Laurent5baf2af2013-09-12 17:37:00 -07001351 effect->setOffloaded(mType == OFFLOAD, mId);
1352
Eric Laurent81784c32012-11-19 14:55:58 -08001353 status_t status = chain->addEffect_l(effect);
1354 if (status != NO_ERROR) {
1355 if (chainCreated) {
1356 removeEffectChain_l(chain);
1357 }
1358 return status;
1359 }
1360
1361 effect->setDevice(mOutDevice);
1362 effect->setDevice(mInDevice);
1363 effect->setMode(mAudioFlinger->getMode());
1364 effect->setAudioSource(mAudioSource);
1365 return NO_ERROR;
1366}
1367
1368void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
1369
1370 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
1371 effect_descriptor_t desc = effect->desc();
1372 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1373 detachAuxEffect_l(effect->id());
1374 }
1375
1376 sp<EffectChain> chain = effect->chain().promote();
1377 if (chain != 0) {
1378 // remove effect chain if removing last effect
1379 if (chain->removeEffect_l(effect) == 0) {
1380 removeEffectChain_l(chain);
1381 }
1382 } else {
1383 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1384 }
1385}
1386
1387void AudioFlinger::ThreadBase::lockEffectChains_l(
1388 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1389{
1390 effectChains = mEffectChains;
1391 for (size_t i = 0; i < mEffectChains.size(); i++) {
1392 mEffectChains[i]->lock();
1393 }
1394}
1395
1396void AudioFlinger::ThreadBase::unlockEffectChains(
1397 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1398{
1399 for (size_t i = 0; i < effectChains.size(); i++) {
1400 effectChains[i]->unlock();
1401 }
1402}
1403
1404sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
1405{
1406 Mutex::Autolock _l(mLock);
1407 return getEffectChain_l(sessionId);
1408}
1409
1410sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const
1411{
1412 size_t size = mEffectChains.size();
1413 for (size_t i = 0; i < size; i++) {
1414 if (mEffectChains[i]->sessionId() == sessionId) {
1415 return mEffectChains[i];
1416 }
1417 }
1418 return 0;
1419}
1420
1421void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1422{
1423 Mutex::Autolock _l(mLock);
1424 size_t size = mEffectChains.size();
1425 for (size_t i = 0; i < size; i++) {
1426 mEffectChains[i]->setMode_l(mode);
1427 }
1428}
1429
Eric Laurent83b88082014-06-20 18:31:16 -07001430void AudioFlinger::ThreadBase::getAudioPortConfig(struct audio_port_config *config)
1431{
1432 config->type = AUDIO_PORT_TYPE_MIX;
1433 config->ext.mix.handle = mId;
1434 config->sample_rate = mSampleRate;
1435 config->format = mFormat;
1436 config->channel_mask = mChannelMask;
1437 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1438 AUDIO_PORT_CONFIG_FORMAT;
1439}
1440
Eric Laurent72e3f392015-05-20 14:43:50 -07001441void AudioFlinger::ThreadBase::systemReady()
1442{
1443 Mutex::Autolock _l(mLock);
1444 if (mSystemReady) {
1445 return;
1446 }
1447 mSystemReady = true;
1448
1449 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1450 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1451 }
1452 mPendingConfigEvents.clear();
1453}
1454
Eric Laurent83b88082014-06-20 18:31:16 -07001455
Eric Laurent81784c32012-11-19 14:55:58 -08001456// ----------------------------------------------------------------------------
1457// Playback
1458// ----------------------------------------------------------------------------
1459
1460AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1461 AudioStreamOut* output,
1462 audio_io_handle_t id,
1463 audio_devices_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07001464 type_t type,
1465 bool systemReady)
1466 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type, systemReady),
Andy Hung2098f272014-02-27 14:00:06 -08001467 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001468 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001469 mMixerBuffer(NULL),
1470 mMixerBufferSize(0),
1471 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1472 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001473 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001474 mEffectBuffer(NULL),
1475 mEffectBufferSize(0),
1476 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1477 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001478 mSuspended(0), mBytesWritten(0),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001479 mActiveTracksGeneration(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001480 // mStreamTypes[] initialized in constructor body
1481 mOutput(output),
1482 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
1483 mMixerStatus(MIXER_IDLE),
1484 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001485 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001486 mBytesRemaining(0),
1487 mCurrentWriteLength(0),
1488 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001489 mWriteAckSequence(0),
1490 mDrainSequence(0),
Eric Laurentede6c3b2013-09-19 14:37:46 -07001491 mSignalPending(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001492 mScreenState(AudioFlinger::mScreenState),
1493 // index 0 is reserved for normal mixer's submix
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001494 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1),
Eric Laurentd1f69b02014-12-15 14:33:13 -08001495 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001496 // mLatchD, mLatchQ,
1497 mLatchDValid(false), mLatchQValid(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001498{
Glenn Kastend7dca052015-03-05 16:05:54 -08001499 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1500 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001501
1502 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1503 // it would be safer to explicitly pass initial masterVolume/masterMute as
1504 // parameter.
1505 //
1506 // If the HAL we are using has support for master volume or master mute,
1507 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1508 // and the mute set to false).
1509 mMasterVolume = audioFlinger->masterVolume_l();
1510 mMasterMute = audioFlinger->masterMute_l();
1511 if (mOutput && mOutput->audioHwDev) {
1512 if (mOutput->audioHwDev->canSetMasterVolume()) {
1513 mMasterVolume = 1.0;
1514 }
1515
1516 if (mOutput->audioHwDev->canSetMasterMute()) {
1517 mMasterMute = false;
1518 }
1519 }
1520
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001521 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001522
Eric Laurent223fd5c2014-11-11 13:43:36 -08001523 // ++ operator does not compile
Glenn Kasten66e46352014-01-16 17:44:23 -08001524 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001525 stream = (audio_stream_type_t) (stream + 1)) {
1526 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1527 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1528 }
Eric Laurent81784c32012-11-19 14:55:58 -08001529}
1530
1531AudioFlinger::PlaybackThread::~PlaybackThread()
1532{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001533 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001534 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001535 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001536 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001537}
1538
1539void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1540{
1541 dumpInternals(fd, args);
1542 dumpTracks(fd, args);
1543 dumpEffectChains(fd, args);
1544}
1545
Glenn Kasten0f11b512014-01-31 16:18:54 -08001546void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001547{
1548 const size_t SIZE = 256;
1549 char buffer[SIZE];
1550 String8 result;
1551
Marco Nelissenb2208842014-02-07 14:00:50 -08001552 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001553 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1554 const stream_type_t *st = &mStreamTypes[i];
1555 if (i > 0) {
1556 result.appendFormat(", ");
1557 }
1558 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1559 if (st->mute) {
1560 result.append("M");
1561 }
1562 }
1563 result.append("\n");
1564 write(fd, result.string(), result.length());
1565 result.clear();
1566
Eric Laurent81784c32012-11-19 14:55:58 -08001567 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1568 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001569 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001570 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001571
1572 size_t numtracks = mTracks.size();
1573 size_t numactive = mActiveTracks.size();
Elliott Hughes87cebad2014-05-22 10:14:43 -07001574 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001575 size_t numactiveseen = 0;
1576 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07001577 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08001578 Track::appendDumpHeader(result);
1579 for (size_t i = 0; i < numtracks; ++i) {
1580 sp<Track> track = mTracks[i];
1581 if (track != 0) {
1582 bool active = mActiveTracks.indexOf(track) >= 0;
1583 if (active) {
1584 numactiveseen++;
1585 }
1586 track->dump(buffer, SIZE, active);
1587 result.append(buffer);
1588 }
1589 }
1590 } else {
1591 result.append("\n");
1592 }
1593 if (numactiveseen != numactive) {
1594 // some tracks in the active list were not in the tracks list
1595 snprintf(buffer, SIZE, " The following tracks are in the active list but"
1596 " not in the track list\n");
1597 result.append(buffer);
1598 Track::appendDumpHeader(result);
1599 for (size_t i = 0; i < numactive; ++i) {
1600 sp<Track> track = mActiveTracks[i].promote();
1601 if (track != 0 && mTracks.indexOf(track) < 0) {
1602 track->dump(buffer, SIZE, true);
1603 result.append(buffer);
1604 }
1605 }
1606 }
1607
1608 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001609}
1610
1611void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1612{
Glenn Kasten97b7b752014-09-28 13:04:24 -07001613 dprintf(fd, "\nOutput thread %p type %d (%s):\n", this, type(), threadTypeToString(type()));
Glenn Kasten44182c22015-03-05 17:12:23 -08001614
1615 dumpBase(fd, args);
1616
Elliott Hughes87cebad2014-05-22 10:14:43 -07001617 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
1618 dprintf(fd, " Last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1619 dprintf(fd, " Total writes: %d\n", mNumWrites);
1620 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1621 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1622 dprintf(fd, " Suspend count: %d\n", mSuspended);
1623 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1624 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1625 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1626 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08001627 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001628 AudioStreamOut *output = mOutput;
1629 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
1630 String8 flagsAsString = outputFlagsToString(flags);
1631 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n", output, flags, flagsAsString.string());
Eric Laurent81784c32012-11-19 14:55:58 -08001632}
1633
1634// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001635
1636void AudioFlinger::PlaybackThread::onFirstRef()
1637{
Glenn Kastend7dca052015-03-05 16:05:54 -08001638 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001639}
1640
1641// ThreadBase virtuals
1642void AudioFlinger::PlaybackThread::preExit()
1643{
1644 ALOGV(" preExit()");
1645 // FIXME this is using hard-coded strings but in the future, this functionality will be
1646 // converted to use audio HAL extensions required to support tunneling
1647 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1648}
1649
1650// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1651sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1652 const sp<AudioFlinger::Client>& client,
1653 audio_stream_type_t streamType,
1654 uint32_t sampleRate,
1655 audio_format_t format,
1656 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001657 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001658 const sp<IMemory>& sharedBuffer,
1659 int sessionId,
1660 IAudioFlinger::track_flags_t *flags,
1661 pid_t tid,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001662 int uid,
Eric Laurent81784c32012-11-19 14:55:58 -08001663 status_t *status)
1664{
Glenn Kasten74935e42013-12-19 08:56:45 -08001665 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001666 sp<Track> track;
1667 status_t lStatus;
1668
1669 bool isTimed = (*flags & IAudioFlinger::TRACK_TIMED) != 0;
1670
1671 // client expresses a preference for FAST, but we get the final say
1672 if (*flags & IAudioFlinger::TRACK_FAST) {
1673 if (
1674 // not timed
1675 (!isTimed) &&
1676 // either of these use cases:
1677 (
1678 // use case 1: shared buffer with any frame count
1679 (
1680 (sharedBuffer != 0)
1681 ) ||
Glenn Kasten1dfe2f92015-03-09 12:03:14 -07001682 // use case 2: frame count is default or at least as large as HAL
Eric Laurent81784c32012-11-19 14:55:58 -08001683 (
Glenn Kasten1dfe2f92015-03-09 12:03:14 -07001684 // we formerly checked for a callback handler (non-0 tid),
1685 // but that is no longer required for TRANSFER_OBTAIN mode
Eric Laurent81784c32012-11-19 14:55:58 -08001686 ((frameCount == 0) ||
Glenn Kastenb5fed682013-12-03 09:06:43 -08001687 (frameCount >= mFrameCount))
Eric Laurent81784c32012-11-19 14:55:58 -08001688 )
1689 ) &&
1690 // PCM data
1691 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07001692 // TODO: extract as a data library function that checks that a computationally
1693 // expensive downmixer is not required: isFastOutputChannelConversion()
Andy Hung9a592762014-07-21 21:56:01 -07001694 (channelMask == mChannelMask ||
Andy Hung1f439e12015-05-19 12:57:41 -07001695 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
1696 (channelMask == AUDIO_CHANNEL_OUT_MONO
1697 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001698 // hardware sample rate
1699 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001700 // normal mixer has an associated fast mixer
1701 hasFastMixer() &&
1702 // there are sufficient fast track slots available
1703 (mFastTrackAvailMask != 0)
1704 // FIXME test that MixerThread for this fast track has a capable output HAL
1705 // FIXME add a permission test also?
1706 ) {
1707 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1708 if (frameCount == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001709 // read the fast track multiplier property the first time it is needed
1710 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1711 if (ok != 0) {
1712 ALOGE("%s pthread_once failed: %d", __func__, ok);
1713 }
1714 frameCount = mFrameCount * sFastTrackMultiplier;
Eric Laurent81784c32012-11-19 14:55:58 -08001715 }
1716 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
1717 frameCount, mFrameCount);
1718 } else {
1719 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
Andy Hung6146c082014-03-18 11:56:15 -07001720 "mFrameCount=%d format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
1721 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001722 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Andy Hung6146c082014-03-18 11:56:15 -07001723 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001724 audio_is_linear_pcm(format),
1725 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
1726 *flags &= ~IAudioFlinger::TRACK_FAST;
Andy Hung0e48d252015-01-26 11:43:15 -08001727 }
1728 }
1729 // For normal PCM streaming tracks, update minimum frame count.
1730 // For compatibility with AudioTrack calculation, buffer depth is forced
1731 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1732 // This is probably too conservative, but legacy application code may depend on it.
1733 // If you change this calculation, also review the start threshold which is related.
1734 if (!(*flags & IAudioFlinger::TRACK_FAST)
1735 && audio_is_linear_pcm(format) && sharedBuffer == 0) {
Andy Hung8edb8dc2015-03-26 19:13:55 -07001736 // this must match AudioTrack.cpp calculateMinFrameCount().
1737 // TODO: Move to a common library
Eric Laurent81784c32012-11-19 14:55:58 -08001738 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1739 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1740 if (minBufCount < 2) {
1741 minBufCount = 2;
1742 }
Andy Hung8edb8dc2015-03-26 19:13:55 -07001743 // For normal mixing tracks, if speed is > 1.0f (normal), AudioTrack
1744 // or the client should compute and pass in a larger buffer request.
Andy Hung0e48d252015-01-26 11:43:15 -08001745 size_t minFrameCount =
Andy Hung8edb8dc2015-03-26 19:13:55 -07001746 minBufCount * sourceFramesNeededWithTimestretch(
1747 sampleRate, mNormalFrameCount,
1748 mSampleRate, AUDIO_TIMESTRETCH_SPEED_NORMAL /*speed*/);
Andy Hung0e48d252015-01-26 11:43:15 -08001749 if (frameCount < minFrameCount) { // including frameCount == 0
Eric Laurent81784c32012-11-19 14:55:58 -08001750 frameCount = minFrameCount;
1751 }
Eric Laurent81784c32012-11-19 14:55:58 -08001752 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001753 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001754
Glenn Kastenc3df8382014-03-13 15:05:25 -07001755 switch (mType) {
1756
1757 case DIRECT:
Glenn Kasten993fa062014-05-02 11:14:34 -07001758 if (audio_is_linear_pcm(format)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001759 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001760 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1761 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001762 sampleRate, format, channelMask, mOutput, mFormat);
1763 lStatus = BAD_VALUE;
1764 goto Exit;
1765 }
1766 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001767 break;
1768
1769 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001770 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001771 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1772 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001773 sampleRate, format, channelMask, mOutput, mFormat);
1774 lStatus = BAD_VALUE;
1775 goto Exit;
1776 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001777 break;
1778
1779 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07001780 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001781 ALOGE("createTrack_l() Bad parameter: format %#x \""
1782 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001783 format, mOutput, mFormat);
1784 lStatus = BAD_VALUE;
1785 goto Exit;
1786 }
Andy Hungcd044842014-08-07 11:04:34 -07001787 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08001788 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1789 lStatus = BAD_VALUE;
1790 goto Exit;
1791 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001792 break;
1793
Eric Laurent81784c32012-11-19 14:55:58 -08001794 }
1795
1796 lStatus = initCheck();
1797 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07001798 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08001799 goto Exit;
1800 }
1801
1802 { // scope for mLock
1803 Mutex::Autolock _l(mLock);
1804
1805 // all tracks in same audio session must share the same routing strategy otherwise
1806 // conflicts will happen when tracks are moved from one output to another by audio policy
1807 // manager
1808 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1809 for (size_t i = 0; i < mTracks.size(); ++i) {
1810 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07001811 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001812 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1813 if (sessionId == t->sessionId() && strategy != actual) {
1814 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1815 strategy, actual);
1816 lStatus = BAD_VALUE;
1817 goto Exit;
1818 }
1819 }
1820 }
1821
1822 if (!isTimed) {
1823 track = new Track(this, client, streamType, sampleRate, format,
Eric Laurent83b88082014-06-20 18:31:16 -07001824 channelMask, frameCount, NULL, sharedBuffer,
1825 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08001826 } else {
1827 track = TimedTrack::create(this, client, streamType, sampleRate, format,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001828 channelMask, frameCount, sharedBuffer, sessionId, uid);
Eric Laurent81784c32012-11-19 14:55:58 -08001829 }
Glenn Kasten03003332013-08-06 15:40:54 -07001830
1831 // new Track always returns non-NULL,
1832 // but TimedTrack::create() is a factory that could fail by returning NULL
1833 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
1834 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08001835 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001836 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08001837 goto Exit;
1838 }
1839 mTracks.add(track);
1840
1841 sp<EffectChain> chain = getEffectChain_l(sessionId);
1842 if (chain != 0) {
1843 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1844 track->setMainBuffer(chain->inBuffer());
1845 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1846 chain->incTrackCnt();
1847 }
1848
1849 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1850 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1851 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1852 // so ask activity manager to do this on our behalf
1853 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1854 }
1855 }
1856
1857 lStatus = NO_ERROR;
1858
1859Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001860 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001861 return track;
1862}
1863
1864uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1865{
1866 return latency;
1867}
1868
1869uint32_t AudioFlinger::PlaybackThread::latency() const
1870{
1871 Mutex::Autolock _l(mLock);
1872 return latency_l();
1873}
1874uint32_t AudioFlinger::PlaybackThread::latency_l() const
1875{
1876 if (initCheck() == NO_ERROR) {
1877 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
1878 } else {
1879 return 0;
1880 }
1881}
1882
1883void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1884{
1885 Mutex::Autolock _l(mLock);
1886 // Don't apply master volume in SW if our HAL can do it for us.
1887 if (mOutput && mOutput->audioHwDev &&
1888 mOutput->audioHwDev->canSetMasterVolume()) {
1889 mMasterVolume = 1.0;
1890 } else {
1891 mMasterVolume = value;
1892 }
1893}
1894
1895void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1896{
1897 Mutex::Autolock _l(mLock);
1898 // Don't apply master mute in SW if our HAL can do it for us.
1899 if (mOutput && mOutput->audioHwDev &&
1900 mOutput->audioHwDev->canSetMasterMute()) {
1901 mMasterMute = false;
1902 } else {
1903 mMasterMute = muted;
1904 }
1905}
1906
1907void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
1908{
1909 Mutex::Autolock _l(mLock);
1910 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001911 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001912}
1913
1914void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
1915{
1916 Mutex::Autolock _l(mLock);
1917 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001918 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001919}
1920
1921float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
1922{
1923 Mutex::Autolock _l(mLock);
1924 return mStreamTypes[stream].volume;
1925}
1926
1927// addTrack_l() must be called with ThreadBase::mLock held
1928status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1929{
1930 status_t status = ALREADY_EXISTS;
1931
1932 // set retry count for buffer fill
1933 track->mRetryCount = kMaxTrackStartupRetries;
1934 if (mActiveTracks.indexOf(track) < 0) {
1935 // the track is newly added, make sure it fills up all its
1936 // buffers before playing. This is to ensure the client will
1937 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07001938 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001939 TrackBase::track_state state = track->mState;
1940 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08001941 status = AudioSystem::startOutput(mId, track->streamType(),
1942 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001943 mLock.lock();
1944 // abort track was stopped/paused while we released the lock
1945 if (state != track->mState) {
1946 if (status == NO_ERROR) {
1947 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08001948 AudioSystem::stopOutput(mId, track->streamType(),
1949 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001950 mLock.lock();
1951 }
1952 return INVALID_OPERATION;
1953 }
1954 // abort if start is rejected by audio policy manager
1955 if (status != NO_ERROR) {
1956 return PERMISSION_DENIED;
1957 }
1958#ifdef ADD_BATTERY_DATA
1959 // to track the speaker usage
1960 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
1961#endif
1962 }
1963
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001964 track->mFillingUpStatus = track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent81784c32012-11-19 14:55:58 -08001965 track->mResetDone = false;
1966 track->mPresentationCompleteFrames = 0;
1967 mActiveTracks.add(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001968 mWakeLockUids.add(track->uid());
1969 mActiveTracksGeneration++;
Eric Laurentfd477972013-10-25 18:10:40 -07001970 mLatestActiveTrack = track;
Eric Laurentd0107bc2013-06-11 14:38:48 -07001971 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1972 if (chain != 0) {
1973 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
1974 track->sessionId());
1975 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08001976 }
1977
1978 status = NO_ERROR;
1979 }
1980
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08001981 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001982 return status;
1983}
1984
Eric Laurentbfb1b832013-01-07 09:53:42 -08001985bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08001986{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001987 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08001988 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001989 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
1990 track->mState = TrackBase::STOPPED;
1991 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08001992 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07001993 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001994 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08001995 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001996
1997 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08001998}
1999
2000void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2001{
2002 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
2003 mTracks.remove(track);
2004 deleteTrackName_l(track->name());
2005 // redundant as track is about to be destroyed, for dumpsys only
2006 track->mName = -1;
2007 if (track->isFastTrack()) {
2008 int index = track->mFastIndex;
2009 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
2010 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2011 mFastTrackAvailMask |= 1 << index;
2012 // redundant as track is about to be destroyed, for dumpsys only
2013 track->mFastIndex = -1;
2014 }
2015 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2016 if (chain != 0) {
2017 chain->decTrackCnt();
2018 }
2019}
2020
Eric Laurentede6c3b2013-09-19 14:37:46 -07002021void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002022{
2023 // Thread could be blocked waiting for async
2024 // so signal it to handle state changes immediately
2025 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
2026 // be lost so we also flag to prevent it blocking on mWaitWorkCV
2027 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002028 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002029}
2030
Eric Laurent81784c32012-11-19 14:55:58 -08002031String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2032{
Eric Laurent81784c32012-11-19 14:55:58 -08002033 Mutex::Autolock _l(mLock);
2034 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07002035 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002036 }
2037
Glenn Kastend8ea6992013-07-16 14:17:15 -07002038 char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
2039 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08002040 free(s);
2041 return out_s8;
2042}
2043
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002044void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002045 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2046 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002047
Eric Laurent73e26b62015-04-27 16:55:58 -07002048 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002049
2050 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002051 case AUDIO_OUTPUT_OPENED:
2052 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002053 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002054 desc->mChannelMask = mChannelMask;
2055 desc->mSamplingRate = mSampleRate;
2056 desc->mFormat = mFormat;
2057 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002058 // AudioFlinger::frameCount(audio_io_handle_t)
Eric Laurent73e26b62015-04-27 16:55:58 -07002059 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002060 break;
2061
Eric Laurent73e26b62015-04-27 16:55:58 -07002062 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002063 default:
2064 break;
2065 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002066 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002067}
2068
Eric Laurentbfb1b832013-01-07 09:53:42 -08002069void AudioFlinger::PlaybackThread::writeCallback()
2070{
2071 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002072 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002073}
2074
2075void AudioFlinger::PlaybackThread::drainCallback()
2076{
2077 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002078 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002079}
2080
Eric Laurent3b4529e2013-09-05 18:09:19 -07002081void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002082{
2083 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002084 // reject out of sequence requests
2085 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2086 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002087 mWaitWorkCV.signal();
2088 }
2089}
2090
Eric Laurent3b4529e2013-09-05 18:09:19 -07002091void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002092{
2093 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002094 // reject out of sequence requests
2095 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
2096 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002097 mWaitWorkCV.signal();
2098 }
2099}
2100
2101// static
2102int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
Glenn Kasten0f11b512014-01-31 16:18:54 -08002103 void *param __unused,
Eric Laurentbfb1b832013-01-07 09:53:42 -08002104 void *cookie)
2105{
2106 AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
2107 ALOGV("asyncCallback() event %d", event);
2108 switch (event) {
2109 case STREAM_CBK_EVENT_WRITE_READY:
2110 me->writeCallback();
2111 break;
2112 case STREAM_CBK_EVENT_DRAIN_READY:
2113 me->drainCallback();
2114 break;
2115 default:
2116 ALOGW("asyncCallback() unknown event %d", event);
2117 break;
2118 }
2119 return 0;
2120}
2121
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002122void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002123{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002124 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Phil Burkca5e6142015-07-14 09:42:29 -07002125 mSampleRate = mOutput->getSampleRate();
2126 mChannelMask = mOutput->getChannelMask();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002127 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002128 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002129 }
Andy Hung9a592762014-07-21 21:56:01 -07002130 if ((mType == MIXER || mType == DUPLICATING)
2131 && !isValidPcmSinkChannelMask(mChannelMask)) {
2132 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2133 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002134 }
Andy Hunge5412692014-05-16 11:25:07 -07002135 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002136
2137 // Get actual HAL format.
Andy Hung463be252014-07-10 16:56:07 -07002138 mHALFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Phil Burkca5e6142015-07-14 09:42:29 -07002139 // Get format from the shim, which will be different than the HAL format
2140 // if playing compressed audio over HDMI passthrough.
2141 mFormat = mOutput->getFormat();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002142 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002143 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002144 }
Andy Hung6146c082014-03-18 11:56:15 -07002145 if ((mType == MIXER || mType == DUPLICATING)
2146 && !isValidPcmSinkFormat(mFormat)) {
2147 LOG_FATAL("HAL format %#x not supported for mixed output",
2148 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002149 }
Phil Burk062e67a2015-02-11 13:40:50 -08002150 mFrameSize = mOutput->getFrameSize();
Glenn Kasten70949c42013-08-06 07:40:12 -07002151 mBufferSize = mOutput->stream->common.get_buffer_size(&mOutput->stream->common);
2152 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002153 if (mFrameCount & 15) {
2154 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
2155 mFrameCount);
2156 }
2157
Eric Laurentbfb1b832013-01-07 09:53:42 -08002158 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
2159 (mOutput->stream->set_callback != NULL)) {
2160 if (mOutput->stream->set_callback(mOutput->stream,
2161 AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
2162 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002163 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002164 }
2165 }
2166
Eric Laurentd1f69b02014-12-15 14:33:13 -08002167 mHwSupportsPause = false;
2168 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
2169 if (mOutput->stream->pause != NULL) {
2170 if (mOutput->stream->resume != NULL) {
2171 mHwSupportsPause = true;
2172 } else {
2173 ALOGW("direct output implements pause but not resume");
2174 }
2175 } else if (mOutput->stream->resume != NULL) {
2176 ALOGW("direct output implements resume but not pause");
2177 }
2178 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002179 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2180 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2181 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002182
Andy Hungfbfc3952015-01-15 13:33:51 -08002183 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2184 // For best precision, we use float instead of the associated output
2185 // device format (typically PCM 16 bit).
2186
2187 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2188 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2189 mBufferSize = mFrameSize * mFrameCount;
2190
2191 // TODO: We currently use the associated output device channel mask and sample rate.
2192 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2193 // (if a valid mask) to avoid premature downmix.
2194 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2195 // instead of the output device sample rate to avoid loss of high frequency information.
2196 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2197 }
2198
Andy Hung09a50072014-02-27 14:30:47 -08002199 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002200 double multiplier = 1.0;
2201 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2202 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002203 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2204 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Eric Laurent81784c32012-11-19 14:55:58 -08002205 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2206 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2207 maxNormalFrameCount = maxNormalFrameCount & ~15;
2208 if (maxNormalFrameCount < minNormalFrameCount) {
2209 maxNormalFrameCount = minNormalFrameCount;
2210 }
2211 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2212 if (multiplier <= 1.0) {
2213 multiplier = 1.0;
2214 } else if (multiplier <= 2.0) {
2215 if (2 * mFrameCount <= maxNormalFrameCount) {
2216 multiplier = 2.0;
2217 } else {
2218 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2219 }
2220 } else {
2221 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
Andy Hung09a50072014-02-27 14:30:47 -08002222 // 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 -08002223 // track, but we sometimes have to do this to satisfy the maximum frame count
2224 // constraint)
2225 // FIXME this rounding up should not be done if no HAL SRC
2226 uint32_t truncMult = (uint32_t) multiplier;
2227 if ((truncMult & 1)) {
2228 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
2229 ++truncMult;
2230 }
2231 }
2232 multiplier = (double) truncMult;
2233 }
2234 }
2235 mNormalFrameCount = multiplier * mFrameCount;
2236 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002237 if (mType == MIXER || mType == DUPLICATING) {
2238 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2239 }
Andy Hung09a50072014-02-27 14:30:47 -08002240 ALOGI("HAL output buffer size %u frames, normal sink buffer size %u frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002241 mNormalFrameCount);
2242
Andy Hung08fb1742015-05-31 23:22:10 -07002243 // Check if we want to throttle the processing to no more than 2x normal rate
2244 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002245 mThreadThrottleTimeMs = 0;
2246 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002247 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2248
Andy Hung010a1a12014-03-13 13:57:33 -07002249 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2250 // Originally this was int16_t[] array, need to remove legacy implications.
2251 free(mSinkBuffer);
2252 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002253 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2254 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2255 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002256 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002257
Andy Hung69aed5f2014-02-25 17:24:40 -08002258 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2259 // drives the output.
2260 free(mMixerBuffer);
2261 mMixerBuffer = NULL;
2262 if (mMixerBufferEnabled) {
2263 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2264 mMixerBufferSize = mNormalFrameCount * mChannelCount
2265 * audio_bytes_per_sample(mMixerBufferFormat);
2266 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2267 }
Andy Hung98ef9782014-03-04 14:46:50 -08002268 free(mEffectBuffer);
2269 mEffectBuffer = NULL;
2270 if (mEffectBufferEnabled) {
2271 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
2272 mEffectBufferSize = mNormalFrameCount * mChannelCount
2273 * audio_bytes_per_sample(mEffectBufferFormat);
2274 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2275 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002276
Eric Laurent81784c32012-11-19 14:55:58 -08002277 // force reconfiguration of effect chains and engines to take new buffer size and audio
2278 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002279 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002280 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2281 // matter.
2282 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2283 Vector< sp<EffectChain> > effectChains = mEffectChains;
2284 for (size_t i = 0; i < effectChains.size(); i ++) {
2285 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2286 }
2287}
2288
2289
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002290status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002291{
2292 if (halFrames == NULL || dspFrames == NULL) {
2293 return BAD_VALUE;
2294 }
2295 Mutex::Autolock _l(mLock);
2296 if (initCheck() != NO_ERROR) {
2297 return INVALID_OPERATION;
2298 }
2299 size_t framesWritten = mBytesWritten / mFrameSize;
2300 *halFrames = framesWritten;
2301
2302 if (isSuspended()) {
2303 // return an estimation of rendered frames when the output is suspended
2304 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
2305 *dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0;
2306 return NO_ERROR;
2307 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002308 status_t status;
2309 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002310 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002311 *dspFrames = (size_t)frames;
2312 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002313 }
2314}
2315
2316uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
2317{
2318 Mutex::Autolock _l(mLock);
2319 uint32_t result = 0;
2320 if (getEffectChain_l(sessionId) != 0) {
2321 result = EFFECT_SESSION;
2322 }
2323
2324 for (size_t i = 0; i < mTracks.size(); ++i) {
2325 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002326 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002327 result |= TRACK_SESSION;
2328 break;
2329 }
2330 }
2331
2332 return result;
2333}
2334
2335uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
2336{
2337 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2338 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2339 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2340 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2341 }
2342 for (size_t i = 0; i < mTracks.size(); i++) {
2343 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002344 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002345 return AudioSystem::getStrategyForStream(track->streamType());
2346 }
2347 }
2348 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2349}
2350
2351
Phil Burk062e67a2015-02-11 13:40:50 -08002352AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002353{
2354 Mutex::Autolock _l(mLock);
2355 return mOutput;
2356}
2357
Phil Burk062e67a2015-02-11 13:40:50 -08002358AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002359{
2360 Mutex::Autolock _l(mLock);
2361 AudioStreamOut *output = mOutput;
2362 mOutput = NULL;
2363 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2364 // must push a NULL and wait for ack
2365 mOutputSink.clear();
2366 mPipeSink.clear();
2367 mNormalSink.clear();
2368 return output;
2369}
2370
2371// this method must always be called either with ThreadBase mLock held or inside the thread loop
2372audio_stream_t* AudioFlinger::PlaybackThread::stream() const
2373{
2374 if (mOutput == NULL) {
2375 return NULL;
2376 }
2377 return &mOutput->stream->common;
2378}
2379
2380uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2381{
2382 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2383}
2384
2385status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2386{
2387 if (!isValidSyncEvent(event)) {
2388 return BAD_VALUE;
2389 }
2390
2391 Mutex::Autolock _l(mLock);
2392
2393 for (size_t i = 0; i < mTracks.size(); ++i) {
2394 sp<Track> track = mTracks[i];
2395 if (event->triggerSession() == track->sessionId()) {
2396 (void) track->setSyncEvent(event);
2397 return NO_ERROR;
2398 }
2399 }
2400
2401 return NAME_NOT_FOUND;
2402}
2403
2404bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2405{
2406 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2407}
2408
2409void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2410 const Vector< sp<Track> >& tracksToRemove)
2411{
2412 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002413 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002414 for (size_t i = 0 ; i < count ; i++) {
2415 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002416 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002417 AudioSystem::stopOutput(mId, track->streamType(),
2418 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002419#ifdef ADD_BATTERY_DATA
2420 // to track the speaker usage
2421 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2422#endif
2423 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002424 AudioSystem::releaseOutput(mId, track->streamType(),
2425 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002426 }
Eric Laurent81784c32012-11-19 14:55:58 -08002427 }
2428 }
2429 }
Eric Laurent81784c32012-11-19 14:55:58 -08002430}
2431
2432void AudioFlinger::PlaybackThread::checkSilentMode_l()
2433{
2434 if (!mMasterMute) {
2435 char value[PROPERTY_VALUE_MAX];
2436 if (property_get("ro.audio.silent", value, "0") > 0) {
2437 char *endptr;
2438 unsigned long ul = strtoul(value, &endptr, 0);
2439 if (*endptr == '\0' && ul != 0) {
2440 ALOGD("Silence is golden");
2441 // The setprop command will not allow a property to be changed after
2442 // the first time it is set, so we don't have to worry about un-muting.
2443 setMasterMute_l(true);
2444 }
2445 }
2446 }
2447}
2448
2449// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002450ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002451{
2452 // FIXME rewrite to reduce number of system calls
2453 mLastWriteTime = systemTime();
2454 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002455 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002456 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002457
2458 // If an NBAIO sink is present, use it to write the normal mixer's submix
2459 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002460
Andy Hung010a1a12014-03-13 13:57:33 -07002461 const size_t count = mBytesRemaining / mFrameSize;
2462
Simon Wilson2d590962012-11-29 15:18:50 -08002463 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002464 // update the setpoint when AudioFlinger::mScreenState changes
2465 uint32_t screenState = AudioFlinger::mScreenState;
2466 if (screenState != mScreenState) {
2467 mScreenState = screenState;
2468 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2469 if (pipe != NULL) {
2470 pipe->setAvgFrames((mScreenState & 1) ?
2471 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2472 }
2473 }
Andy Hung010a1a12014-03-13 13:57:33 -07002474 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002475 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002476 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002477 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002478 } else {
2479 bytesWritten = framesWritten;
2480 }
Glenn Kastenefaa7ab2014-08-20 08:48:54 -07002481 mLatchDValid = false;
Glenn Kasten767094d2013-08-23 13:51:43 -07002482 status_t status = mNormalSink->getTimestamp(mLatchD.mTimestamp);
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002483 if (status == NO_ERROR) {
2484 size_t totalFramesWritten = mNormalSink->framesWritten();
2485 if (totalFramesWritten >= mLatchD.mTimestamp.mPosition) {
2486 mLatchD.mUnpresentedFrames = totalFramesWritten - mLatchD.mTimestamp.mPosition;
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002487 // mLatchD.mFramesReleased is set immediately before D is clocked into Q
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002488 mLatchDValid = true;
2489 }
2490 }
Eric Laurent81784c32012-11-19 14:55:58 -08002491 // otherwise use the HAL / AudioStreamOut directly
2492 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002493 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002494
Eric Laurentbfb1b832013-01-07 09:53:42 -08002495 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002496 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2497 mWriteAckSequence += 2;
2498 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002499 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002500 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002501 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002502 // FIXME We should have an implementation of timestamps for direct output threads.
2503 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002504 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002505 if (mUseAsyncWrite &&
2506 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2507 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002508 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002509 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002510 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002511 }
Eric Laurent81784c32012-11-19 14:55:58 -08002512 }
2513
Eric Laurent81784c32012-11-19 14:55:58 -08002514 mNumWrites++;
2515 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002516 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002517 return bytesWritten;
2518}
2519
2520void AudioFlinger::PlaybackThread::threadLoop_drain()
2521{
2522 if (mOutput->stream->drain) {
2523 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2524 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002525 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2526 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002527 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002528 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002529 }
2530 mOutput->stream->drain(mOutput->stream,
2531 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
2532 : AUDIO_DRAIN_ALL);
2533 }
2534}
2535
2536void AudioFlinger::PlaybackThread::threadLoop_exit()
2537{
Eric Laurent275e8e92014-11-30 15:14:47 -08002538 {
2539 Mutex::Autolock _l(mLock);
2540 for (size_t i = 0; i < mTracks.size(); i++) {
2541 sp<Track> track = mTracks[i];
2542 track->invalidate();
2543 }
2544 }
Eric Laurent81784c32012-11-19 14:55:58 -08002545}
2546
2547/*
2548The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002549 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002550 - mActiveSleepTimeUs from activeSleepTimeUs()
2551 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08002552 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
2553 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08002554 - maxPeriod from frame count and sample rate (MIXER only)
2555
2556The parameters that affect these derived values are:
2557 - frame count
2558 - frame size
2559 - sample rate
2560 - device type: A2DP or not
2561 - device latency
2562 - format: PCM or not
2563 - active sleep time
2564 - idle sleep time
2565*/
2566
2567void AudioFlinger::PlaybackThread::cacheParameters_l()
2568{
Andy Hung25c2dac2014-02-27 14:56:00 -08002569 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002570 mActiveSleepTimeUs = activeSleepTimeUs();
2571 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08002572
2573 // make sure standby delay is not too short when connected to an A2DP sink to avoid
2574 // truncating audio when going to standby.
2575 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
2576 if ((mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != 0) {
2577 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
2578 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
2579 }
2580 }
Eric Laurent81784c32012-11-19 14:55:58 -08002581}
2582
2583void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2584{
Glenn Kasten7c027242012-12-26 14:43:16 -08002585 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurent81784c32012-11-19 14:55:58 -08002586 this, streamType, mTracks.size());
2587 Mutex::Autolock _l(mLock);
2588
2589 size_t size = mTracks.size();
2590 for (size_t i = 0; i < size; i++) {
2591 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07002592 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002593 t->invalidate();
Eric Laurent81784c32012-11-19 14:55:58 -08002594 }
2595 }
2596}
2597
2598status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2599{
2600 int session = chain->sessionId();
Andy Hung010a1a12014-03-13 13:57:33 -07002601 int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled
2602 ? mEffectBuffer : mSinkBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002603 bool ownsBuffer = false;
2604
2605 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
2606 if (session > 0) {
2607 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002608 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002609 if (mType != DIRECT) {
2610 size_t numSamples = mNormalFrameCount * mChannelCount;
2611 buffer = new int16_t[numSamples];
2612 memset(buffer, 0, numSamples * sizeof(int16_t));
2613 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2614 ownsBuffer = true;
2615 }
2616
2617 // Attach all tracks with same session ID to this chain.
2618 for (size_t i = 0; i < mTracks.size(); ++i) {
2619 sp<Track> track = mTracks[i];
2620 if (session == track->sessionId()) {
2621 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2622 buffer);
2623 track->setMainBuffer(buffer);
2624 chain->incTrackCnt();
2625 }
2626 }
2627
2628 // indicate all active tracks in the chain
2629 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2630 sp<Track> track = mActiveTracks[i].promote();
2631 if (track == 0) {
2632 continue;
2633 }
2634 if (session == track->sessionId()) {
2635 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2636 chain->incActiveTrackCnt();
2637 }
2638 }
2639 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002640 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08002641 chain->setInBuffer(buffer, ownsBuffer);
Andy Hung010a1a12014-03-13 13:57:33 -07002642 chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled
2643 ? mEffectBuffer : mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002644 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
2645 // chains list in order to be processed last as it contains output stage effects
2646 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2647 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
2648 // after track specific effects and before output stage
2649 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
2650 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
2651 // Effect chain for other sessions are inserted at beginning of effect
2652 // chains list to be processed before output mix effects. Relative order between other
2653 // sessions is not important
2654 size_t size = mEffectChains.size();
2655 size_t i = 0;
2656 for (i = 0; i < size; i++) {
2657 if (mEffectChains[i]->sessionId() < session) {
2658 break;
2659 }
2660 }
2661 mEffectChains.insertAt(chain, i);
2662 checkSuspendOnAddEffectChain_l(chain);
2663
2664 return NO_ERROR;
2665}
2666
2667size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2668{
2669 int session = chain->sessionId();
2670
2671 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2672
2673 for (size_t i = 0; i < mEffectChains.size(); i++) {
2674 if (chain == mEffectChains[i]) {
2675 mEffectChains.removeAt(i);
2676 // detach all active tracks from the chain
2677 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2678 sp<Track> track = mActiveTracks[i].promote();
2679 if (track == 0) {
2680 continue;
2681 }
2682 if (session == track->sessionId()) {
2683 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2684 chain.get(), session);
2685 chain->decActiveTrackCnt();
2686 }
2687 }
2688
2689 // detach all tracks with same session ID from this chain
2690 for (size_t i = 0; i < mTracks.size(); ++i) {
2691 sp<Track> track = mTracks[i];
2692 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002693 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002694 chain->decTrackCnt();
2695 }
2696 }
2697 break;
2698 }
2699 }
2700 return mEffectChains.size();
2701}
2702
2703status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2704 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2705{
2706 Mutex::Autolock _l(mLock);
2707 return attachAuxEffect_l(track, EffectId);
2708}
2709
2710status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2711 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2712{
2713 status_t status = NO_ERROR;
2714
2715 if (EffectId == 0) {
2716 track->setAuxBuffer(0, NULL);
2717 } else {
2718 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2719 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2720 if (effect != 0) {
2721 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2722 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2723 } else {
2724 status = INVALID_OPERATION;
2725 }
2726 } else {
2727 status = BAD_VALUE;
2728 }
2729 }
2730 return status;
2731}
2732
2733void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2734{
2735 for (size_t i = 0; i < mTracks.size(); ++i) {
2736 sp<Track> track = mTracks[i];
2737 if (track->auxEffectId() == effectId) {
2738 attachAuxEffect_l(track, 0);
2739 }
2740 }
2741}
2742
2743bool AudioFlinger::PlaybackThread::threadLoop()
2744{
2745 Vector< sp<Track> > tracksToRemove;
2746
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002747 mStandbyTimeNs = systemTime();
Eric Laurent81784c32012-11-19 14:55:58 -08002748
2749 // MIXER
2750 nsecs_t lastWarning = 0;
2751
2752 // DUPLICATING
2753 // FIXME could this be made local to while loop?
2754 writeFrames = 0;
2755
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002756 int lastGeneration = 0;
2757
Eric Laurent81784c32012-11-19 14:55:58 -08002758 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002759 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08002760
2761 if (mType == MIXER) {
2762 sleepTimeShift = 0;
2763 }
2764
2765 CpuStats cpuStats;
2766 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2767
2768 acquireWakeLock();
2769
Glenn Kasten9e58b552013-01-18 15:09:48 -08002770 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2771 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2772 // and then that string will be logged at the next convenient opportunity.
2773 const char *logString = NULL;
2774
Eric Laurent664539d2013-09-23 18:24:31 -07002775 checkSilentMode_l();
2776
Eric Laurent81784c32012-11-19 14:55:58 -08002777 while (!exitPending())
2778 {
2779 cpuStats.sample(myName);
2780
2781 Vector< sp<EffectChain> > effectChains;
2782
Eric Laurent81784c32012-11-19 14:55:58 -08002783 { // scope for mLock
2784
2785 Mutex::Autolock _l(mLock);
2786
Eric Laurent021cf962014-05-13 10:18:14 -07002787 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07002788
Glenn Kasten9e58b552013-01-18 15:09:48 -08002789 if (logString != NULL) {
2790 mNBLogWriter->logTimestamp();
2791 mNBLogWriter->log(logString);
2792 logString = NULL;
2793 }
2794
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002795 // Gather the framesReleased counters for all active tracks,
2796 // and latch them atomically with the timestamp.
2797 // FIXME We're using raw pointers as indices. A unique track ID would be a better index.
2798 mLatchD.mFramesReleased.clear();
2799 size_t size = mActiveTracks.size();
2800 for (size_t i = 0; i < size; i++) {
2801 sp<Track> t = mActiveTracks[i].promote();
2802 if (t != 0) {
2803 mLatchD.mFramesReleased.add(t.get(),
2804 t->mAudioTrackServerProxy->framesReleased());
2805 }
2806 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002807 if (mLatchDValid) {
2808 mLatchQ = mLatchD;
2809 mLatchDValid = false;
2810 mLatchQValid = true;
2811 }
2812
Eric Laurent81784c32012-11-19 14:55:58 -08002813 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002814 if (mSignalPending) {
2815 // A signal was raised while we were unlocked
2816 mSignalPending = false;
2817 } else if (waitingAsyncCallback_l()) {
2818 if (exitPending()) {
2819 break;
2820 }
Marco Nelissen078538c2015-05-12 09:17:57 -07002821 bool released = false;
2822 // The following works around a bug in the offload driver. Ideally we would release
2823 // the wake lock every time, but that causes the last offload buffer(s) to be
2824 // dropped while the device is on battery, so we need to hold a wake lock during
2825 // the drain phase.
2826 if (mBytesRemaining && !(mDrainSequence & 1)) {
2827 releaseWakeLock_l();
2828 released = true;
2829 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002830 mWakeLockUids.clear();
2831 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002832 ALOGV("wait async completion");
2833 mWaitWorkCV.wait(mLock);
2834 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07002835 if (released) {
2836 acquireWakeLock_l();
2837 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002838 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
2839 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002840
2841 continue;
2842 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002843 if ((!mActiveTracks.size() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08002844 isSuspended()) {
2845 // put audio hardware into standby after short delay
2846 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002847
2848 threadLoop_standby();
2849
2850 mStandby = true;
2851 }
2852
2853 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2854 // we're about to wait, flush the binder command buffer
2855 IPCThreadState::self()->flushCommands();
2856
2857 clearOutputTracks();
2858
2859 if (exitPending()) {
2860 break;
2861 }
2862
2863 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002864 mWakeLockUids.clear();
2865 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002866 // wait until we have something to do...
2867 ALOGV("%s going to sleep", myName.string());
2868 mWaitWorkCV.wait(mLock);
2869 ALOGV("%s waking up", myName.string());
2870 acquireWakeLock_l();
2871
2872 mMixerStatus = MIXER_IDLE;
2873 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2874 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002875 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002876 checkSilentMode_l();
2877
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002878 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
2879 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08002880 if (mType == MIXER) {
2881 sleepTimeShift = 0;
2882 }
2883
2884 continue;
2885 }
2886 }
Eric Laurent81784c32012-11-19 14:55:58 -08002887 // mMixerStatusIgnoringFastTracks is also updated internally
2888 mMixerStatus = prepareTracks_l(&tracksToRemove);
2889
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002890 // compare with previously applied list
2891 if (lastGeneration != mActiveTracksGeneration) {
2892 // update wakelock
2893 updateWakeLockUids_l(mWakeLockUids);
2894 lastGeneration = mActiveTracksGeneration;
2895 }
2896
Eric Laurent81784c32012-11-19 14:55:58 -08002897 // prevent any changes in effect chain list and in each effect chain
2898 // during mixing and effect process as the audio buffers could be deleted
2899 // or modified if an effect is created or deleted
2900 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002901 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08002902
Eric Laurentbfb1b832013-01-07 09:53:42 -08002903 if (mBytesRemaining == 0) {
2904 mCurrentWriteLength = 0;
2905 if (mMixerStatus == MIXER_TRACKS_READY) {
2906 // threadLoop_mix() sets mCurrentWriteLength
2907 threadLoop_mix();
2908 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
2909 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002910 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08002911 // must be written to HAL
2912 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002913 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08002914 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002915 }
2916 }
Andy Hung98ef9782014-03-04 14:46:50 -08002917 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002918 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08002919 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
2920 // or mSinkBuffer (if there are no effects).
2921 //
2922 // This is done pre-effects computation; if effects change to
2923 // support higher precision, this needs to move.
2924 //
2925 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002926 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08002927 if (mMixerBufferValid) {
2928 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
2929 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
2930
Andy Hung2ddee192015-12-18 17:34:44 -08002931 // mono blend occurs for mixer threads only (not direct or offloaded)
2932 // and is handled here if we're going directly to the sink.
2933 if (requireMonoBlend() && !mEffectBufferValid) {
2934 mono_blend(
2935 mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount);
2936 }
2937
Andy Hung98ef9782014-03-04 14:46:50 -08002938 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
2939 mNormalFrameCount * mChannelCount);
2940 }
2941
Eric Laurentbfb1b832013-01-07 09:53:42 -08002942 mBytesRemaining = mCurrentWriteLength;
2943 if (isSuspended()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002944 mSleepTimeUs = suspendSleepTimeUs();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002945 // simulate write to HAL when suspended
Andy Hung25c2dac2014-02-27 14:56:00 -08002946 mBytesWritten += mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002947 mBytesRemaining = 0;
2948 }
Eric Laurent81784c32012-11-19 14:55:58 -08002949
Eric Laurentbfb1b832013-01-07 09:53:42 -08002950 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002951 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002952 for (size_t i = 0; i < effectChains.size(); i ++) {
2953 effectChains[i]->process_l();
2954 }
Eric Laurent81784c32012-11-19 14:55:58 -08002955 }
2956 }
Eric Laurent59fe0102013-09-27 18:48:26 -07002957 // Process effect chains for offloaded thread even if no audio
2958 // was read from audio track: process only updates effect state
2959 // and thus does have to be synchronized with audio writes but may have
2960 // to be called while waiting for async write callback
2961 if (mType == OFFLOAD) {
2962 for (size_t i = 0; i < effectChains.size(); i ++) {
2963 effectChains[i]->process_l();
2964 }
2965 }
Eric Laurent81784c32012-11-19 14:55:58 -08002966
Andy Hung98ef9782014-03-04 14:46:50 -08002967 // Only if the Effects buffer is enabled and there is data in the
2968 // Effects buffer (buffer valid), we need to
2969 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002970 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08002971 if (mEffectBufferValid) {
2972 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08002973
2974 if (requireMonoBlend()) {
2975 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount);
2976 }
2977
Andy Hung98ef9782014-03-04 14:46:50 -08002978 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
2979 mNormalFrameCount * mChannelCount);
2980 }
2981
Eric Laurent81784c32012-11-19 14:55:58 -08002982 // enable changes in effect chain
2983 unlockEffectChains(effectChains);
2984
Eric Laurentbfb1b832013-01-07 09:53:42 -08002985 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002986 // mSleepTimeUs == 0 means we must write to audio hardware
2987 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07002988 ssize_t ret = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002989 if (mBytesRemaining) {
Andy Hung08fb1742015-05-31 23:22:10 -07002990 ret = threadLoop_write();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002991 if (ret < 0) {
2992 mBytesRemaining = 0;
2993 } else {
2994 mBytesWritten += ret;
2995 mBytesRemaining -= ret;
2996 }
2997 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
2998 (mMixerStatus == MIXER_DRAIN_ALL)) {
2999 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08003000 }
Andy Hung08fb1742015-05-31 23:22:10 -07003001 if (mType == MIXER && !mStandby) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003002 // write blocked detection
3003 nsecs_t now = systemTime();
3004 nsecs_t delta = now - mLastWriteTime;
Andy Hung08fb1742015-05-31 23:22:10 -07003005 if (delta > maxPeriod) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003006 mNumDelayedWrites++;
3007 if ((now - lastWarning) > kWarningThrottleNs) {
3008 ATRACE_NAME("underrun");
3009 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
3010 ns2ms(delta), mNumDelayedWrites, this);
3011 lastWarning = now;
3012 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003013 }
Andy Hung08fb1742015-05-31 23:22:10 -07003014
3015 if (mThreadThrottle
3016 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
3017 && ret > 0) { // we wrote something
3018 // Limit MixerThread data processing to no more than twice the
3019 // expected processing rate.
3020 //
3021 // This helps prevent underruns with NuPlayer and other applications
3022 // which may set up buffers that are close to the minimum size, or use
3023 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3024 //
3025 // The throttle smooths out sudden large data drains from the device,
3026 // e.g. when it comes out of standby, which often causes problems with
3027 // (1) mixer threads without a fast mixer (which has its own warm-up)
3028 // (2) minimum buffer sized tracks (even if the track is full,
3029 // the app won't fill fast enough to handle the sudden draw).
3030
3031 const int32_t deltaMs = delta / 1000000;
3032 const int32_t throttleMs = mHalfBufferMs - deltaMs;
3033 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
3034 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003035 // notify of throttle start on verbose log
3036 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3037 "mixer(%p) throttle begin:"
3038 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003039 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07003040 mThreadThrottleTimeMs += throttleMs;
3041 } else {
3042 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3043 if (diff > 0) {
3044 // notify of throttle end on debug log
3045 ALOGD("mixer(%p) throttle end: throttle time(%u)", this, diff);
3046 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3047 }
Andy Hung08fb1742015-05-31 23:22:10 -07003048 }
3049 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003050 }
Eric Laurent81784c32012-11-19 14:55:58 -08003051
Eric Laurentbfb1b832013-01-07 09:53:42 -08003052 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003053 ATRACE_BEGIN("sleep");
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003054 usleep(mSleepTimeUs);
Glenn Kastene7754022014-10-31 12:11:26 -07003055 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003056 }
Eric Laurent81784c32012-11-19 14:55:58 -08003057 }
3058
3059 // Finally let go of removed track(s), without the lock held
3060 // since we can't guarantee the destructors won't acquire that
3061 // same lock. This will also mutate and push a new fast mixer state.
3062 threadLoop_removeTracks(tracksToRemove);
3063 tracksToRemove.clear();
3064
3065 // FIXME I don't understand the need for this here;
3066 // it was in the original code but maybe the
3067 // assignment in saveOutputTracks() makes this unnecessary?
3068 clearOutputTracks();
3069
3070 // Effect chains will be actually deleted here if they were removed from
3071 // mEffectChains list during mixing or effects processing
3072 effectChains.clear();
3073
3074 // FIXME Note that the above .clear() is no longer necessary since effectChains
3075 // is now local to this block, but will keep it for now (at least until merge done).
3076 }
3077
Eric Laurentbfb1b832013-01-07 09:53:42 -08003078 threadLoop_exit();
3079
Eric Laurentcf817a22014-08-04 20:36:31 -07003080 if (!mStandby) {
3081 threadLoop_standby();
3082 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003083 }
3084
3085 releaseWakeLock();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003086 mWakeLockUids.clear();
3087 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08003088
3089 ALOGV("Thread %p type %d exiting", this, mType);
3090 return false;
3091}
3092
Eric Laurentbfb1b832013-01-07 09:53:42 -08003093// removeTracks_l() must be called with ThreadBase::mLock held
3094void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3095{
3096 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07003097 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003098 for (size_t i=0 ; i<count ; i++) {
3099 const sp<Track>& track = tracksToRemove.itemAt(i);
3100 mActiveTracks.remove(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003101 mWakeLockUids.remove(track->uid());
3102 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003103 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
3104 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3105 if (chain != 0) {
3106 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
3107 track->sessionId());
3108 chain->decActiveTrackCnt();
3109 }
3110 if (track->isTerminated()) {
3111 removeTrack_l(track);
3112 }
3113 }
3114 }
3115
3116}
Eric Laurent81784c32012-11-19 14:55:58 -08003117
Eric Laurentaccc1472013-09-20 09:36:34 -07003118status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3119{
3120 if (mNormalSink != 0) {
3121 return mNormalSink->getTimestamp(timestamp);
3122 }
Andy Hung9a1c8892014-12-03 11:37:42 -08003123 if ((mType == OFFLOAD || mType == DIRECT)
3124 && mOutput != NULL && mOutput->stream->get_presentation_position) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003125 uint64_t position64;
Phil Burk062e67a2015-02-11 13:40:50 -08003126 int ret = mOutput->getPresentationPosition(&position64, &timestamp.mTime);
Eric Laurentaccc1472013-09-20 09:36:34 -07003127 if (ret == 0) {
3128 timestamp.mPosition = (uint32_t)position64;
3129 return NO_ERROR;
3130 }
3131 }
3132 return INVALID_OPERATION;
3133}
Eric Laurent1c333e22014-05-20 10:48:17 -07003134
Eric Laurent054d9d32015-04-24 08:48:48 -07003135status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
3136 audio_patch_handle_t *handle)
3137{
3138 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3139 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3140 if (mFastMixer != 0) {
3141 FastMixerStateQueue *sq = mFastMixer->sq();
3142 FastMixerState *state = sq->begin();
3143 if (!(state->mCommand & FastMixerState::IDLE)) {
3144 previousCommand = state->mCommand;
3145 state->mCommand = FastMixerState::HOT_IDLE;
3146 sq->end();
3147 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3148 } else {
3149 sq->end(false /*didModify*/);
3150 }
3151 }
3152 status_t status = PlaybackThread::createAudioPatch_l(patch, handle);
3153
3154 if (!(previousCommand & FastMixerState::IDLE)) {
3155 ALOG_ASSERT(mFastMixer != 0);
3156 FastMixerStateQueue *sq = mFastMixer->sq();
3157 FastMixerState *state = sq->begin();
3158 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3159 state->mCommand = previousCommand;
3160 sq->end();
3161 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3162 }
3163
3164 return status;
3165}
3166
Eric Laurent1c333e22014-05-20 10:48:17 -07003167status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3168 audio_patch_handle_t *handle)
3169{
3170 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003171
3172 // store new device and send to effects
3173 audio_devices_t type = AUDIO_DEVICE_NONE;
3174 for (unsigned int i = 0; i < patch->num_sinks; i++) {
3175 type |= patch->sinks[i].ext.device.type;
3176 }
3177
3178#ifdef ADD_BATTERY_DATA
3179 // when changing the audio output device, call addBatteryData to notify
3180 // the change
3181 if (mOutDevice != type) {
3182 uint32_t params = 0;
3183 // check whether speaker is on
3184 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3185 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003186 }
3187
Eric Laurent054d9d32015-04-24 08:48:48 -07003188 audio_devices_t deviceWithoutSpeaker
3189 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3190 // check if any other device (except speaker) is on
3191 if (type & deviceWithoutSpeaker) {
3192 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3193 }
3194
3195 if (params != 0) {
3196 addBatteryData(params);
3197 }
3198 }
3199#endif
3200
3201 for (size_t i = 0; i < mEffectChains.size(); i++) {
3202 mEffectChains[i]->setDevice_l(type);
3203 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003204
3205 // mPrevOutDevice is the latest device set by createAudioPatch_l(). It is not set when
3206 // the thread is created so that the first patch creation triggers an ioConfigChanged callback
3207 bool configChanged = mPrevOutDevice != type;
Eric Laurent054d9d32015-04-24 08:48:48 -07003208 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003209 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003210
3211 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003212 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
3213 status = hwDevice->create_audio_patch(hwDevice,
3214 patch->num_sources,
3215 patch->sources,
3216 patch->num_sinks,
3217 patch->sinks,
3218 handle);
3219 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003220 char *address;
3221 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3222 //FIXME: we only support address on first sink with HAL version < 3.0
3223 address = audio_device_address_to_parameter(
3224 patch->sinks[0].ext.device.type,
3225 patch->sinks[0].ext.device.address);
3226 } else {
3227 address = (char *)calloc(1, 1);
3228 }
3229 AudioParameter param = AudioParameter(String8(address));
3230 free(address);
3231 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), (int)type);
3232 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3233 param.toString().string());
3234 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003235 }
Eric Laurente8726fe2015-06-26 09:39:24 -07003236 if (configChanged) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003237 mPrevOutDevice = type;
Eric Laurente8726fe2015-06-26 09:39:24 -07003238 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
3239 }
Eric Laurent1c333e22014-05-20 10:48:17 -07003240 return status;
3241}
3242
Eric Laurent054d9d32015-04-24 08:48:48 -07003243status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3244{
3245 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3246 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3247 if (mFastMixer != 0) {
3248 FastMixerStateQueue *sq = mFastMixer->sq();
3249 FastMixerState *state = sq->begin();
3250 if (!(state->mCommand & FastMixerState::IDLE)) {
3251 previousCommand = state->mCommand;
3252 state->mCommand = FastMixerState::HOT_IDLE;
3253 sq->end();
3254 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3255 } else {
3256 sq->end(false /*didModify*/);
3257 }
3258 }
3259
3260 status_t status = PlaybackThread::releaseAudioPatch_l(handle);
3261
3262 if (!(previousCommand & FastMixerState::IDLE)) {
3263 ALOG_ASSERT(mFastMixer != 0);
3264 FastMixerStateQueue *sq = mFastMixer->sq();
3265 FastMixerState *state = sq->begin();
3266 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3267 state->mCommand = previousCommand;
3268 sq->end();
3269 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3270 }
3271
3272 return status;
3273}
3274
Eric Laurent1c333e22014-05-20 10:48:17 -07003275status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3276{
3277 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003278
3279 mOutDevice = AUDIO_DEVICE_NONE;
3280
Eric Laurent1c333e22014-05-20 10:48:17 -07003281 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
3282 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
3283 status = hwDevice->release_audio_patch(hwDevice, handle);
3284 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003285 AudioParameter param;
3286 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
3287 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3288 param.toString().string());
Eric Laurent1c333e22014-05-20 10:48:17 -07003289 }
3290 return status;
3291}
3292
Eric Laurent83b88082014-06-20 18:31:16 -07003293void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3294{
3295 Mutex::Autolock _l(mLock);
3296 mTracks.add(track);
3297}
3298
3299void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3300{
3301 Mutex::Autolock _l(mLock);
3302 destroyTrack_l(track);
3303}
3304
3305void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
3306{
3307 ThreadBase::getAudioPortConfig(config);
3308 config->role = AUDIO_PORT_ROLE_SOURCE;
3309 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3310 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
3311}
3312
Eric Laurent81784c32012-11-19 14:55:58 -08003313// ----------------------------------------------------------------------------
3314
3315AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurent72e3f392015-05-20 14:43:50 -07003316 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
3317 : PlaybackThread(audioFlinger, output, id, device, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08003318 // mAudioMixer below
3319 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08003320 mFastMixerFutex(0),
3321 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08003322 // mOutputSink below
3323 // mPipeSink below
3324 // mNormalSink below
3325{
3326 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07003327 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, "
Eric Laurent81784c32012-11-19 14:55:58 -08003328 "mFrameCount=%d, mNormalFrameCount=%d",
3329 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3330 mNormalFrameCount);
3331 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3332
Andy Hungfbfc3952015-01-15 13:33:51 -08003333 if (type == DUPLICATING) {
3334 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3335 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3336 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3337 return;
3338 }
Eric Laurent81784c32012-11-19 14:55:58 -08003339 // create an NBAIO sink for the HAL output stream, and negotiate
3340 mOutputSink = new AudioStreamOutSink(output->stream);
3341 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003342 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Eric Laurent81784c32012-11-19 14:55:58 -08003343 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
3344 ALOG_ASSERT(index == 0);
3345
3346 // initialize fast mixer depending on configuration
3347 bool initFastMixer;
3348 switch (kUseFastMixer) {
3349 case FastMixer_Never:
3350 initFastMixer = false;
3351 break;
3352 case FastMixer_Always:
3353 initFastMixer = true;
3354 break;
3355 case FastMixer_Static:
3356 case FastMixer_Dynamic:
3357 initFastMixer = mFrameCount < mNormalFrameCount;
3358 break;
3359 }
3360 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003361 audio_format_t fastMixerFormat;
3362 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3363 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3364 } else {
3365 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3366 }
3367 if (mFormat != fastMixerFormat) {
3368 // change our Sink format to accept our intermediate precision
3369 mFormat = fastMixerFormat;
3370 free(mSinkBuffer);
3371 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3372 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3373 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3374 }
Eric Laurent81784c32012-11-19 14:55:58 -08003375
3376 // create a MonoPipe to connect our submix to FastMixer
3377 NBAIO_Format format = mOutputSink->format();
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003378 NBAIO_Format origformat = format;
Andy Hung1258c1a2014-05-23 21:22:17 -07003379 // adjust format to match that of the Fast Mixer
Glenn Kasten97b7b752014-09-28 13:04:24 -07003380 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003381 format.mFormat = fastMixerFormat;
3382 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3383
Eric Laurent81784c32012-11-19 14:55:58 -08003384 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3385 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3386 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3387 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3388 const NBAIO_Format offers[1] = {format};
3389 size_t numCounterOffers = 0;
3390 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
3391 ALOG_ASSERT(index == 0);
3392 monoPipe->setAvgFrames((mScreenState & 1) ?
3393 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3394 mPipeSink = monoPipe;
3395
Glenn Kasten46909e72013-02-26 09:20:22 -08003396#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08003397 if (mTeeSinkOutputEnabled) {
3398 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003399 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
3400 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08003401 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003402 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003403 ALOG_ASSERT(index == 0);
3404 mTeeSink = teeSink;
3405 PipeReader *teeSource = new PipeReader(*teeSink);
3406 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003407 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003408 ALOG_ASSERT(index == 0);
3409 mTeeSource = teeSource;
3410 }
Glenn Kasten46909e72013-02-26 09:20:22 -08003411#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003412
3413 // create fast mixer and configure it initially with just one fast track for our submix
3414 mFastMixer = new FastMixer();
3415 FastMixerStateQueue *sq = mFastMixer->sq();
3416#ifdef STATE_QUEUE_DUMP
3417 sq->setObserverDump(&mStateQueueObserverDump);
3418 sq->setMutatorDump(&mStateQueueMutatorDump);
3419#endif
3420 FastMixerState *state = sq->begin();
3421 FastTrack *fastTrack = &state->mFastTracks[0];
3422 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3423 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3424 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003425 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3426 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003427 fastTrack->mGeneration++;
3428 state->mFastTracksGen++;
3429 state->mTrackMask = 1;
3430 // fast mixer will use the HAL output sink
3431 state->mOutputSink = mOutputSink.get();
3432 state->mOutputSinkGen++;
3433 state->mFrameCount = mFrameCount;
3434 state->mCommand = FastMixerState::COLD_IDLE;
3435 // already done in constructor initialization list
3436 //mFastMixerFutex = 0;
3437 state->mColdFutexAddr = &mFastMixerFutex;
3438 state->mColdGen++;
3439 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08003440#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003441 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08003442#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08003443 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3444 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003445 sq->end();
3446 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3447
3448 // start the fast mixer
3449 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3450 pid_t tid = mFastMixer->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003451 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003452
3453#ifdef AUDIO_WATCHDOG
3454 // create and start the watchdog
3455 mAudioWatchdog = new AudioWatchdog();
3456 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3457 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3458 tid = mAudioWatchdog->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003459 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003460#endif
3461
Eric Laurent81784c32012-11-19 14:55:58 -08003462 }
3463
3464 switch (kUseFastMixer) {
3465 case FastMixer_Never:
3466 case FastMixer_Dynamic:
3467 mNormalSink = mOutputSink;
3468 break;
3469 case FastMixer_Always:
3470 mNormalSink = mPipeSink;
3471 break;
3472 case FastMixer_Static:
3473 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3474 break;
3475 }
3476}
3477
3478AudioFlinger::MixerThread::~MixerThread()
3479{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003480 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003481 FastMixerStateQueue *sq = mFastMixer->sq();
3482 FastMixerState *state = sq->begin();
3483 if (state->mCommand == FastMixerState::COLD_IDLE) {
3484 int32_t old = android_atomic_inc(&mFastMixerFutex);
3485 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003486 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003487 }
3488 }
3489 state->mCommand = FastMixerState::EXIT;
3490 sq->end();
3491 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3492 mFastMixer->join();
3493 // Though the fast mixer thread has exited, it's state queue is still valid.
3494 // We'll use that extract the final state which contains one remaining fast track
3495 // corresponding to our sub-mix.
3496 state = sq->begin();
3497 ALOG_ASSERT(state->mTrackMask == 1);
3498 FastTrack *fastTrack = &state->mFastTracks[0];
3499 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3500 delete fastTrack->mBufferProvider;
3501 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003502 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003503#ifdef AUDIO_WATCHDOG
3504 if (mAudioWatchdog != 0) {
3505 mAudioWatchdog->requestExit();
3506 mAudioWatchdog->requestExitAndWait();
3507 mAudioWatchdog.clear();
3508 }
3509#endif
3510 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003511 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003512 delete mAudioMixer;
3513}
3514
3515
3516uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3517{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003518 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003519 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3520 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3521 }
3522 return latency;
3523}
3524
3525
3526void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3527{
3528 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3529}
3530
Eric Laurentbfb1b832013-01-07 09:53:42 -08003531ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003532{
3533 // FIXME we should only do one push per cycle; confirm this is true
3534 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003535 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003536 FastMixerStateQueue *sq = mFastMixer->sq();
3537 FastMixerState *state = sq->begin();
3538 if (state->mCommand != FastMixerState::MIX_WRITE &&
3539 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3540 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07003541
3542 // FIXME workaround for first HAL write being CPU bound on some devices
3543 ATRACE_BEGIN("write");
3544 mOutput->write((char *)mSinkBuffer, 0);
3545 ATRACE_END();
3546
Eric Laurent81784c32012-11-19 14:55:58 -08003547 int32_t old = android_atomic_inc(&mFastMixerFutex);
3548 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003549 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003550 }
3551#ifdef AUDIO_WATCHDOG
3552 if (mAudioWatchdog != 0) {
3553 mAudioWatchdog->resume();
3554 }
3555#endif
3556 }
3557 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08003558#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003559 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08003560 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08003561#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003562 sq->end();
3563 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3564 if (kUseFastMixer == FastMixer_Dynamic) {
3565 mNormalSink = mPipeSink;
3566 }
3567 } else {
3568 sq->end(false /*didModify*/);
3569 }
3570 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003571 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003572}
3573
3574void AudioFlinger::MixerThread::threadLoop_standby()
3575{
3576 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003577 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003578 FastMixerStateQueue *sq = mFastMixer->sq();
3579 FastMixerState *state = sq->begin();
3580 if (!(state->mCommand & FastMixerState::IDLE)) {
3581 state->mCommand = FastMixerState::COLD_IDLE;
3582 state->mColdFutexAddr = &mFastMixerFutex;
3583 state->mColdGen++;
3584 mFastMixerFutex = 0;
3585 sq->end();
3586 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3587 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3588 if (kUseFastMixer == FastMixer_Dynamic) {
3589 mNormalSink = mOutputSink;
3590 }
3591#ifdef AUDIO_WATCHDOG
3592 if (mAudioWatchdog != 0) {
3593 mAudioWatchdog->pause();
3594 }
3595#endif
3596 } else {
3597 sq->end(false /*didModify*/);
3598 }
3599 }
3600 PlaybackThread::threadLoop_standby();
3601}
3602
Eric Laurentbfb1b832013-01-07 09:53:42 -08003603bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3604{
3605 return false;
3606}
3607
3608bool AudioFlinger::PlaybackThread::shouldStandby_l()
3609{
3610 return !mStandby;
3611}
3612
3613bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3614{
3615 Mutex::Autolock _l(mLock);
3616 return waitingAsyncCallback_l();
3617}
3618
Eric Laurent81784c32012-11-19 14:55:58 -08003619// shared by MIXER and DIRECT, overridden by DUPLICATING
3620void AudioFlinger::PlaybackThread::threadLoop_standby()
3621{
3622 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08003623 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003624 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003625 // discard any pending drain or write ack by incrementing sequence
3626 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3627 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003628 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003629 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3630 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003631 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003632 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003633}
3634
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003635void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3636{
3637 ALOGV("signal playback thread");
3638 broadcast_l();
3639}
3640
Eric Laurent81784c32012-11-19 14:55:58 -08003641void AudioFlinger::MixerThread::threadLoop_mix()
3642{
3643 // obtain the presentation timestamp of the next output buffer
3644 int64_t pts;
3645 status_t status = INVALID_OPERATION;
3646
3647 if (mNormalSink != 0) {
3648 status = mNormalSink->getNextWriteTimestamp(&pts);
3649 } else {
3650 status = mOutputSink->getNextWriteTimestamp(&pts);
3651 }
3652
3653 if (status != NO_ERROR) {
3654 pts = AudioBufferProvider::kInvalidPTS;
3655 }
3656
3657 // mix buffers...
3658 mAudioMixer->process(pts);
Andy Hung25c2dac2014-02-27 14:56:00 -08003659 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003660 // increase sleep time progressively when application underrun condition clears.
3661 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3662 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3663 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003664 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003665 sleepTimeShift--;
3666 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003667 mSleepTimeUs = 0;
3668 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08003669 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003670
Eric Laurent81784c32012-11-19 14:55:58 -08003671}
3672
3673void AudioFlinger::MixerThread::threadLoop_sleepTime()
3674{
3675 // If no tracks are ready, sleep once for the duration of an output
3676 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003677 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003678 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003679 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
3680 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
3681 mSleepTimeUs = kMinThreadSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003682 }
3683 // reduce sleep time in case of consecutive application underruns to avoid
3684 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3685 // duration we would end up writing less data than needed by the audio HAL if
3686 // the condition persists.
3687 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3688 sleepTimeShift++;
3689 }
3690 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003691 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003692 }
3693 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003694 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3695 // before effects processing or output.
3696 if (mMixerBufferValid) {
3697 memset(mMixerBuffer, 0, mMixerBufferSize);
3698 } else {
3699 memset(mSinkBuffer, 0, mSinkBufferSize);
3700 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003701 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003702 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3703 "anticipated start");
3704 }
3705 // TODO add standby time extension fct of effect tail
3706}
3707
3708// prepareTracks_l() must be called with ThreadBase::mLock held
3709AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3710 Vector< sp<Track> > *tracksToRemove)
3711{
3712
3713 mixer_state mixerStatus = MIXER_IDLE;
3714 // find out which tracks need to be processed
3715 size_t count = mActiveTracks.size();
3716 size_t mixedTracks = 0;
3717 size_t tracksWithEffect = 0;
3718 // counts only _active_ fast tracks
3719 size_t fastTracks = 0;
3720 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
3721
3722 float masterVolume = mMasterVolume;
3723 bool masterMute = mMasterMute;
3724
3725 if (masterMute) {
3726 masterVolume = 0;
3727 }
3728 // Delegate master volume control to effect in output mix effect chain if needed
3729 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3730 if (chain != 0) {
3731 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
3732 chain->setVolume_l(&v, &v);
3733 masterVolume = (float)((v + (1 << 23)) >> 24);
3734 chain.clear();
3735 }
3736
3737 // prepare a new state to push
3738 FastMixerStateQueue *sq = NULL;
3739 FastMixerState *state = NULL;
3740 bool didModify = false;
3741 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003742 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003743 sq = mFastMixer->sq();
3744 state = sq->begin();
3745 }
3746
Andy Hung69aed5f2014-02-25 17:24:40 -08003747 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08003748 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08003749
Eric Laurent81784c32012-11-19 14:55:58 -08003750 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003751 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003752 if (t == 0) {
3753 continue;
3754 }
3755
3756 // this const just means the local variable doesn't change
3757 Track* const track = t.get();
3758
3759 // process fast tracks
3760 if (track->isFastTrack()) {
3761
3762 // It's theoretically possible (though unlikely) for a fast track to be created
3763 // and then removed within the same normal mix cycle. This is not a problem, as
3764 // the track never becomes active so it's fast mixer slot is never touched.
3765 // The converse, of removing an (active) track and then creating a new track
3766 // at the identical fast mixer slot within the same normal mix cycle,
3767 // is impossible because the slot isn't marked available until the end of each cycle.
3768 int j = track->mFastIndex;
3769 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
3770 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
3771 FastTrack *fastTrack = &state->mFastTracks[j];
3772
3773 // Determine whether the track is currently in underrun condition,
3774 // and whether it had a recent underrun.
3775 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
3776 FastTrackUnderruns underruns = ftDump->mUnderruns;
3777 uint32_t recentFull = (underruns.mBitFields.mFull -
3778 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
3779 uint32_t recentPartial = (underruns.mBitFields.mPartial -
3780 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
3781 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
3782 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
3783 uint32_t recentUnderruns = recentPartial + recentEmpty;
3784 track->mObservedUnderruns = underruns;
3785 // don't count underruns that occur while stopping or pausing
3786 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07003787 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
3788 recentUnderruns > 0) {
3789 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
3790 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003791 }
3792
3793 // This is similar to the state machine for normal tracks,
3794 // with a few modifications for fast tracks.
3795 bool isActive = true;
3796 switch (track->mState) {
3797 case TrackBase::STOPPING_1:
3798 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08003799 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003800 track->mState = TrackBase::STOPPING_2;
3801 }
3802 break;
3803 case TrackBase::PAUSING:
3804 // ramp down is not yet implemented
3805 track->setPaused();
3806 break;
3807 case TrackBase::RESUMING:
3808 // ramp up is not yet implemented
3809 track->mState = TrackBase::ACTIVE;
3810 break;
3811 case TrackBase::ACTIVE:
3812 if (recentFull > 0 || recentPartial > 0) {
3813 // track has provided at least some frames recently: reset retry count
3814 track->mRetryCount = kMaxTrackRetries;
3815 }
3816 if (recentUnderruns == 0) {
3817 // no recent underruns: stay active
3818 break;
3819 }
3820 // there has recently been an underrun of some kind
3821 if (track->sharedBuffer() == 0) {
3822 // were any of the recent underruns "empty" (no frames available)?
3823 if (recentEmpty == 0) {
3824 // no, then ignore the partial underruns as they are allowed indefinitely
3825 break;
3826 }
3827 // there has recently been an "empty" underrun: decrement the retry counter
3828 if (--(track->mRetryCount) > 0) {
3829 break;
3830 }
3831 // indicate to client process that the track was disabled because of underrun;
3832 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003833 android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003834 // remove from active list, but state remains ACTIVE [confusing but true]
3835 isActive = false;
3836 break;
3837 }
3838 // fall through
3839 case TrackBase::STOPPING_2:
3840 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003841 case TrackBase::STOPPED:
3842 case TrackBase::FLUSHED: // flush() while active
3843 // Check for presentation complete if track is inactive
3844 // We have consumed all the buffers of this track.
3845 // This would be incomplete if we auto-paused on underrun
3846 {
3847 size_t audioHALFrames =
3848 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3849 size_t framesWritten = mBytesWritten / mFrameSize;
3850 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
3851 // track stays in active list until presentation is complete
3852 break;
3853 }
3854 }
3855 if (track->isStopping_2()) {
3856 track->mState = TrackBase::STOPPED;
3857 }
3858 if (track->isStopped()) {
3859 // Can't reset directly, as fast mixer is still polling this track
3860 // track->reset();
3861 // So instead mark this track as needing to be reset after push with ack
3862 resetMask |= 1 << i;
3863 }
3864 isActive = false;
3865 break;
3866 case TrackBase::IDLE:
3867 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08003868 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08003869 }
3870
3871 if (isActive) {
3872 // was it previously inactive?
3873 if (!(state->mTrackMask & (1 << j))) {
3874 ExtendedAudioBufferProvider *eabp = track;
3875 VolumeProvider *vp = track;
3876 fastTrack->mBufferProvider = eabp;
3877 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08003878 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003879 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08003880 fastTrack->mGeneration++;
3881 state->mTrackMask |= 1 << j;
3882 didModify = true;
3883 // no acknowledgement required for newly active tracks
3884 }
3885 // cache the combined master volume and stream type volume for fast mixer; this
3886 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08003887 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08003888 ++fastTracks;
3889 } else {
3890 // was it previously active?
3891 if (state->mTrackMask & (1 << j)) {
3892 fastTrack->mBufferProvider = NULL;
3893 fastTrack->mGeneration++;
3894 state->mTrackMask &= ~(1 << j);
3895 didModify = true;
3896 // If any fast tracks were removed, we must wait for acknowledgement
3897 // because we're about to decrement the last sp<> on those tracks.
3898 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3899 } else {
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08003900 LOG_ALWAYS_FATAL("fast track %d should have been active; "
3901 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
3902 j, track->mState, state->mTrackMask, recentUnderruns,
3903 track->sharedBuffer() != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08003904 }
3905 tracksToRemove->add(track);
3906 // Avoids a misleading display in dumpsys
3907 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
3908 }
3909 continue;
3910 }
3911
3912 { // local variable scope to avoid goto warning
3913
3914 audio_track_cblk_t* cblk = track->cblk();
3915
3916 // The first time a track is added we wait
3917 // for all its buffers to be filled before processing it
3918 int name = track->name();
3919 // make sure that we have enough frames to mix one full buffer.
3920 // enforce this condition only once to enable draining the buffer in case the client
3921 // app does not call stop() and relies on underrun to stop:
3922 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
3923 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003924 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07003925 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07003926 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07003927
3928 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07003929 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07003930 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
3931 // add frames already consumed but not yet released by the resampler
3932 // because mAudioTrackServerProxy->framesReady() will include these frames
3933 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
3934
Eric Laurent81784c32012-11-19 14:55:58 -08003935 uint32_t minFrames = 1;
3936 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
3937 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003938 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08003939 }
Eric Laurent13e4c962013-12-20 17:36:01 -08003940
3941 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07003942 if (ATRACE_ENABLED()) {
3943 // I wish we had formatted trace names
3944 char traceName[16];
3945 strcpy(traceName, "nRdy");
3946 int name = track->name();
3947 if (AudioMixer::TRACK0 <= name &&
3948 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
3949 name -= AudioMixer::TRACK0;
3950 traceName[4] = (name / 10) + '0';
3951 traceName[5] = (name % 10) + '0';
3952 } else {
3953 traceName[4] = '?';
3954 traceName[5] = '?';
3955 }
3956 traceName[6] = '\0';
3957 ATRACE_INT(traceName, framesReady);
3958 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003959 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08003960 !track->isPaused() && !track->isTerminated())
3961 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003962 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003963
3964 mixedTracks++;
3965
Andy Hung69aed5f2014-02-25 17:24:40 -08003966 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
3967 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08003968 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08003969 if (track->mainBuffer() != mSinkBuffer &&
3970 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08003971 if (mEffectBufferEnabled) {
3972 mEffectBufferValid = true; // Later can set directly.
3973 }
Eric Laurent81784c32012-11-19 14:55:58 -08003974 chain = getEffectChain_l(track->sessionId());
3975 // Delegate volume control to effect in track effect chain if needed
3976 if (chain != 0) {
3977 tracksWithEffect++;
3978 } else {
3979 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
3980 "session %d",
3981 name, track->sessionId());
3982 }
3983 }
3984
3985
3986 int param = AudioMixer::VOLUME;
3987 if (track->mFillingUpStatus == Track::FS_FILLED) {
3988 // no ramp for the first volume setting
3989 track->mFillingUpStatus = Track::FS_ACTIVE;
3990 if (track->mState == TrackBase::RESUMING) {
3991 track->mState = TrackBase::ACTIVE;
3992 param = AudioMixer::RAMP_VOLUME;
3993 }
3994 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003995 // FIXME should not make a decision based on mServer
3996 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003997 // If the track is stopped before the first frame was mixed,
3998 // do not apply ramp
3999 param = AudioMixer::RAMP_VOLUME;
4000 }
4001
4002 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07004003 uint32_t vl, vr; // in U8.24 integer format
4004 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08004005 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07004006 vl = vr = 0;
4007 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08004008 if (track->isPausing()) {
4009 track->setPaused();
4010 }
4011 } else {
4012
4013 // read original volumes with volume control
4014 float typeVolume = mStreamTypes[track->streamType()].volume;
4015 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004016 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004017 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07004018 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
4019 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08004020 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07004021 if (vlf > GAIN_FLOAT_UNITY) {
4022 ALOGV("Track left volume out of range: %.3g", vlf);
4023 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004024 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07004025 if (vrf > GAIN_FLOAT_UNITY) {
4026 ALOGV("Track right volume out of range: %.3g", vrf);
4027 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004028 }
4029 // now apply the master volume and stream type volume
Andy Hung6be49402014-05-30 10:42:03 -07004030 vlf *= v;
4031 vrf *= v;
Eric Laurent81784c32012-11-19 14:55:58 -08004032 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07004033 // then derive vl and vr as U8.24 versions for the effect chain
4034 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
4035 vl = (uint32_t) (scaleto8_24 * vlf);
4036 vr = (uint32_t) (scaleto8_24 * vrf);
4037 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08004038 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08004039 // send level comes from shared memory and so may be corrupt
4040 if (sendLevel > MAX_GAIN_INT) {
4041 ALOGV("Track send level out of range: %04X", sendLevel);
4042 sendLevel = MAX_GAIN_INT;
4043 }
Andy Hung6be49402014-05-30 10:42:03 -07004044 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
4045 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08004046 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004047
Eric Laurent81784c32012-11-19 14:55:58 -08004048 // Delegate volume control to effect in track effect chain if needed
4049 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
4050 // Do not ramp volume if volume is controlled by effect
4051 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08004052 // Update remaining floating point volume levels
4053 vlf = (float)vl / (1 << 24);
4054 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08004055 track->mHasVolumeController = true;
4056 } else {
4057 // force no volume ramp when volume controller was just disabled or removed
4058 // from effect chain to avoid volume spike
4059 if (track->mHasVolumeController) {
4060 param = AudioMixer::VOLUME;
4061 }
4062 track->mHasVolumeController = false;
4063 }
4064
Eric Laurent81784c32012-11-19 14:55:58 -08004065 // XXX: these things DON'T need to be done each time
4066 mAudioMixer->setBufferProvider(name, track);
4067 mAudioMixer->enable(name);
4068
Andy Hung6be49402014-05-30 10:42:03 -07004069 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
4070 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
4071 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08004072 mAudioMixer->setParameter(
4073 name,
4074 AudioMixer::TRACK,
4075 AudioMixer::FORMAT, (void *)track->format());
4076 mAudioMixer->setParameter(
4077 name,
4078 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004079 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07004080 mAudioMixer->setParameter(
4081 name,
4082 AudioMixer::TRACK,
4083 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08004084 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07004085 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004086 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08004087 if (reqSampleRate == 0) {
4088 reqSampleRate = mSampleRate;
4089 } else if (reqSampleRate > maxSampleRate) {
4090 reqSampleRate = maxSampleRate;
4091 }
Eric Laurent81784c32012-11-19 14:55:58 -08004092 mAudioMixer->setParameter(
4093 name,
4094 AudioMixer::RESAMPLE,
4095 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004096 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004097
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004098 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004099 mAudioMixer->setParameter(
4100 name,
4101 AudioMixer::TIMESTRETCH,
4102 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004103 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004104
Andy Hung69aed5f2014-02-25 17:24:40 -08004105 /*
4106 * Select the appropriate output buffer for the track.
4107 *
Andy Hung98ef9782014-03-04 14:46:50 -08004108 * Tracks with effects go into their own effects chain buffer
4109 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08004110 *
4111 * Other tracks can use mMixerBuffer for higher precision
4112 * channel accumulation. If this buffer is enabled
4113 * (mMixerBufferEnabled true), then selected tracks will accumulate
4114 * into it.
4115 *
4116 */
4117 if (mMixerBufferEnabled
4118 && (track->mainBuffer() == mSinkBuffer
4119 || track->mainBuffer() == mMixerBuffer)) {
4120 mAudioMixer->setParameter(
4121 name,
4122 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004123 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08004124 mAudioMixer->setParameter(
4125 name,
4126 AudioMixer::TRACK,
4127 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
4128 // TODO: override track->mainBuffer()?
4129 mMixerBufferValid = true;
4130 } else {
4131 mAudioMixer->setParameter(
4132 name,
4133 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004134 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08004135 mAudioMixer->setParameter(
4136 name,
4137 AudioMixer::TRACK,
4138 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
4139 }
Eric Laurent81784c32012-11-19 14:55:58 -08004140 mAudioMixer->setParameter(
4141 name,
4142 AudioMixer::TRACK,
4143 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
4144
4145 // reset retry count
4146 track->mRetryCount = kMaxTrackRetries;
4147
4148 // If one track is ready, set the mixer ready if:
4149 // - the mixer was not ready during previous round OR
4150 // - no other track is not ready
4151 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
4152 mixerStatus != MIXER_TRACKS_ENABLED) {
4153 mixerStatus = MIXER_TRACKS_READY;
4154 }
4155 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004156 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hung08fb1742015-05-31 23:22:10 -07004157 ALOGV("track(%p) underrun, framesReady(%zu) < framesDesired(%zd)",
4158 track, framesReady, desiredFrames);
Glenn Kasten82aaf942013-07-17 16:05:07 -07004159 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004160 }
Eric Laurent81784c32012-11-19 14:55:58 -08004161 // clear effect chain input buffer if an active track underruns to avoid sending
4162 // previous audio buffer again to effects
4163 chain = getEffectChain_l(track->sessionId());
4164 if (chain != 0) {
4165 chain->clearInputBuffer();
4166 }
4167
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004168 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004169 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
4170 track->isStopped() || track->isPaused()) {
4171 // We have consumed all the buffers of this track.
4172 // Remove it from the list of active tracks.
4173 // TODO: use actual buffer filling status instead of latency when available from
4174 // audio HAL
4175 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
4176 size_t framesWritten = mBytesWritten / mFrameSize;
4177 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
4178 if (track->isStopped()) {
4179 track->reset();
4180 }
4181 tracksToRemove->add(track);
4182 }
4183 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08004184 // No buffers for this track. Give it a few chances to
4185 // fill a buffer, then remove it from active list.
4186 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004187 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004188 tracksToRemove->add(track);
4189 // indicate to client process that the track was disabled because of underrun;
4190 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07004191 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08004192 // If one track is not ready, mark the mixer also not ready if:
4193 // - the mixer was ready during previous round OR
4194 // - no other track is ready
4195 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
4196 mixerStatus != MIXER_TRACKS_READY) {
4197 mixerStatus = MIXER_TRACKS_ENABLED;
4198 }
4199 }
4200 mAudioMixer->disable(name);
4201 }
4202
4203 } // local variable scope to avoid goto warning
4204track_is_ready: ;
4205
4206 }
4207
4208 // Push the new FastMixer state if necessary
4209 bool pauseAudioWatchdog = false;
4210 if (didModify) {
4211 state->mFastTracksGen++;
4212 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4213 if (kUseFastMixer == FastMixer_Dynamic &&
4214 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4215 state->mCommand = FastMixerState::COLD_IDLE;
4216 state->mColdFutexAddr = &mFastMixerFutex;
4217 state->mColdGen++;
4218 mFastMixerFutex = 0;
4219 if (kUseFastMixer == FastMixer_Dynamic) {
4220 mNormalSink = mOutputSink;
4221 }
4222 // If we go into cold idle, need to wait for acknowledgement
4223 // so that fast mixer stops doing I/O.
4224 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4225 pauseAudioWatchdog = true;
4226 }
Eric Laurent81784c32012-11-19 14:55:58 -08004227 }
4228 if (sq != NULL) {
4229 sq->end(didModify);
4230 sq->push(block);
4231 }
4232#ifdef AUDIO_WATCHDOG
4233 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4234 mAudioWatchdog->pause();
4235 }
4236#endif
4237
4238 // Now perform the deferred reset on fast tracks that have stopped
4239 while (resetMask != 0) {
4240 size_t i = __builtin_ctz(resetMask);
4241 ALOG_ASSERT(i < count);
4242 resetMask &= ~(1 << i);
4243 sp<Track> t = mActiveTracks[i].promote();
4244 if (t == 0) {
4245 continue;
4246 }
4247 Track* track = t.get();
4248 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
4249 track->reset();
4250 }
4251
4252 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004253 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004254
Eric Laurent97d547d2014-09-02 14:45:53 -07004255 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
4256 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07004257 }
4258
4259 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07004260 // as long as there are effects we should clear the effects buffer, to avoid
4261 // passing a non-clean buffer to the effect chain
4262 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07004263 }
Andy Hung69aed5f2014-02-25 17:24:40 -08004264 // sink or mix buffer must be cleared if all tracks are connected to an
4265 // effect chain as in this case the mixer will not write to the sink or mix buffer
4266 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08004267 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4268 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08004269 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08004270 if (mMixerBufferValid) {
4271 memset(mMixerBuffer, 0, mMixerBufferSize);
4272 // TODO: In testing, mSinkBuffer below need not be cleared because
4273 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
4274 // after mixing.
4275 //
4276 // To enforce this guarantee:
4277 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4278 // (mixedTracks == 0 && fastTracks > 0))
4279 // must imply MIXER_TRACKS_READY.
4280 // Later, we may clear buffers regardless, and skip much of this logic.
4281 }
Andy Hung98ef9782014-03-04 14:46:50 -08004282 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07004283 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004284 }
4285
4286 // if any fast tracks, then status is ready
4287 mMixerStatusIgnoringFastTracks = mixerStatus;
4288 if (fastTracks > 0) {
4289 mixerStatus = MIXER_TRACKS_READY;
4290 }
4291 return mixerStatus;
4292}
4293
4294// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07004295int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
4296 audio_format_t format, int sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08004297{
Andy Hunge8a1ced2014-05-09 15:02:21 -07004298 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08004299}
4300
4301// deleteTrackName_l() must be called with ThreadBase::mLock held
4302void AudioFlinger::MixerThread::deleteTrackName_l(int name)
4303{
4304 ALOGV("remove track (%d) and delete from mixer", name);
4305 mAudioMixer->deleteTrackName(name);
4306}
4307
Eric Laurent10351942014-05-08 18:49:52 -07004308// checkForNewParameter_l() must be called with ThreadBase::mLock held
4309bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
4310 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004311{
Eric Laurent81784c32012-11-19 14:55:58 -08004312 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08004313 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004314
Eric Laurent10351942014-05-08 18:49:52 -07004315 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004316
Eric Laurent10351942014-05-08 18:49:52 -07004317 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
4318 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004319 if (mFastMixer != 0) {
Eric Laurent10351942014-05-08 18:49:52 -07004320 FastMixerStateQueue *sq = mFastMixer->sq();
4321 FastMixerState *state = sq->begin();
4322 if (!(state->mCommand & FastMixerState::IDLE)) {
4323 previousCommand = state->mCommand;
4324 state->mCommand = FastMixerState::HOT_IDLE;
4325 sq->end();
4326 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
4327 } else {
4328 sq->end(false /*didModify*/);
Eric Laurent81784c32012-11-19 14:55:58 -08004329 }
Eric Laurent10351942014-05-08 18:49:52 -07004330 }
Eric Laurent81784c32012-11-19 14:55:58 -08004331
Eric Laurent10351942014-05-08 18:49:52 -07004332 AudioParameter param = AudioParameter(keyValuePair);
4333 int value;
4334 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4335 reconfig = true;
4336 }
4337 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004338 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004339 status = BAD_VALUE;
4340 } else {
4341 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08004342 reconfig = true;
4343 }
Eric Laurent10351942014-05-08 18:49:52 -07004344 }
4345 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004346 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004347 status = BAD_VALUE;
4348 } else {
4349 // no need to save value, since it's constant
4350 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004351 }
Eric Laurent10351942014-05-08 18:49:52 -07004352 }
4353 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4354 // do not accept frame count changes if tracks are open as the track buffer
4355 // size depends on frame count and correct behavior would not be guaranteed
4356 // if frame count is changed after track creation
4357 if (!mTracks.isEmpty()) {
4358 status = INVALID_OPERATION;
4359 } else {
4360 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004361 }
Eric Laurent10351942014-05-08 18:49:52 -07004362 }
4363 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004364#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07004365 // when changing the audio output device, call addBatteryData to notify
4366 // the change
4367 if (mOutDevice != value) {
4368 uint32_t params = 0;
4369 // check whether speaker is on
4370 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
4371 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08004372 }
Eric Laurent10351942014-05-08 18:49:52 -07004373
4374 audio_devices_t deviceWithoutSpeaker
4375 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
4376 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07004377 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07004378 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4379 }
4380
4381 if (params != 0) {
4382 addBatteryData(params);
4383 }
4384 }
Eric Laurent81784c32012-11-19 14:55:58 -08004385#endif
4386
Eric Laurent10351942014-05-08 18:49:52 -07004387 // forward device change to effects that have requested to be
4388 // aware of attached audio device.
4389 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08004390 a2dpDeviceChanged =
4391 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07004392 mOutDevice = value;
4393 for (size_t i = 0; i < mEffectChains.size(); i++) {
4394 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08004395 }
4396 }
Eric Laurent10351942014-05-08 18:49:52 -07004397 }
Eric Laurent81784c32012-11-19 14:55:58 -08004398
Eric Laurent10351942014-05-08 18:49:52 -07004399 if (status == NO_ERROR) {
4400 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4401 keyValuePair.string());
4402 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004403 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004404 mStandby = true;
4405 mBytesWritten = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004406 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Eric Laurent10351942014-05-08 18:49:52 -07004407 keyValuePair.string());
Eric Laurent81784c32012-11-19 14:55:58 -08004408 }
Eric Laurent10351942014-05-08 18:49:52 -07004409 if (status == NO_ERROR && reconfig) {
4410 readOutputParameters_l();
4411 delete mAudioMixer;
4412 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4413 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07004414 int name = getTrackName_l(mTracks[i]->mChannelMask,
4415 mTracks[i]->mFormat, mTracks[i]->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07004416 if (name < 0) {
4417 break;
4418 }
4419 mTracks[i]->mName = name;
4420 }
Eric Laurent73e26b62015-04-27 16:55:58 -07004421 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004422 }
Eric Laurent81784c32012-11-19 14:55:58 -08004423 }
4424
4425 if (!(previousCommand & FastMixerState::IDLE)) {
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004426 ALOG_ASSERT(mFastMixer != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08004427 FastMixerStateQueue *sq = mFastMixer->sq();
4428 FastMixerState *state = sq->begin();
4429 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
4430 state->mCommand = previousCommand;
4431 sq->end();
4432 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4433 }
4434
Eric Laurent42537be2016-01-08 17:16:42 -08004435 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08004436}
4437
4438
4439void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
4440{
4441 const size_t SIZE = 256;
4442 char buffer[SIZE];
4443 String8 result;
4444
4445 PlaybackThread::dumpInternals(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07004446 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Elliott Hughes87cebad2014-05-22 10:14:43 -07004447 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Andy Hung2ddee192015-12-18 17:34:44 -08004448 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Eric Laurent81784c32012-11-19 14:55:58 -08004449
4450 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten2f90c512015-12-02 11:40:09 -08004451 // while we are dumping it. It may be inconsistent, but it won't mutate!
4452 // This is a large object so we place it on the heap.
4453 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
4454 const FastMixerDumpState *copy = new FastMixerDumpState(mFastMixerDumpState);
4455 copy->dump(fd);
4456 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08004457
4458#ifdef STATE_QUEUE_DUMP
4459 // Similar for state queue
4460 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4461 observerCopy.dump(fd);
4462 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4463 mutatorCopy.dump(fd);
4464#endif
4465
Glenn Kasten46909e72013-02-26 09:20:22 -08004466#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08004467 // Write the tee output to a .wav file
4468 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08004469#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004470
4471#ifdef AUDIO_WATCHDOG
4472 if (mAudioWatchdog != 0) {
4473 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4474 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4475 wdCopy.dump(fd);
4476 }
4477#endif
4478}
4479
4480uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4481{
4482 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4483}
4484
4485uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4486{
4487 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4488}
4489
4490void AudioFlinger::MixerThread::cacheParameters_l()
4491{
4492 PlaybackThread::cacheParameters_l();
4493
4494 // FIXME: Relaxed timing because of a certain device that can't meet latency
4495 // Should be reduced to 2x after the vendor fixes the driver issue
4496 // increase threshold again due to low power audio mode. The way this warning
4497 // threshold is calculated and its usefulness should be reconsidered anyway.
4498 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4499}
4500
4501// ----------------------------------------------------------------------------
4502
4503AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07004504 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device, bool systemReady)
4505 : PlaybackThread(audioFlinger, output, id, device, DIRECT, systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08004506 // mLeftVolFloat, mRightVolFloat
4507{
4508}
4509
Eric Laurentbfb1b832013-01-07 09:53:42 -08004510AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4511 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07004512 ThreadBase::type_t type, bool systemReady)
4513 : PlaybackThread(audioFlinger, output, id, device, type, systemReady)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004514 // mLeftVolFloat, mRightVolFloat
4515{
4516}
4517
Eric Laurent81784c32012-11-19 14:55:58 -08004518AudioFlinger::DirectOutputThread::~DirectOutputThread()
4519{
4520}
4521
Eric Laurentbfb1b832013-01-07 09:53:42 -08004522void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
4523{
4524 audio_track_cblk_t* cblk = track->cblk();
4525 float left, right;
4526
4527 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4528 left = right = 0;
4529 } else {
4530 float typeVolume = mStreamTypes[track->streamType()].volume;
4531 float v = mMasterVolume * typeVolume;
4532 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004533 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4534 left = float_from_gain(gain_minifloat_unpack_left(vlr));
4535 if (left > GAIN_FLOAT_UNITY) {
4536 left = GAIN_FLOAT_UNITY;
4537 }
4538 left *= v;
4539 right = float_from_gain(gain_minifloat_unpack_right(vlr));
4540 if (right > GAIN_FLOAT_UNITY) {
4541 right = GAIN_FLOAT_UNITY;
4542 }
4543 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004544 }
4545
4546 if (lastTrack) {
4547 if (left != mLeftVolFloat || right != mRightVolFloat) {
4548 mLeftVolFloat = left;
4549 mRightVolFloat = right;
4550
4551 // Convert volumes from float to 8.24
4552 uint32_t vl = (uint32_t)(left * (1 << 24));
4553 uint32_t vr = (uint32_t)(right * (1 << 24));
4554
4555 // Delegate volume control to effect in track effect chain if needed
4556 // only one effect chain can be present on DirectOutputThread, so if
4557 // there is one, the track is connected to it
4558 if (!mEffectChains.isEmpty()) {
4559 mEffectChains[0]->setVolume_l(&vl, &vr);
4560 left = (float)vl / (1 << 24);
4561 right = (float)vr / (1 << 24);
4562 }
4563 if (mOutput->stream->set_volume) {
4564 mOutput->stream->set_volume(mOutput->stream, left, right);
4565 }
4566 }
4567 }
4568}
4569
Phil Burk43b4dcc2015-06-09 16:53:44 -07004570void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
4571{
4572 sp<Track> previousTrack = mPreviousTrack.promote();
4573 sp<Track> latestTrack = mLatestActiveTrack.promote();
4574
Eric Laurent0f0631e2015-07-06 18:01:25 -07004575 if (previousTrack != 0 && latestTrack != 0) {
4576 if (mType == DIRECT) {
4577 if (previousTrack.get() != latestTrack.get()) {
4578 mFlushPending = true;
4579 }
4580 } else /* mType == OFFLOAD */ {
4581 if (previousTrack->sessionId() != latestTrack->sessionId()) {
4582 mFlushPending = true;
4583 }
4584 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004585 }
4586 PlaybackThread::onAddNewTrack_l();
4587}
Eric Laurentbfb1b832013-01-07 09:53:42 -08004588
Eric Laurent81784c32012-11-19 14:55:58 -08004589AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4590 Vector< sp<Track> > *tracksToRemove
4591)
4592{
Eric Laurentd595b7c2013-04-03 17:27:56 -07004593 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08004594 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004595 bool doHwPause = false;
4596 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004597
4598 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07004599 for (size_t i = 0; i < count; i++) {
4600 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08004601 // The track died recently
4602 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004603 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08004604 }
4605
Phil Burk43b4dcc2015-06-09 16:53:44 -07004606 if (t->isInvalid()) {
4607 ALOGW("An invalidated track shouldn't be in active list");
4608 tracksToRemove->add(t);
4609 continue;
4610 }
4611
Eric Laurent81784c32012-11-19 14:55:58 -08004612 Track* const track = t.get();
4613 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07004614 // Only consider last track started for volume and mixer state control.
4615 // In theory an older track could underrun and restart after the new one starts
4616 // but as we only care about the transition phase between two tracks on a
4617 // direct output, it is not a problem to ignore the underrun case.
4618 sp<Track> l = mLatestActiveTrack.promote();
4619 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08004620
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004621 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004622 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004623 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004624 doHwPause = true;
4625 mHwPaused = true;
4626 }
4627 tracksToRemove->add(track);
4628 } else if (track->isFlushPending()) {
4629 track->flushAck();
4630 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004631 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004632 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004633 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004634 track->resumeAck();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004635 if (last && mHwPaused) {
4636 doHwResume = true;
4637 mHwPaused = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004638 }
4639 }
4640
Eric Laurent81784c32012-11-19 14:55:58 -08004641 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08004642 // for all its buffers to be filled before processing it.
4643 // Allow draining the buffer in case the client
4644 // app does not call stop() and relies on underrun to stop:
4645 // hence the test on (track->mRetryCount > 1).
4646 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07004647 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08004648 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08004649 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkca5e6142015-07-14 09:42:29 -07004650 && (track->mRetryCount > 1) && audio_is_linear_pcm(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004651 minFrames = mNormalFrameCount;
4652 } else {
4653 minFrames = 1;
4654 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004655
Eric Laurentab5cdba2014-06-09 17:22:27 -07004656 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4657 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08004658 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004659 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08004660
4661 if (track->mFillingUpStatus == Track::FS_FILLED) {
4662 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004663 // make sure processVolume_l() will apply new volume even if 0
4664 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004665 if (!mHwSupportsPause) {
4666 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08004667 }
4668 }
4669
4670 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004671 processVolume_l(track, last);
4672 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004673 sp<Track> previousTrack = mPreviousTrack.promote();
4674 if (previousTrack != 0) {
4675 if (track != previousTrack.get()) {
4676 // Flush any data still being written from last track
4677 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07004678 // Invalidate previous track to force a seek when resuming.
4679 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004680 }
4681 }
4682 mPreviousTrack = track;
4683
Eric Laurentd595b7c2013-04-03 17:27:56 -07004684 // reset retry count
4685 track->mRetryCount = kMaxTrackRetriesDirect;
4686 mActiveTrack = t;
4687 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07004688 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004689 doHwResume = true;
4690 mHwPaused = false;
4691 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004692 }
Eric Laurent81784c32012-11-19 14:55:58 -08004693 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004694 // clear effect chain input buffer if the last active track started underruns
4695 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07004696 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004697 mEffectChains[0]->clearInputBuffer();
4698 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004699 if (track->isStopping_1()) {
4700 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07004701 if (last && mHwPaused) {
4702 doHwResume = true;
4703 mHwPaused = false;
4704 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004705 }
4706 if ((track->sharedBuffer() != 0) || track->isStopped() ||
4707 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004708 // We have consumed all the buffers of this track.
4709 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07004710 size_t audioHALFrames;
4711 if (audio_is_linear_pcm(mFormat)) {
4712 audioHALFrames = (latency_l() * mSampleRate) / 1000;
4713 } else {
4714 audioHALFrames = 0;
4715 }
4716
Eric Laurent81784c32012-11-19 14:55:58 -08004717 size_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07004718 if (mStandby || !last ||
4719 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004720 if (track->isStopping_2()) {
4721 track->mState = TrackBase::STOPPED;
4722 }
Eric Laurent81784c32012-11-19 14:55:58 -08004723 if (track->isStopped()) {
4724 track->reset();
4725 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004726 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08004727 }
4728 } else {
4729 // No buffers for this track. Give it a few chances to
4730 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07004731 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08004732 if (--(track->mRetryCount) <= 0) {
4733 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07004734 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004735 // indicate to client process that the track was disabled because of underrun;
4736 // it will then automatically call start() when data is available
4737 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004738 } else if (last) {
Phil Burkca5e6142015-07-14 09:42:29 -07004739 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
4740 "minFrames = %u, mFormat = %#x",
4741 track->framesReady(), minFrames, mFormat);
Eric Laurent81784c32012-11-19 14:55:58 -08004742 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07004743 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004744 doHwPause = true;
4745 mHwPaused = true;
4746 }
Eric Laurent81784c32012-11-19 14:55:58 -08004747 }
4748 }
4749 }
4750 }
4751
Eric Laurentd1f69b02014-12-15 14:33:13 -08004752 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07004753 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004754 for (size_t i = 0; i < mTracks.size(); i++) {
4755 if (mTracks[i]->isFlushPending()) {
4756 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004757 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004758 }
4759 }
4760 }
4761
4762 // make sure the pause/flush/resume sequence is executed in the right order.
4763 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4764 // before flush and then resume HW. This can happen in case of pause/flush/resume
4765 // if resume is received before pause is executed.
4766 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07004767 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004768 mOutput->stream->pause(mOutput->stream);
4769 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004770 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004771 flushHw_l();
4772 }
4773 if (mHwSupportsPause && !mStandby && doHwResume) {
4774 mOutput->stream->resume(mOutput->stream);
4775 }
Eric Laurent81784c32012-11-19 14:55:58 -08004776 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004777 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004778
4779 return mixerStatus;
4780}
4781
4782void AudioFlinger::DirectOutputThread::threadLoop_mix()
4783{
Eric Laurent81784c32012-11-19 14:55:58 -08004784 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08004785 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004786 // output audio to hardware
4787 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07004788 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004789 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08004790 status_t status = mActiveTrack->getNextBuffer(&buffer);
4791 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08004792 memset(curBuf, 0, frameCount * mFrameSize);
4793 break;
4794 }
4795 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
4796 frameCount -= buffer.frameCount;
4797 curBuf += buffer.frameCount * mFrameSize;
4798 mActiveTrack->releaseBuffer(&buffer);
4799 }
Andy Hung2098f272014-02-27 14:00:06 -08004800 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004801 mSleepTimeUs = 0;
4802 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08004803 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004804}
4805
4806void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
4807{
Eric Laurentd1f69b02014-12-15 14:33:13 -08004808 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004809 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004810 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004811 return;
4812 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004813 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004814 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004815 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004816 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004817 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004818 }
4819 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08004820 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004821 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004822 }
4823}
4824
Eric Laurentd1f69b02014-12-15 14:33:13 -08004825void AudioFlinger::DirectOutputThread::threadLoop_exit()
4826{
4827 {
4828 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08004829 for (size_t i = 0; i < mTracks.size(); i++) {
4830 if (mTracks[i]->isFlushPending()) {
4831 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004832 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004833 }
4834 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004835 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004836 flushHw_l();
4837 }
4838 }
4839 PlaybackThread::threadLoop_exit();
4840}
4841
4842// must be called with thread mutex locked
4843bool AudioFlinger::DirectOutputThread::shouldStandby_l()
4844{
4845 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07004846 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004847
4848 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4849 // after a timeout and we will enter standby then.
4850 if (mTracks.size() > 0) {
4851 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07004852 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
4853 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004854 }
4855
Eric Laurent5cff4032015-05-26 13:49:58 -07004856 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08004857}
4858
Eric Laurent81784c32012-11-19 14:55:58 -08004859// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004860int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Andy Hunge8a1ced2014-05-09 15:02:21 -07004861 audio_format_t format __unused, int sessionId __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004862{
4863 return 0;
4864}
4865
4866// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004867void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004868{
4869}
4870
Eric Laurent10351942014-05-08 18:49:52 -07004871// checkForNewParameter_l() must be called with ThreadBase::mLock held
4872bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
4873 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004874{
4875 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08004876 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004877
Eric Laurent10351942014-05-08 18:49:52 -07004878 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004879
Eric Laurent10351942014-05-08 18:49:52 -07004880 AudioParameter param = AudioParameter(keyValuePair);
4881 int value;
4882 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4883 // forward device change to effects that have requested to be
4884 // aware of attached audio device.
4885 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08004886 a2dpDeviceChanged =
4887 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07004888 mOutDevice = value;
4889 for (size_t i = 0; i < mEffectChains.size(); i++) {
4890 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07004891 }
4892 }
Eric Laurent81784c32012-11-19 14:55:58 -08004893 }
Eric Laurent10351942014-05-08 18:49:52 -07004894 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4895 // do not accept frame count changes if tracks are open as the track buffer
4896 // size depends on frame count and correct behavior would not be garantied
4897 // if frame count is changed after track creation
4898 if (!mTracks.isEmpty()) {
4899 status = INVALID_OPERATION;
4900 } else {
4901 reconfig = true;
4902 }
4903 }
4904 if (status == NO_ERROR) {
4905 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4906 keyValuePair.string());
4907 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004908 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004909 mStandby = true;
4910 mBytesWritten = 0;
4911 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4912 keyValuePair.string());
4913 }
4914 if (status == NO_ERROR && reconfig) {
4915 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07004916 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004917 }
4918 }
4919
Eric Laurent42537be2016-01-08 17:16:42 -08004920 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08004921}
4922
4923uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
4924{
4925 uint32_t time;
4926 if (audio_is_linear_pcm(mFormat)) {
4927 time = PlaybackThread::activeSleepTimeUs();
4928 } else {
4929 time = 10000;
4930 }
4931 return time;
4932}
4933
4934uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
4935{
4936 uint32_t time;
4937 if (audio_is_linear_pcm(mFormat)) {
4938 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
4939 } else {
4940 time = 10000;
4941 }
4942 return time;
4943}
4944
4945uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
4946{
4947 uint32_t time;
4948 if (audio_is_linear_pcm(mFormat)) {
4949 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
4950 } else {
4951 time = 10000;
4952 }
4953 return time;
4954}
4955
4956void AudioFlinger::DirectOutputThread::cacheParameters_l()
4957{
4958 PlaybackThread::cacheParameters_l();
4959
4960 // use shorter standby delay as on normal output to release
4961 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07004962 // no delay on outputs with HW A/V sync
4963 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004964 mStandbyDelayNs = 0;
Eric Laurent5cff4032015-05-26 13:49:58 -07004965 } else if ((mType == OFFLOAD) && !audio_is_linear_pcm(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004966 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07004967 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004968 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07004969 }
Eric Laurent81784c32012-11-19 14:55:58 -08004970}
4971
Eric Laurente659ef42014-09-29 13:06:46 -07004972void AudioFlinger::DirectOutputThread::flushHw_l()
4973{
Phil Burk062e67a2015-02-11 13:40:50 -08004974 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08004975 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07004976 mFlushPending = false;
Eric Laurente659ef42014-09-29 13:06:46 -07004977}
4978
Eric Laurent81784c32012-11-19 14:55:58 -08004979// ----------------------------------------------------------------------------
4980
Eric Laurentbfb1b832013-01-07 09:53:42 -08004981AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07004982 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004983 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07004984 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07004985 mWriteAckSequence(0),
4986 mDrainSequence(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004987{
4988}
4989
4990AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
4991{
4992}
4993
4994void AudioFlinger::AsyncCallbackThread::onFirstRef()
4995{
4996 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
4997}
4998
4999bool AudioFlinger::AsyncCallbackThread::threadLoop()
5000{
5001 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005002 uint32_t writeAckSequence;
5003 uint32_t drainSequence;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005004
5005 {
5006 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005007 while (!((mWriteAckSequence & 1) ||
5008 (mDrainSequence & 1) ||
5009 exitPending())) {
5010 mWaitWorkCV.wait(mLock);
5011 }
5012
Eric Laurentbfb1b832013-01-07 09:53:42 -08005013 if (exitPending()) {
5014 break;
5015 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005016 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
5017 mWriteAckSequence, mDrainSequence);
5018 writeAckSequence = mWriteAckSequence;
5019 mWriteAckSequence &= ~1;
5020 drainSequence = mDrainSequence;
5021 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005022 }
5023 {
Eric Laurent4de95592013-09-26 15:28:21 -07005024 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
5025 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005026 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005027 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005028 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005029 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005030 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005031 }
5032 }
5033 }
5034 }
5035 return false;
5036}
5037
5038void AudioFlinger::AsyncCallbackThread::exit()
5039{
5040 ALOGV("AsyncCallbackThread::exit");
5041 Mutex::Autolock _l(mLock);
5042 requestExit();
5043 mWaitWorkCV.broadcast();
5044}
5045
Eric Laurent3b4529e2013-09-05 18:09:19 -07005046void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005047{
5048 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005049 // bit 0 is cleared
5050 mWriteAckSequence = sequence << 1;
5051}
5052
5053void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
5054{
5055 Mutex::Autolock _l(mLock);
5056 // ignore unexpected callbacks
5057 if (mWriteAckSequence & 2) {
5058 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005059 mWaitWorkCV.signal();
5060 }
5061}
5062
Eric Laurent3b4529e2013-09-05 18:09:19 -07005063void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005064{
5065 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005066 // bit 0 is cleared
5067 mDrainSequence = sequence << 1;
5068}
5069
5070void AudioFlinger::AsyncCallbackThread::resetDraining()
5071{
5072 Mutex::Autolock _l(mLock);
5073 // ignore unexpected callbacks
5074 if (mDrainSequence & 2) {
5075 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005076 mWaitWorkCV.signal();
5077 }
5078}
5079
5080
5081// ----------------------------------------------------------------------------
5082AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07005083 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady)
5084 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady),
Eric Laurentd7e59222013-11-15 12:02:28 -08005085 mPausedBytesRemaining(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005086{
Eric Laurentfd477972013-10-25 18:10:40 -07005087 //FIXME: mStandby should be set to true by ThreadBase constructor
5088 mStandby = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005089}
5090
Eric Laurentbfb1b832013-01-07 09:53:42 -08005091void AudioFlinger::OffloadThread::threadLoop_exit()
5092{
5093 if (mFlushPending || mHwPaused) {
5094 // If a flush is pending or track was paused, just discard buffered data
5095 flushHw_l();
5096 } else {
5097 mMixerStatus = MIXER_DRAIN_ALL;
5098 threadLoop_drain();
5099 }
Uday Gupta56604aa2014-05-13 11:19:17 -07005100 if (mUseAsyncWrite) {
5101 ALOG_ASSERT(mCallbackThread != 0);
5102 mCallbackThread->exit();
5103 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005104 PlaybackThread::threadLoop_exit();
5105}
5106
5107AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
5108 Vector< sp<Track> > *tracksToRemove
5109)
5110{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005111 size_t count = mActiveTracks.size();
5112
5113 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07005114 bool doHwPause = false;
5115 bool doHwResume = false;
5116
Eric Laurentede6c3b2013-09-19 14:37:46 -07005117 ALOGV("OffloadThread::prepareTracks_l active tracks %d", count);
5118
Eric Laurentbfb1b832013-01-07 09:53:42 -08005119 // find out which tracks need to be processed
5120 for (size_t i = 0; i < count; i++) {
5121 sp<Track> t = mActiveTracks[i].promote();
5122 // The track died recently
5123 if (t == 0) {
5124 continue;
5125 }
5126 Track* const track = t.get();
5127 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07005128 // Only consider last track started for volume and mixer state control.
5129 // In theory an older track could underrun and restart after the new one starts
5130 // but as we only care about the transition phase between two tracks on a
5131 // direct output, it is not a problem to ignore the underrun case.
5132 sp<Track> l = mLatestActiveTrack.promote();
5133 bool last = l.get() == track;
5134
Haynes Mathew George7844f672014-01-15 12:32:55 -08005135 if (track->isInvalid()) {
5136 ALOGW("An invalidated track shouldn't be in active list");
5137 tracksToRemove->add(track);
5138 continue;
5139 }
5140
5141 if (track->mState == TrackBase::IDLE) {
5142 ALOGW("An idle track shouldn't be in active list");
5143 continue;
5144 }
5145
Eric Laurentbfb1b832013-01-07 09:53:42 -08005146 if (track->isPausing()) {
5147 track->setPaused();
5148 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07005149 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07005150 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005151 mHwPaused = true;
5152 }
5153 // If we were part way through writing the mixbuffer to
5154 // the HAL we must save this until we resume
5155 // BUG - this will be wrong if a different track is made active,
5156 // in that case we want to discard the pending data in the
5157 // mixbuffer and tell the client to present it again when the
5158 // track is resumed
5159 mPausedWriteLength = mCurrentWriteLength;
5160 mPausedBytesRemaining = mBytesRemaining;
5161 mBytesRemaining = 0; // stop writing
5162 }
5163 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08005164 } else if (track->isFlushPending()) {
5165 track->flushAck();
5166 if (last) {
5167 mFlushPending = true;
5168 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005169 } else if (track->isResumePending()){
5170 track->resumeAck();
5171 if (last) {
5172 if (mPausedBytesRemaining) {
5173 // Need to continue write that was interrupted
5174 mCurrentWriteLength = mPausedWriteLength;
5175 mBytesRemaining = mPausedBytesRemaining;
5176 mPausedBytesRemaining = 0;
5177 }
5178 if (mHwPaused) {
5179 doHwResume = true;
5180 mHwPaused = false;
5181 // threadLoop_mix() will handle the case that we need to
5182 // resume an interrupted write
5183 }
5184 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005185 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005186
5187 // Do not handle new data in this iteration even if track->framesReady()
5188 mixerStatus = MIXER_TRACKS_ENABLED;
5189 }
5190 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07005191 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005192 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005193 if (track->mFillingUpStatus == Track::FS_FILLED) {
5194 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07005195 // make sure processVolume_l() will apply new volume even if 0
5196 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005197 }
5198
5199 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08005200 sp<Track> previousTrack = mPreviousTrack.promote();
5201 if (previousTrack != 0) {
5202 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08005203 // Flush any data still being written from last track
5204 mBytesRemaining = 0;
5205 if (mPausedBytesRemaining) {
5206 // Last track was paused so we also need to flush saved
5207 // mixbuffer state and invalidate track so that it will
5208 // re-submit that unwritten data when it is next resumed
5209 mPausedBytesRemaining = 0;
5210 // Invalidate is a bit drastic - would be more efficient
5211 // to have a flag to tell client that some of the
5212 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08005213 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005214 }
5215 // flush data already sent to the DSP if changing audio session as audio
5216 // comes from a different source. Also invalidate previous track to force a
5217 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08005218 if (previousTrack->sessionId() != track->sessionId()) {
5219 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005220 }
5221 }
5222 }
5223 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005224 // reset retry count
5225 track->mRetryCount = kMaxTrackRetriesOffload;
5226 mActiveTrack = t;
5227 mixerStatus = MIXER_TRACKS_READY;
5228 }
5229 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005230 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005231 if (track->isStopping_1()) {
5232 // Hardware buffer can hold a large amount of audio so we must
5233 // wait for all current track's data to drain before we say
5234 // that the track is stopped.
5235 if (mBytesRemaining == 0) {
5236 // Only start draining when all data in mixbuffer
5237 // has been written
5238 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
5239 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005240 // do not drain if no data was ever sent to HAL (mStandby == true)
5241 if (last && !mStandby) {
Eric Laurent1b9f9b12013-11-12 19:10:17 -08005242 // do not modify drain sequence if we are already draining. This happens
5243 // when resuming from pause after drain.
5244 if ((mDrainSequence & 1) == 0) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005245 mSleepTimeUs = 0;
5246 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent1b9f9b12013-11-12 19:10:17 -08005247 mixerStatus = MIXER_DRAIN_TRACK;
5248 mDrainSequence += 2;
5249 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005250 if (mHwPaused) {
5251 // It is possible to move from PAUSED to STOPPING_1 without
5252 // a resume so we must ensure hardware is running
Eric Laurent1b9f9b12013-11-12 19:10:17 -08005253 doHwResume = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005254 mHwPaused = false;
5255 }
5256 }
5257 }
5258 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005259 // Drain has completed or we are in standby, signal presentation complete
5260 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005261 track->mState = TrackBase::STOPPED;
5262 size_t audioHALFrames =
5263 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
5264 size_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08005265 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005266 track->presentationComplete(framesWritten, audioHALFrames);
5267 track->reset();
5268 tracksToRemove->add(track);
5269 }
5270 } else {
5271 // No buffers for this track. Give it a few chances to
5272 // fill a buffer, then remove it from active list.
5273 if (--(track->mRetryCount) <= 0) {
5274 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
5275 track->name());
5276 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08005277 // indicate to client process that the track was disabled because of underrun;
5278 // it will then automatically call start() when data is available
5279 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005280 } else if (last){
5281 mixerStatus = MIXER_TRACKS_ENABLED;
5282 }
5283 }
5284 }
5285 // compute volume for this track
5286 processVolume_l(track, last);
5287 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005288
Eric Laurentea0fade2013-10-04 16:23:48 -07005289 // make sure the pause/flush/resume sequence is executed in the right order.
5290 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5291 // before flush and then resume HW. This can happen in case of pause/flush/resume
5292 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07005293 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurent972a1732013-09-04 09:42:59 -07005294 mOutput->stream->pause(mOutput->stream);
5295 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005296 if (mFlushPending) {
5297 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005298 }
Eric Laurentfd477972013-10-25 18:10:40 -07005299 if (!mStandby && doHwResume) {
Eric Laurent972a1732013-09-04 09:42:59 -07005300 mOutput->stream->resume(mOutput->stream);
5301 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005302
Eric Laurentbfb1b832013-01-07 09:53:42 -08005303 // remove all the tracks that need to be...
5304 removeTracks_l(*tracksToRemove);
5305
5306 return mixerStatus;
5307}
5308
Eric Laurentbfb1b832013-01-07 09:53:42 -08005309// must be called with thread mutex locked
5310bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
5311{
Eric Laurent3b4529e2013-09-05 18:09:19 -07005312 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
5313 mWriteAckSequence, mDrainSequence);
5314 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005315 return true;
5316 }
5317 return false;
5318}
5319
Eric Laurentbfb1b832013-01-07 09:53:42 -08005320bool AudioFlinger::OffloadThread::waitingAsyncCallback()
5321{
5322 Mutex::Autolock _l(mLock);
5323 return waitingAsyncCallback_l();
5324}
5325
5326void AudioFlinger::OffloadThread::flushHw_l()
5327{
Eric Laurente659ef42014-09-29 13:06:46 -07005328 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005329 // Flush anything still waiting in the mixbuffer
5330 mCurrentWriteLength = 0;
5331 mBytesRemaining = 0;
5332 mPausedWriteLength = 0;
5333 mPausedBytesRemaining = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08005334
Eric Laurentbfb1b832013-01-07 09:53:42 -08005335 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005336 // discard any pending drain or write ack by incrementing sequence
5337 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5338 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005339 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005340 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5341 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005342 }
5343}
5344
5345// ----------------------------------------------------------------------------
5346
Eric Laurent81784c32012-11-19 14:55:58 -08005347AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07005348 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08005349 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
Eric Laurent72e3f392015-05-20 14:43:50 -07005350 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08005351 mWaitTimeMs(UINT_MAX)
5352{
5353 addOutputTrack(mainThread);
5354}
5355
5356AudioFlinger::DuplicatingThread::~DuplicatingThread()
5357{
5358 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5359 mOutputTracks[i]->destroy();
5360 }
5361}
5362
5363void AudioFlinger::DuplicatingThread::threadLoop_mix()
5364{
5365 // mix buffers...
5366 if (outputsReady(outputTracks)) {
5367 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
5368 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08005369 if (mMixerBufferValid) {
5370 memset(mMixerBuffer, 0, mMixerBufferSize);
5371 } else {
5372 memset(mSinkBuffer, 0, mSinkBufferSize);
5373 }
Eric Laurent81784c32012-11-19 14:55:58 -08005374 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005375 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005376 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005377 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005378 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005379}
5380
5381void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
5382{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005383 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005384 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005385 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005386 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005387 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005388 }
5389 } else if (mBytesWritten != 0) {
5390 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5391 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005392 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005393 } else {
5394 // flush remaining overflow buffers in output tracks
5395 writeFrames = 0;
5396 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005397 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005398 }
5399}
5400
Eric Laurentbfb1b832013-01-07 09:53:42 -08005401ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005402{
5403 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08005404 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005405 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07005406 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08005407 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005408}
5409
5410void AudioFlinger::DuplicatingThread::threadLoop_standby()
5411{
5412 // DuplicatingThread implements standby by stopping all tracks
5413 for (size_t i = 0; i < outputTracks.size(); i++) {
5414 outputTracks[i]->stop();
5415 }
5416}
5417
5418void AudioFlinger::DuplicatingThread::saveOutputTracks()
5419{
5420 outputTracks = mOutputTracks;
5421}
5422
5423void AudioFlinger::DuplicatingThread::clearOutputTracks()
5424{
5425 outputTracks.clear();
5426}
5427
5428void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
5429{
5430 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08005431 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
5432 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
5433 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
5434 const size_t frameCount =
5435 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
5436 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
5437 // from different OutputTracks and their associated MixerThreads (e.g. one may
5438 // nearly empty and the other may be dropping data).
5439
5440 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08005441 this,
5442 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08005443 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08005444 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005445 frameCount,
5446 IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08005447 if (outputTrack->cblk() != NULL) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005448 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
Eric Laurent81784c32012-11-19 14:55:58 -08005449 mOutputTracks.add(outputTrack);
Andy Hungc25b84a2015-01-14 19:04:10 -08005450 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005451 updateWaitTime_l();
5452 }
5453}
5454
5455void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
5456{
5457 Mutex::Autolock _l(mLock);
5458 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5459 if (mOutputTracks[i]->thread() == thread) {
5460 mOutputTracks[i]->destroy();
5461 mOutputTracks.removeAt(i);
5462 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07005463 if (thread->getOutput() == mOutput) {
5464 mOutput = NULL;
5465 }
Eric Laurent81784c32012-11-19 14:55:58 -08005466 return;
5467 }
5468 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07005469 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005470}
5471
5472// caller must hold mLock
5473void AudioFlinger::DuplicatingThread::updateWaitTime_l()
5474{
5475 mWaitTimeMs = UINT_MAX;
5476 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5477 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
5478 if (strong != 0) {
5479 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
5480 if (waitTimeMs < mWaitTimeMs) {
5481 mWaitTimeMs = waitTimeMs;
5482 }
5483 }
5484 }
5485}
5486
5487
5488bool AudioFlinger::DuplicatingThread::outputsReady(
5489 const SortedVector< sp<OutputTrack> > &outputTracks)
5490{
5491 for (size_t i = 0; i < outputTracks.size(); i++) {
5492 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
5493 if (thread == 0) {
5494 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
5495 outputTracks[i].get());
5496 return false;
5497 }
5498 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5499 // see note at standby() declaration
5500 if (playbackThread->standby() && !playbackThread->isSuspended()) {
5501 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
5502 thread.get());
5503 return false;
5504 }
5505 }
5506 return true;
5507}
5508
5509uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
5510{
5511 return (mWaitTimeMs * 1000) / 2;
5512}
5513
5514void AudioFlinger::DuplicatingThread::cacheParameters_l()
5515{
5516 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
5517 updateWaitTime_l();
5518
5519 MixerThread::cacheParameters_l();
5520}
5521
5522// ----------------------------------------------------------------------------
5523// Record
5524// ----------------------------------------------------------------------------
5525
5526AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5527 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08005528 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08005529 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07005530 audio_devices_t inDevice,
5531 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08005532#ifdef TEE_SINK
5533 , const sp<NBAIO_Sink>& teeSink
5534#endif
5535 ) :
Eric Laurent72e3f392015-05-20 14:43:50 -07005536 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005537 mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005538 // mRsmpInFrames and mRsmpInFramesP2 are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005539 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08005540#ifdef TEE_SINK
5541 , mTeeSink(teeSink)
5542#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07005543 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
5544 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005545 // mFastCapture below
5546 , mFastCaptureFutex(0)
5547 // mInputSource
5548 // mPipeSink
5549 // mPipeSource
5550 , mPipeFramesP2(0)
5551 // mPipeMemory
5552 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005553 , mFastTrackAvail(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005554{
Glenn Kastend7dca052015-03-05 16:05:54 -08005555 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
5556 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08005557
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005558 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005559
5560 // create an NBAIO source for the HAL input stream, and negotiate
5561 mInputSource = new AudioStreamInSource(input->stream);
5562 size_t numCounterOffers = 0;
5563 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
5564 ssize_t index = mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
5565 ALOG_ASSERT(index == 0);
5566
5567 // initialize fast capture depending on configuration
5568 bool initFastCapture;
5569 switch (kUseFastCapture) {
5570 case FastCapture_Never:
5571 initFastCapture = false;
5572 break;
5573 case FastCapture_Always:
5574 initFastCapture = true;
5575 break;
5576 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07005577 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005578 break;
5579 // case FastCapture_Dynamic:
5580 }
5581
5582 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07005583 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005584 NBAIO_Format format = mInputSource->format();
Glenn Kasten49d00ad2014-07-21 11:22:03 -07005585 size_t pipeFramesP2 = roundup(mSampleRate / 25); // double-buffering of 20 ms each
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005586 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
5587 void *pipeBuffer;
5588 const sp<MemoryDealer> roHeap(readOnlyHeap());
5589 sp<IMemory> pipeMemory;
5590 if ((roHeap == 0) ||
5591 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
5592 (pipeBuffer = pipeMemory->pointer()) == NULL) {
5593 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
5594 goto failed;
5595 }
5596 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
5597 memset(pipeBuffer, 0, pipeSize);
5598 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
5599 const NBAIO_Format offers[1] = {format};
5600 size_t numCounterOffers = 0;
5601 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
5602 ALOG_ASSERT(index == 0);
5603 mPipeSink = pipe;
5604 PipeReader *pipeReader = new PipeReader(*pipe);
5605 numCounterOffers = 0;
5606 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
5607 ALOG_ASSERT(index == 0);
5608 mPipeSource = pipeReader;
5609 mPipeFramesP2 = pipeFramesP2;
5610 mPipeMemory = pipeMemory;
5611
5612 // create fast capture
5613 mFastCapture = new FastCapture();
5614 FastCaptureStateQueue *sq = mFastCapture->sq();
5615#ifdef STATE_QUEUE_DUMP
5616 // FIXME
5617#endif
5618 FastCaptureState *state = sq->begin();
5619 state->mCblk = NULL;
5620 state->mInputSource = mInputSource.get();
5621 state->mInputSourceGen++;
5622 state->mPipeSink = pipe;
5623 state->mPipeSinkGen++;
5624 state->mFrameCount = mFrameCount;
5625 state->mCommand = FastCaptureState::COLD_IDLE;
5626 // already done in constructor initialization list
5627 //mFastCaptureFutex = 0;
5628 state->mColdFutexAddr = &mFastCaptureFutex;
5629 state->mColdGen++;
5630 state->mDumpState = &mFastCaptureDumpState;
5631#ifdef TEE_SINK
5632 // FIXME
5633#endif
5634 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
5635 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
5636 sq->end();
5637 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5638
5639 // start the fast capture
5640 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
5641 pid_t tid = mFastCapture->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07005642 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005643#ifdef AUDIO_WATCHDOG
5644 // FIXME
5645#endif
5646
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005647 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005648 }
5649failed: ;
5650
5651 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08005652}
5653
Eric Laurent81784c32012-11-19 14:55:58 -08005654AudioFlinger::RecordThread::~RecordThread()
5655{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005656 if (mFastCapture != 0) {
5657 FastCaptureStateQueue *sq = mFastCapture->sq();
5658 FastCaptureState *state = sq->begin();
5659 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5660 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5661 if (old == -1) {
5662 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5663 }
5664 }
5665 state->mCommand = FastCaptureState::EXIT;
5666 sq->end();
5667 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5668 mFastCapture->join();
5669 mFastCapture.clear();
5670 }
5671 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07005672 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07005673 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08005674}
5675
5676void AudioFlinger::RecordThread::onFirstRef()
5677{
Glenn Kastend7dca052015-03-05 16:05:54 -08005678 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08005679}
5680
Eric Laurent81784c32012-11-19 14:55:58 -08005681bool AudioFlinger::RecordThread::threadLoop()
5682{
Eric Laurent81784c32012-11-19 14:55:58 -08005683 nsecs_t lastWarning = 0;
5684
5685 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08005686
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005687reacquire_wakelock:
5688 sp<RecordTrack> activeTrack;
Glenn Kasten2b806402013-11-20 16:37:38 -08005689 int activeTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005690 {
5691 Mutex::Autolock _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005692 size_t size = mActiveTracks.size();
5693 activeTracksGen = mActiveTracksGen;
5694 if (size > 0) {
5695 // FIXME an arbitrary choice
5696 activeTrack = mActiveTracks[0];
5697 acquireWakeLock_l(activeTrack->uid());
5698 if (size > 1) {
5699 SortedVector<int> tmp;
5700 for (size_t i = 0; i < size; i++) {
5701 tmp.add(mActiveTracks[i]->uid());
5702 }
5703 updateWakeLockUids_l(tmp);
5704 }
5705 } else {
5706 acquireWakeLock_l(-1);
5707 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005708 }
5709
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005710 // used to request a deferred sleep, to be executed later while mutex is unlocked
5711 uint32_t sleepUs = 0;
5712
5713 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005714 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005715 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07005716
Glenn Kasten5edadd42013-08-14 16:30:49 -07005717 // sleep with mutex unlocked
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005718 if (sleepUs > 0) {
Glenn Kastene7754022014-10-31 12:11:26 -07005719 ATRACE_BEGIN("sleep");
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005720 usleep(sleepUs);
Glenn Kastene7754022014-10-31 12:11:26 -07005721 ATRACE_END();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005722 sleepUs = 0;
Glenn Kasten5edadd42013-08-14 16:30:49 -07005723 }
5724
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005725 // activeTracks accumulates a copy of a subset of mActiveTracks
5726 Vector< sp<RecordTrack> > activeTracks;
5727
Glenn Kasten735f45f2014-08-18 15:51:59 -07005728 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005729 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07005730
Glenn Kasten735f45f2014-08-18 15:51:59 -07005731 // reference to a fast track which is about to be removed
5732 sp<RecordTrack> fastTrackToRemove;
5733
Eric Laurent81784c32012-11-19 14:55:58 -08005734 { // scope for mLock
5735 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08005736
Eric Laurent021cf962014-05-13 10:18:14 -07005737 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005738
Eric Laurent000a4192014-01-29 15:17:32 -08005739 // check exitPending here because checkForNewParameters_l() and
5740 // checkForNewParameters_l() can temporarily release mLock
5741 if (exitPending()) {
5742 break;
5743 }
5744
Glenn Kasten2b806402013-11-20 16:37:38 -08005745 // if no active track(s), then standby and release wakelock
5746 size_t size = mActiveTracks.size();
5747 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07005748 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005749 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08005750 releaseWakeLock_l();
5751 ALOGV("RecordThread: loop stopping");
5752 // go to sleep
5753 mWaitWorkCV.wait(mLock);
5754 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005755 goto reacquire_wakelock;
5756 }
5757
Glenn Kasten2b806402013-11-20 16:37:38 -08005758 if (mActiveTracksGen != activeTracksGen) {
5759 activeTracksGen = mActiveTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005760 SortedVector<int> tmp;
Glenn Kasten2b806402013-11-20 16:37:38 -08005761 for (size_t i = 0; i < size; i++) {
5762 tmp.add(mActiveTracks[i]->uid());
5763 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005764 updateWakeLockUids_l(tmp);
Eric Laurent81784c32012-11-19 14:55:58 -08005765 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005766
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005767 bool doBroadcast = false;
5768 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07005769
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005770 activeTrack = mActiveTracks[i];
5771 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07005772 if (activeTrack->isFastTrack()) {
5773 ALOG_ASSERT(fastTrackToRemove == 0);
5774 fastTrackToRemove = activeTrack;
5775 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005776 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08005777 mActiveTracks.remove(activeTrack);
5778 mActiveTracksGen++;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005779 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07005780 continue;
5781 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005782
5783 TrackBase::track_state activeTrackState = activeTrack->mState;
5784 switch (activeTrackState) {
5785
5786 case TrackBase::PAUSING:
5787 mActiveTracks.remove(activeTrack);
5788 mActiveTracksGen++;
5789 doBroadcast = true;
5790 size--;
5791 continue;
5792
5793 case TrackBase::STARTING_1:
5794 sleepUs = 10000;
5795 i++;
5796 continue;
5797
5798 case TrackBase::STARTING_2:
5799 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005800 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07005801 activeTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005802 break;
5803
5804 case TrackBase::ACTIVE:
5805 break;
5806
5807 case TrackBase::IDLE:
5808 i++;
5809 continue;
5810
5811 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08005812 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07005813 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005814
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005815 activeTracks.add(activeTrack);
5816 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07005817
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005818 if (activeTrack->isFastTrack()) {
5819 ALOG_ASSERT(!mFastTrackAvail);
5820 ALOG_ASSERT(fastTrack == 0);
5821 fastTrack = activeTrack;
5822 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005823 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005824 if (doBroadcast) {
5825 mStartStopCond.broadcast();
5826 }
5827
5828 // sleep if there are no active tracks to process
5829 if (activeTracks.size() == 0) {
5830 if (sleepUs == 0) {
5831 sleepUs = kRecordThreadSleepUs;
5832 }
5833 continue;
5834 }
5835 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07005836
Eric Laurent81784c32012-11-19 14:55:58 -08005837 lockEffectChains_l(effectChains);
5838 }
5839
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005840 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07005841
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005842 size_t size = effectChains.size();
5843 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005844 // thread mutex is not locked, but effect chain is locked
5845 effectChains[i]->process_l();
5846 }
5847
Glenn Kasten735f45f2014-08-18 15:51:59 -07005848 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005849 if (mFastCapture != 0) {
5850 FastCaptureStateQueue *sq = mFastCapture->sq();
5851 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07005852 bool didModify = false;
5853 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005854 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
5855 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
5856 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5857 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5858 if (old == -1) {
5859 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5860 }
5861 }
5862 state->mCommand = FastCaptureState::READ_WRITE;
5863#if 0 // FIXME
5864 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08005865 FastThreadDumpState::kSamplingNforLowRamDevice :
5866 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005867#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07005868 didModify = true;
5869 }
5870 audio_track_cblk_t *cblkOld = state->mCblk;
5871 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
5872 if (cblkNew != cblkOld) {
5873 state->mCblk = cblkNew;
5874 // block until acked if removing a fast track
5875 if (cblkOld != NULL) {
5876 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
5877 }
5878 didModify = true;
5879 }
5880 sq->end(didModify);
5881 if (didModify) {
5882 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005883#if 0
5884 if (kUseFastCapture == FastCapture_Dynamic) {
5885 mNormalSource = mPipeSource;
5886 }
5887#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005888 }
5889 }
5890
Glenn Kasten735f45f2014-08-18 15:51:59 -07005891 // now run the fast track destructor with thread mutex unlocked
5892 fastTrackToRemove.clear();
5893
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005894 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
5895 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
5896 // slow, then this RecordThread will overrun by not calling HAL read often enough.
5897 // If destination is non-contiguous, first read past the nominal end of buffer, then
5898 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005899
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005900 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005901 ssize_t framesRead;
5902
5903 // If an NBAIO source is present, use it to read the normal capture's data
5904 if (mPipeSource != 0) {
5905 size_t framesToRead = mBufferSize / mFrameSize;
Andy Hung57446612015-04-19 23:56:46 -07005906 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005907 framesToRead, AudioBufferProvider::kInvalidPTS);
5908 if (framesRead == 0) {
5909 // since pipe is non-blocking, simulate blocking input
5910 sleepUs = (framesToRead * 1000000LL) / mSampleRate;
5911 }
5912 // otherwise use the HAL / AudioStreamIn directly
5913 } else {
5914 ssize_t bytesRead = mInput->stream->read(mInput->stream,
Andy Hung57446612015-04-19 23:56:46 -07005915 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005916 if (bytesRead < 0) {
5917 framesRead = bytesRead;
5918 } else {
5919 framesRead = bytesRead / mFrameSize;
5920 }
5921 }
5922
5923 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
5924 ALOGE("read failed: framesRead=%d", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005925 // Force input into standby so that it tries to recover at next read attempt
5926 inputStandBy();
5927 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005928 }
5929 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005930 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005931 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005932 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005933
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005934 if (mTeeSink != 0) {
Andy Hung57446612015-04-19 23:56:46 -07005935 (void) mTeeSink->write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005936 }
5937 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005938 {
5939 size_t part1 = mRsmpInFramesP2 - rear;
5940 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07005941 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005942 (framesRead - part1) * mFrameSize);
5943 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005944 }
5945 rear = mRsmpInRear += framesRead;
5946
5947 size = activeTracks.size();
5948 // loop over each active track
5949 for (size_t i = 0; i < size; i++) {
5950 activeTrack = activeTracks[i];
5951
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005952 // skip fast tracks, as those are handled directly by FastCapture
5953 if (activeTrack->isFastTrack()) {
5954 continue;
5955 }
5956
Andy Hung73c02e42015-03-29 01:13:58 -07005957 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07005958 // TODO: Update the activeTrack buffer converter in case of reconfigure.
5959
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005960 enum {
5961 OVERRUN_UNKNOWN,
5962 OVERRUN_TRUE,
5963 OVERRUN_FALSE
5964 } overrun = OVERRUN_UNKNOWN;
5965
5966 // loop over getNextBuffer to handle circular sink
5967 for (;;) {
5968
5969 activeTrack->mSink.frameCount = ~0;
5970 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
5971 size_t framesOut = activeTrack->mSink.frameCount;
5972 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
5973
Andy Hung73c02e42015-03-29 01:13:58 -07005974 // check available frames and handle overrun conditions
5975 // if the record track isn't draining fast enough.
5976 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005977 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07005978 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
5979 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005980 overrun = OVERRUN_TRUE;
5981 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005982 if (framesOut == 0 || framesIn == 0) {
5983 break;
5984 }
5985
Andy Hung6770c6f2015-04-07 13:43:36 -07005986 // Don't allow framesOut to be larger than what is possible with resampling
5987 // from framesIn.
5988 // This isn't strictly necessary but helps limit buffer resizing in
5989 // RecordBufferConverter. TODO: remove when no longer needed.
5990 framesOut = min(framesOut,
5991 destinationFramesPossible(
5992 framesIn, mSampleRate, activeTrack->mSampleRate));
Andy Hung97a893e2015-03-29 01:03:07 -07005993 // process frames from the RecordThread buffer provider to the RecordTrack buffer
5994 framesOut = activeTrack->mRecordBufferConverter->convert(
5995 activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005996
5997 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
5998 overrun = OVERRUN_FALSE;
5999 }
6000
6001 if (activeTrack->mFramesToDrop == 0) {
6002 if (framesOut > 0) {
6003 activeTrack->mSink.frameCount = framesOut;
6004 activeTrack->releaseBuffer(&activeTrack->mSink);
6005 }
6006 } else {
6007 // FIXME could do a partial drop of framesOut
6008 if (activeTrack->mFramesToDrop > 0) {
6009 activeTrack->mFramesToDrop -= framesOut;
6010 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006011 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006012 }
6013 } else {
6014 activeTrack->mFramesToDrop += framesOut;
6015 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
6016 activeTrack->mSyncStartEvent->isCancelled()) {
6017 ALOGW("Synced record %s, session %d, trigger session %d",
6018 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
6019 activeTrack->sessionId(),
6020 (activeTrack->mSyncStartEvent != 0) ?
6021 activeTrack->mSyncStartEvent->triggerSession() : 0);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006022 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006023 }
6024 }
6025 }
6026
6027 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006028 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006029 }
6030 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006031
6032 switch (overrun) {
6033 case OVERRUN_TRUE:
6034 // client isn't retrieving buffers fast enough
6035 if (!activeTrack->setOverflow()) {
6036 nsecs_t now = systemTime();
6037 // FIXME should lastWarning per track?
6038 if ((now - lastWarning) > kWarningThrottleNs) {
6039 ALOGW("RecordThread: buffer overflow");
6040 lastWarning = now;
6041 }
6042 }
6043 break;
6044 case OVERRUN_FALSE:
6045 activeTrack->clearOverflow();
6046 break;
6047 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006048 break;
6049 }
6050
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006051 }
6052
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006053unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08006054 // enable changes in effect chain
6055 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006056 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08006057 }
6058
Glenn Kasten93e471f2013-08-19 08:40:07 -07006059 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08006060
6061 {
6062 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07006063 for (size_t i = 0; i < mTracks.size(); i++) {
6064 sp<RecordTrack> track = mTracks[i];
6065 track->invalidate();
6066 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006067 mActiveTracks.clear();
6068 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08006069 mStartStopCond.broadcast();
6070 }
6071
6072 releaseWakeLock();
6073
6074 ALOGV("RecordThread %p exiting", this);
6075 return false;
6076}
6077
Glenn Kasten93e471f2013-08-19 08:40:07 -07006078void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08006079{
6080 if (!mStandby) {
6081 inputStandBy();
6082 mStandby = true;
6083 }
6084}
6085
6086void AudioFlinger::RecordThread::inputStandBy()
6087{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006088 // Idle the fast capture if it's currently running
6089 if (mFastCapture != 0) {
6090 FastCaptureStateQueue *sq = mFastCapture->sq();
6091 FastCaptureState *state = sq->begin();
6092 if (!(state->mCommand & FastCaptureState::IDLE)) {
6093 state->mCommand = FastCaptureState::COLD_IDLE;
6094 state->mColdFutexAddr = &mFastCaptureFutex;
6095 state->mColdGen++;
6096 mFastCaptureFutex = 0;
6097 sq->end();
6098 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
6099 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
6100#if 0
6101 if (kUseFastCapture == FastCapture_Dynamic) {
6102 // FIXME
6103 }
6104#endif
6105#ifdef AUDIO_WATCHDOG
6106 // FIXME
6107#endif
6108 } else {
6109 sq->end(false /*didModify*/);
6110 }
6111 }
Eric Laurent81784c32012-11-19 14:55:58 -08006112 mInput->stream->common.standby(&mInput->stream->common);
6113}
6114
Glenn Kasten05997e22014-03-13 15:08:33 -07006115// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07006116sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08006117 const sp<AudioFlinger::Client>& client,
6118 uint32_t sampleRate,
6119 audio_format_t format,
6120 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08006121 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08006122 int sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07006123 size_t *notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08006124 int uid,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07006125 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08006126 pid_t tid,
6127 status_t *status)
6128{
Glenn Kasten74935e42013-12-19 08:56:45 -08006129 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08006130 sp<RecordTrack> track;
6131 status_t lStatus;
6132
Glenn Kasten90e58b12013-07-31 16:16:02 -07006133 // client expresses a preference for FAST, but we get the final say
6134 if (*flags & IAudioFlinger::TRACK_FAST) {
6135 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07006136 // we formerly checked for a callback handler (non-0 tid),
6137 // but that is no longer required for TRANSFER_OBTAIN mode
6138 //
Glenn Kasten74105912014-07-03 12:28:53 -07006139 // frame count is not specified, or is exactly the pipe depth
6140 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006141 // PCM data
6142 audio_is_linear_pcm(format) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006143 // native format
6144 (format == mFormat) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006145 // native channel mask
6146 (channelMask == mChannelMask) &&
6147 // native hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07006148 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006149 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006150 hasFastCapture() &&
6151 // there are sufficient fast track slots available
6152 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07006153 ) {
Glenn Kasten74105912014-07-03 12:28:53 -07006154 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%u mFrameCount=%u",
Glenn Kasten90e58b12013-07-31 16:16:02 -07006155 frameCount, mFrameCount);
6156 } else {
Glenn Kasten74105912014-07-03 12:28:53 -07006157 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%u mFrameCount=%u mPipeFramesP2=%u "
6158 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006159 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Glenn Kasten74105912014-07-03 12:28:53 -07006160 frameCount, mFrameCount, mPipeFramesP2,
6161 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
6162 hasFastCapture(), tid, mFastTrackAvail);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006163 *flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kasten74105912014-07-03 12:28:53 -07006164 }
6165 }
6166
6167 // compute track buffer size in frames, and suggest the notification frame count
6168 if (*flags & IAudioFlinger::TRACK_FAST) {
6169 // fast track: frame count is exactly the pipe depth
6170 frameCount = mPipeFramesP2;
6171 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
6172 *notificationFrames = mFrameCount;
6173 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006174 // not fast track: max notification period is resampled equivalent of one HAL buffer time
6175 // or 20 ms if there is a fast capture
6176 // TODO This could be a roundupRatio inline, and const
6177 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
6178 * sampleRate + mSampleRate - 1) / mSampleRate;
6179 // minimum number of notification periods is at least kMinNotifications,
6180 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
6181 static const size_t kMinNotifications = 3;
6182 static const uint32_t kMinMs = 30;
6183 // TODO This could be a roundupRatio inline
6184 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
6185 // TODO This could be a roundupRatio inline
6186 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
6187 maxNotificationFrames;
6188 const size_t minFrameCount = maxNotificationFrames *
6189 max(kMinNotifications, minNotificationsByMs);
6190 frameCount = max(frameCount, minFrameCount);
6191 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
6192 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07006193 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07006194 }
Glenn Kasten74935e42013-12-19 08:56:45 -08006195 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07006196
Glenn Kasten15e57982013-09-24 11:52:37 -07006197 lStatus = initCheck();
6198 if (lStatus != NO_ERROR) {
6199 ALOGE("createRecordTrack_l() audio driver not initialized");
6200 goto Exit;
6201 }
Eric Laurent81784c32012-11-19 14:55:58 -08006202
6203 { // scope for mLock
6204 Mutex::Autolock _l(mLock);
6205
6206 track = new RecordTrack(this, client, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07006207 format, channelMask, frameCount, NULL, sessionId, uid,
6208 *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08006209
Glenn Kasten03003332013-08-06 15:40:54 -07006210 lStatus = track->initCheck();
6211 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07006212 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08006213 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08006214 goto Exit;
6215 }
6216 mTracks.add(track);
6217
6218 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6219 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6220 mAudioFlinger->btNrecIsOff();
6221 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6222 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006223
6224 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
6225 pid_t callingPid = IPCThreadState::self()->getCallingPid();
6226 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
6227 // so ask activity manager to do this on our behalf
6228 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
6229 }
Eric Laurent81784c32012-11-19 14:55:58 -08006230 }
Glenn Kasten05997e22014-03-13 15:08:33 -07006231
Eric Laurent81784c32012-11-19 14:55:58 -08006232 lStatus = NO_ERROR;
6233
6234Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07006235 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08006236 return track;
6237}
6238
6239status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
6240 AudioSystem::sync_event_t event,
6241 int triggerSession)
6242{
6243 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
6244 sp<ThreadBase> strongMe = this;
6245 status_t status = NO_ERROR;
6246
6247 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006248 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006249 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006250 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08006251 triggerSession,
6252 recordTrack->sessionId(),
6253 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006254 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08006255 // Sync event can be cancelled by the trigger session if the track is not in a
6256 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006257 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006258 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006259 } else {
6260 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006261 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006262 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08006263 }
6264 }
6265
6266 {
Glenn Kasten47c20702013-08-13 15:37:35 -07006267 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08006268 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006269 if (mActiveTracks.indexOf(recordTrack) >= 0) {
6270 if (recordTrack->mState == TrackBase::PAUSING) {
6271 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006272 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006273 } else {
6274 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08006275 }
6276 return status;
6277 }
6278
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006279 // TODO consider other ways of handling this, such as changing the state to :STARTING and
6280 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
6281 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006282 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08006283 mActiveTracks.add(recordTrack);
6284 mActiveTracksGen++;
Eric Laurent83b88082014-06-20 18:31:16 -07006285 status_t status = NO_ERROR;
6286 if (recordTrack->isExternalTrack()) {
6287 mLock.unlock();
Eric Laurent4dc68062014-07-28 17:26:49 -07006288 status = AudioSystem::startInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006289 mLock.lock();
6290 // FIXME should verify that recordTrack is still in mActiveTracks
6291 if (status != NO_ERROR) {
6292 mActiveTracks.remove(recordTrack);
6293 mActiveTracksGen++;
6294 recordTrack->clearSyncStartEvent();
6295 ALOGV("RecordThread::start error %d", status);
6296 return status;
6297 }
Eric Laurent81784c32012-11-19 14:55:58 -08006298 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006299 // Catch up with current buffer indices if thread is already running.
6300 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
6301 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
6302 // see previously buffered data before it called start(), but with greater risk of overrun.
6303
Andy Hung73c02e42015-03-29 01:13:58 -07006304 recordTrack->mResamplerBufferProvider->reset();
Andy Hung97a893e2015-03-29 01:03:07 -07006305 // clear any converter state as new data will be discontinuous
6306 recordTrack->mRecordBufferConverter->reset();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006307 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08006308 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08006309 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08006310 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006311 ALOGV("Record failed to start");
6312 status = BAD_VALUE;
6313 goto startError;
6314 }
Eric Laurent81784c32012-11-19 14:55:58 -08006315 return status;
6316 }
Glenn Kasten7c027242012-12-26 14:43:16 -08006317
Eric Laurent81784c32012-11-19 14:55:58 -08006318startError:
Eric Laurent83b88082014-06-20 18:31:16 -07006319 if (recordTrack->isExternalTrack()) {
Eric Laurent4dc68062014-07-28 17:26:49 -07006320 AudioSystem::stopInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006321 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006322 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006323 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08006324 return status;
6325}
6326
Eric Laurent81784c32012-11-19 14:55:58 -08006327void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6328{
6329 sp<SyncEvent> strongEvent = event.promote();
6330
6331 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08006332 sp<RefBase> ptr = strongEvent->cookie().promote();
6333 if (ptr != 0) {
6334 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
6335 recordTrack->handleSyncStartEvent(strongEvent);
6336 }
Eric Laurent81784c32012-11-19 14:55:58 -08006337 }
6338}
6339
Glenn Kastena8356f62013-07-25 14:37:52 -07006340bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08006341 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07006342 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006343 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08006344 return false;
6345 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006346 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08006347 recordTrack->mState = TrackBase::PAUSING;
6348 // do not wait for mStartStopCond if exiting
6349 if (exitPending()) {
6350 return true;
6351 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006352 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08006353 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006354 // if we have been restarted, recordTrack is in mActiveTracks here
6355 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006356 ALOGV("Record stopped OK");
6357 return true;
6358 }
6359 return false;
6360}
6361
Glenn Kasten0f11b512014-01-31 16:18:54 -08006362bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08006363{
6364 return false;
6365}
6366
Glenn Kasten0f11b512014-01-31 16:18:54 -08006367status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006368{
6369#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
6370 if (!isValidSyncEvent(event)) {
6371 return BAD_VALUE;
6372 }
6373
6374 int eventSession = event->triggerSession();
6375 status_t ret = NAME_NOT_FOUND;
6376
6377 Mutex::Autolock _l(mLock);
6378
6379 for (size_t i = 0; i < mTracks.size(); i++) {
6380 sp<RecordTrack> track = mTracks[i];
6381 if (eventSession == track->sessionId()) {
6382 (void) track->setSyncEvent(event);
6383 ret = NO_ERROR;
6384 }
6385 }
6386 return ret;
6387#else
6388 return BAD_VALUE;
6389#endif
6390}
6391
6392// destroyTrack_l() must be called with ThreadBase::mLock held
6393void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6394{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006395 track->terminate();
6396 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08006397 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08006398 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006399 removeTrack_l(track);
6400 }
6401}
6402
6403void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6404{
6405 mTracks.remove(track);
6406 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006407 if (track->isFastTrack()) {
6408 ALOG_ASSERT(!mFastTrackAvail);
6409 mFastTrackAvail = true;
6410 }
Eric Laurent81784c32012-11-19 14:55:58 -08006411}
6412
6413void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6414{
6415 dumpInternals(fd, args);
6416 dumpTracks(fd, args);
6417 dumpEffectChains(fd, args);
6418}
6419
6420void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6421{
Elliott Hughes87cebad2014-05-22 10:14:43 -07006422 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08006423
Glenn Kasten44182c22015-03-05 17:12:23 -08006424 dumpBase(fd, args);
6425
6426 if (mActiveTracks.size() == 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006427 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006428 }
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006429 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006430 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08006431
Glenn Kasten2f90c512015-12-02 11:40:09 -08006432 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
6433 // while we are dumping it. It may be inconsistent, but it won't mutate!
6434 // This is a large object so we place it on the heap.
6435 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
6436 const FastCaptureDumpState *copy = new FastCaptureDumpState(mFastCaptureDumpState);
6437 copy->dump(fd);
6438 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08006439}
6440
Glenn Kasten0f11b512014-01-31 16:18:54 -08006441void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006442{
6443 const size_t SIZE = 256;
6444 char buffer[SIZE];
6445 String8 result;
6446
Marco Nelissenb2208842014-02-07 14:00:50 -08006447 size_t numtracks = mTracks.size();
6448 size_t numactive = mActiveTracks.size();
6449 size_t numactiveseen = 0;
Elliott Hughes87cebad2014-05-22 10:14:43 -07006450 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08006451 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006452 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08006453 RecordTrack::appendDumpHeader(result);
6454 for (size_t i = 0; i < numtracks ; ++i) {
6455 sp<RecordTrack> track = mTracks[i];
6456 if (track != 0) {
6457 bool active = mActiveTracks.indexOf(track) >= 0;
6458 if (active) {
6459 numactiveseen++;
6460 }
6461 track->dump(buffer, SIZE, active);
6462 result.append(buffer);
6463 }
Eric Laurent81784c32012-11-19 14:55:58 -08006464 }
Marco Nelissenb2208842014-02-07 14:00:50 -08006465 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006466 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006467 }
6468
Marco Nelissenb2208842014-02-07 14:00:50 -08006469 if (numactiveseen != numactive) {
6470 snprintf(buffer, SIZE, " The following tracks are in the active list but"
6471 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006472 result.append(buffer);
6473 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08006474 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08006475 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08006476 if (mTracks.indexOf(track) < 0) {
6477 track->dump(buffer, SIZE, true);
6478 result.append(buffer);
6479 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006480 }
Eric Laurent81784c32012-11-19 14:55:58 -08006481
6482 }
6483 write(fd, result.string(), result.size());
6484}
6485
Andy Hung73c02e42015-03-29 01:13:58 -07006486
6487void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
6488{
6489 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6490 RecordThread *recordThread = (RecordThread *) threadBase.get();
6491 mRsmpInFront = recordThread->mRsmpInRear;
6492 mRsmpInUnrel = 0;
6493}
6494
6495void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
6496 size_t *framesAvailable, bool *hasOverrun)
6497{
6498 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6499 RecordThread *recordThread = (RecordThread *) threadBase.get();
6500 const int32_t rear = recordThread->mRsmpInRear;
6501 const int32_t front = mRsmpInFront;
6502 const ssize_t filled = rear - front;
6503
6504 size_t framesIn;
6505 bool overrun = false;
6506 if (filled < 0) {
6507 // should not happen, but treat like a massive overrun and re-sync
6508 framesIn = 0;
6509 mRsmpInFront = rear;
6510 overrun = true;
6511 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
6512 framesIn = (size_t) filled;
6513 } else {
6514 // client is not keeping up with server, but give it latest data
6515 framesIn = recordThread->mRsmpInFrames;
6516 mRsmpInFront = /* front = */ rear - framesIn;
6517 overrun = true;
6518 }
6519 if (framesAvailable != NULL) {
6520 *framesAvailable = framesIn;
6521 }
6522 if (hasOverrun != NULL) {
6523 *hasOverrun = overrun;
6524 }
6525}
6526
Eric Laurent81784c32012-11-19 14:55:58 -08006527// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006528status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
6529 AudioBufferProvider::Buffer* buffer, int64_t pts __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006530{
Andy Hung73c02e42015-03-29 01:13:58 -07006531 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006532 if (threadBase == 0) {
6533 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006534 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006535 return NOT_ENOUGH_DATA;
6536 }
6537 RecordThread *recordThread = (RecordThread *) threadBase.get();
6538 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07006539 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07006540 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006541 // FIXME should not be P2 (don't want to increase latency)
6542 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006543 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07006544 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006545 front &= recordThread->mRsmpInFramesP2 - 1;
6546 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07006547 if (part1 > (size_t) filled) {
6548 part1 = filled;
6549 }
6550 size_t ask = buffer->frameCount;
6551 ALOG_ASSERT(ask > 0);
6552 if (part1 > ask) {
6553 part1 = ask;
6554 }
6555 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07006556 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07006557 buffer->raw = NULL;
6558 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07006559 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07006560 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08006561 }
6562
Andy Hung57446612015-04-19 23:56:46 -07006563 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07006564 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07006565 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08006566 return NO_ERROR;
6567}
6568
6569// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006570void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
6571 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006572{
Glenn Kasten85948432013-08-19 12:09:05 -07006573 size_t stepCount = buffer->frameCount;
6574 if (stepCount == 0) {
6575 return;
6576 }
Andy Hung73c02e42015-03-29 01:13:58 -07006577 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
6578 mRsmpInUnrel -= stepCount;
6579 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07006580 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006581 buffer->frameCount = 0;
6582}
6583
Andy Hung97a893e2015-03-29 01:03:07 -07006584AudioFlinger::RecordThread::RecordBufferConverter::RecordBufferConverter(
6585 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6586 uint32_t srcSampleRate,
6587 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6588 uint32_t dstSampleRate) :
6589 mSrcChannelMask(AUDIO_CHANNEL_INVALID), // updateParameters will set following vars
6590 // mSrcFormat
6591 // mSrcSampleRate
6592 // mDstChannelMask
6593 // mDstFormat
6594 // mDstSampleRate
6595 // mSrcChannelCount
6596 // mDstChannelCount
6597 // mDstFrameSize
6598 mBuf(NULL), mBufFrames(0), mBufFrameSize(0),
Andy Hungd330ee42015-04-20 13:23:41 -07006599 mResampler(NULL),
6600 mIsLegacyDownmix(false),
6601 mIsLegacyUpmix(false),
6602 mRequiresFloat(false),
6603 mInputConverterProvider(NULL)
Andy Hung97a893e2015-03-29 01:03:07 -07006604{
6605 (void)updateParameters(srcChannelMask, srcFormat, srcSampleRate,
6606 dstChannelMask, dstFormat, dstSampleRate);
6607}
6608
6609AudioFlinger::RecordThread::RecordBufferConverter::~RecordBufferConverter() {
6610 free(mBuf);
6611 delete mResampler;
Andy Hungd330ee42015-04-20 13:23:41 -07006612 delete mInputConverterProvider;
Andy Hung97a893e2015-03-29 01:03:07 -07006613}
6614
6615size_t AudioFlinger::RecordThread::RecordBufferConverter::convert(void *dst,
6616 AudioBufferProvider *provider, size_t frames)
6617{
Andy Hungd330ee42015-04-20 13:23:41 -07006618 if (mInputConverterProvider != NULL) {
6619 mInputConverterProvider->setBufferProvider(provider);
6620 provider = mInputConverterProvider;
6621 }
6622
6623 if (mResampler == NULL) {
Andy Hung97a893e2015-03-29 01:03:07 -07006624 ALOGVV("NO RESAMPLING sampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6625 mSrcSampleRate, mSrcFormat, mDstFormat);
6626
6627 AudioBufferProvider::Buffer buffer;
6628 for (size_t i = frames; i > 0; ) {
6629 buffer.frameCount = i;
6630 status_t status = provider->getNextBuffer(&buffer, 0);
6631 if (status != OK || buffer.frameCount == 0) {
6632 frames -= i; // cannot fill request.
6633 break;
6634 }
Andy Hungd330ee42015-04-20 13:23:41 -07006635 // format convert to destination buffer
6636 convertNoResampler(dst, buffer.raw, buffer.frameCount);
Andy Hung97a893e2015-03-29 01:03:07 -07006637
6638 dst = (int8_t*)dst + buffer.frameCount * mDstFrameSize;
6639 i -= buffer.frameCount;
6640 provider->releaseBuffer(&buffer);
6641 }
6642 } else {
6643 ALOGVV("RESAMPLING mSrcSampleRate:%u mDstSampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6644 mSrcSampleRate, mDstSampleRate, mSrcFormat, mDstFormat);
6645
Andy Hungd330ee42015-04-20 13:23:41 -07006646 // reallocate buffer if needed
6647 if (mBufFrameSize != 0 && mBufFrames < frames) {
6648 free(mBuf);
6649 mBufFrames = frames;
6650 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
6651 }
Andy Hung97a893e2015-03-29 01:03:07 -07006652 // resampler accumulates, but we only have one source track
Andy Hungd330ee42015-04-20 13:23:41 -07006653 memset(mBuf, 0, frames * mBufFrameSize);
6654 frames = mResampler->resample((int32_t*)mBuf, frames, provider);
6655 // format convert to destination buffer
6656 convertResampler(dst, mBuf, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006657 }
6658 return frames;
6659}
6660
6661status_t AudioFlinger::RecordThread::RecordBufferConverter::updateParameters(
6662 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6663 uint32_t srcSampleRate,
6664 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6665 uint32_t dstSampleRate)
6666{
6667 // quick evaluation if there is any change.
6668 if (mSrcFormat == srcFormat
6669 && mSrcChannelMask == srcChannelMask
6670 && mSrcSampleRate == srcSampleRate
6671 && mDstFormat == dstFormat
6672 && mDstChannelMask == dstChannelMask
6673 && mDstSampleRate == dstSampleRate) {
6674 return NO_ERROR;
6675 }
6676
Andy Hungdb4c0312015-05-06 08:46:52 -07006677 ALOGV("RecordBufferConverter updateParameters srcMask:%#x dstMask:%#x"
6678 " srcFormat:%#x dstFormat:%#x srcRate:%u dstRate:%u",
6679 srcChannelMask, dstChannelMask, srcFormat, dstFormat, srcSampleRate, dstSampleRate);
Andy Hung97a893e2015-03-29 01:03:07 -07006680 const bool valid =
6681 audio_is_input_channel(srcChannelMask)
6682 && audio_is_input_channel(dstChannelMask)
6683 && audio_is_valid_format(srcFormat) && audio_is_linear_pcm(srcFormat)
6684 && audio_is_valid_format(dstFormat) && audio_is_linear_pcm(dstFormat)
6685 && (srcSampleRate <= dstSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX)
6686 ; // no upsampling checks for now
6687 if (!valid) {
6688 return BAD_VALUE;
6689 }
6690
6691 mSrcFormat = srcFormat;
6692 mSrcChannelMask = srcChannelMask;
6693 mSrcSampleRate = srcSampleRate;
6694 mDstFormat = dstFormat;
6695 mDstChannelMask = dstChannelMask;
6696 mDstSampleRate = dstSampleRate;
6697
6698 // compute derived parameters
6699 mSrcChannelCount = audio_channel_count_from_in_mask(srcChannelMask);
6700 mDstChannelCount = audio_channel_count_from_in_mask(dstChannelMask);
6701 mDstFrameSize = mDstChannelCount * audio_bytes_per_sample(mDstFormat);
6702
Andy Hungd330ee42015-04-20 13:23:41 -07006703 // do we need to resample?
6704 delete mResampler;
6705 mResampler = NULL;
6706 if (mSrcSampleRate != mDstSampleRate) {
6707 mResampler = AudioResampler::create(AUDIO_FORMAT_PCM_FLOAT,
6708 mSrcChannelCount, mDstSampleRate);
6709 mResampler->setSampleRate(mSrcSampleRate);
6710 mResampler->setVolume(AudioMixer::UNITY_GAIN_FLOAT, AudioMixer::UNITY_GAIN_FLOAT);
6711 }
6712
6713 // are we running legacy channel conversion modes?
6714 mIsLegacyDownmix = (mSrcChannelMask == AUDIO_CHANNEL_IN_STEREO
6715 || mSrcChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK)
6716 && mDstChannelMask == AUDIO_CHANNEL_IN_MONO;
6717 mIsLegacyUpmix = mSrcChannelMask == AUDIO_CHANNEL_IN_MONO
6718 && (mDstChannelMask == AUDIO_CHANNEL_IN_STEREO
6719 || mDstChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK);
6720
6721 // do we need to process in float?
6722 mRequiresFloat = mResampler != NULL || mIsLegacyDownmix || mIsLegacyUpmix;
6723
6724 // do we need a staging buffer to convert for destination (we can still optimize this)?
6725 // we use mBufFrameSize > 0 to indicate both frame size as well as buffer necessity
6726 if (mResampler != NULL) {
6727 mBufFrameSize = max(mSrcChannelCount, FCC_2)
6728 * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
Andy Hunga97630b2015-07-22 23:27:24 -07006729 } else if (mIsLegacyUpmix || mIsLegacyDownmix) { // legacy modes always float
Andy Hungd330ee42015-04-20 13:23:41 -07006730 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
6731 } else if (mSrcChannelMask != mDstChannelMask && mDstFormat != mSrcFormat) {
Andy Hung97a893e2015-03-29 01:03:07 -07006732 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(mSrcFormat);
6733 } else {
6734 mBufFrameSize = 0;
6735 }
6736 mBufFrames = 0; // force the buffer to be resized.
6737
Andy Hungd330ee42015-04-20 13:23:41 -07006738 // do we need an input converter buffer provider to give us float?
6739 delete mInputConverterProvider;
6740 mInputConverterProvider = NULL;
6741 if (mRequiresFloat && mSrcFormat != AUDIO_FORMAT_PCM_FLOAT) {
6742 mInputConverterProvider = new ReformatBufferProvider(
6743 audio_channel_count_from_in_mask(mSrcChannelMask),
6744 mSrcFormat,
6745 AUDIO_FORMAT_PCM_FLOAT,
6746 256 /* provider buffer frame count */);
6747 }
6748
6749 // do we need a remixer to do channel mask conversion
6750 if (!mIsLegacyDownmix && !mIsLegacyUpmix && mSrcChannelMask != mDstChannelMask) {
6751 (void) memcpy_by_index_array_initialization_from_channel_mask(
6752 mIdxAry, ARRAY_SIZE(mIdxAry), mDstChannelMask, mSrcChannelMask);
Andy Hung97a893e2015-03-29 01:03:07 -07006753 }
6754 return NO_ERROR;
6755}
6756
Andy Hungd330ee42015-04-20 13:23:41 -07006757void AudioFlinger::RecordThread::RecordBufferConverter::convertNoResampler(
6758 void *dst, const void *src, size_t frames)
Andy Hung97a893e2015-03-29 01:03:07 -07006759{
Andy Hungd330ee42015-04-20 13:23:41 -07006760 // src is native type unless there is legacy upmix or downmix, whereupon it is float.
Andy Hung97a893e2015-03-29 01:03:07 -07006761 if (mBufFrameSize != 0 && mBufFrames < frames) {
6762 free(mBuf);
6763 mBufFrames = frames;
6764 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
6765 }
Andy Hungd330ee42015-04-20 13:23:41 -07006766 // do we need to do legacy upmix and downmix?
6767 if (mIsLegacyUpmix || mIsLegacyDownmix) {
Andy Hung97a893e2015-03-29 01:03:07 -07006768 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07006769 if (mIsLegacyUpmix) {
6770 upmix_to_stereo_float_from_mono_float((float *)dstBuf,
6771 (const float *)src, frames);
6772 } else /*mIsLegacyDownmix */ {
6773 downmix_to_mono_float_from_stereo_float((float *)dstBuf,
6774 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006775 }
Andy Hungd330ee42015-04-20 13:23:41 -07006776 if (mBuf != NULL) {
6777 memcpy_by_audio_format(dst, mDstFormat, mBuf, AUDIO_FORMAT_PCM_FLOAT,
6778 frames * mDstChannelCount);
6779 }
6780 return;
6781 }
6782 // do we need to do channel mask conversion?
6783 if (mSrcChannelMask != mDstChannelMask) {
Andy Hung97a893e2015-03-29 01:03:07 -07006784 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07006785 memcpy_by_index_array(dstBuf, mDstChannelCount,
6786 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mSrcFormat), frames);
6787 if (dstBuf == dst) {
6788 return; // format is the same
6789 }
6790 }
6791 // convert to destination buffer
6792 const void *convertBuf = mBuf != NULL ? mBuf : src;
6793 memcpy_by_audio_format(dst, mDstFormat, convertBuf, mSrcFormat,
6794 frames * mDstChannelCount);
6795}
6796
6797void AudioFlinger::RecordThread::RecordBufferConverter::convertResampler(
6798 void *dst, /*not-a-const*/ void *src, size_t frames)
6799{
6800 // src buffer format is ALWAYS float when entering this routine
6801 if (mIsLegacyUpmix) {
6802 ; // mono to stereo already handled by resampler
6803 } else if (mIsLegacyDownmix
6804 || (mSrcChannelMask == mDstChannelMask && mSrcChannelCount == 1)) {
6805 // the resampler outputs stereo for mono input channel (a feature?)
6806 // must convert to mono
6807 downmix_to_mono_float_from_stereo_float((float *)src,
6808 (const float *)src, frames);
6809 } else if (mSrcChannelMask != mDstChannelMask) {
6810 // convert to mono channel again for channel mask conversion (could be skipped
6811 // with further optimization).
Andy Hung97a893e2015-03-29 01:03:07 -07006812 if (mSrcChannelCount == 1) {
Andy Hungd330ee42015-04-20 13:23:41 -07006813 downmix_to_mono_float_from_stereo_float((float *)src,
6814 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006815 }
Andy Hungd330ee42015-04-20 13:23:41 -07006816 // convert to destination format (in place, OK as float is larger than other types)
6817 if (mDstFormat != AUDIO_FORMAT_PCM_FLOAT) {
6818 memcpy_by_audio_format(src, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
6819 frames * mSrcChannelCount);
6820 }
6821 // channel convert and save to dst
6822 memcpy_by_index_array(dst, mDstChannelCount,
6823 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mDstFormat), frames);
6824 return;
Andy Hung97a893e2015-03-29 01:03:07 -07006825 }
Andy Hungd330ee42015-04-20 13:23:41 -07006826 // convert to destination format and save to dst
6827 memcpy_by_audio_format(dst, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
6828 frames * mDstChannelCount);
Andy Hung97a893e2015-03-29 01:03:07 -07006829}
6830
Eric Laurent10351942014-05-08 18:49:52 -07006831bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
6832 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006833{
6834 bool reconfig = false;
6835
Eric Laurent10351942014-05-08 18:49:52 -07006836 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006837
Eric Laurent10351942014-05-08 18:49:52 -07006838 audio_format_t reqFormat = mFormat;
6839 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07006840 // 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 -07006841 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
6842
6843 AudioParameter param = AudioParameter(keyValuePair);
6844 int value;
6845 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
6846 // channel count change can be requested. Do we mandate the first client defines the
6847 // HAL sampling rate and channel count or do we allow changes on the fly?
6848 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6849 samplingRate = value;
6850 reconfig = true;
6851 }
6852 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07006853 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07006854 status = BAD_VALUE;
6855 } else {
6856 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08006857 reconfig = true;
6858 }
Eric Laurent10351942014-05-08 18:49:52 -07006859 }
6860 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
6861 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07006862 if (!audio_is_input_channel(mask) ||
6863 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07006864 status = BAD_VALUE;
6865 } else {
6866 channelMask = mask;
6867 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006868 }
Eric Laurent10351942014-05-08 18:49:52 -07006869 }
6870 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6871 // do not accept frame count changes if tracks are open as the track buffer
6872 // size depends on frame count and correct behavior would not be guaranteed
6873 // if frame count is changed after track creation
6874 if (mActiveTracks.size() > 0) {
6875 status = INVALID_OPERATION;
6876 } else {
6877 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006878 }
Eric Laurent10351942014-05-08 18:49:52 -07006879 }
6880 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6881 // forward device change to effects that have requested to be
6882 // aware of attached audio device.
6883 for (size_t i = 0; i < mEffectChains.size(); i++) {
6884 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08006885 }
Eric Laurent81784c32012-11-19 14:55:58 -08006886
Eric Laurent10351942014-05-08 18:49:52 -07006887 // store input device and output device but do not forward output device to audio HAL.
6888 // Note that status is ignored by the caller for output device
6889 // (see AudioFlinger::setParameters()
6890 if (audio_is_output_devices(value)) {
6891 mOutDevice = value;
6892 status = BAD_VALUE;
6893 } else {
6894 mInDevice = value;
Eric Laurente8726fe2015-06-26 09:39:24 -07006895 if (value != AUDIO_DEVICE_NONE) {
6896 mPrevInDevice = value;
6897 }
Eric Laurent10351942014-05-08 18:49:52 -07006898 // disable AEC and NS if the device is a BT SCO headset supporting those
6899 // pre processings
6900 if (mTracks.size() > 0) {
6901 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6902 mAudioFlinger->btNrecIsOff();
6903 for (size_t i = 0; i < mTracks.size(); i++) {
6904 sp<RecordTrack> track = mTracks[i];
6905 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
6906 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08006907 }
6908 }
6909 }
Eric Laurent10351942014-05-08 18:49:52 -07006910 }
6911 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
6912 mAudioSource != (audio_source_t)value) {
6913 // forward device change to effects that have requested to be
6914 // aware of attached audio device.
6915 for (size_t i = 0; i < mEffectChains.size(); i++) {
6916 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08006917 }
Eric Laurent10351942014-05-08 18:49:52 -07006918 mAudioSource = (audio_source_t)value;
6919 }
Glenn Kastene198c362013-08-13 09:13:36 -07006920
Eric Laurent10351942014-05-08 18:49:52 -07006921 if (status == NO_ERROR) {
6922 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6923 keyValuePair.string());
6924 if (status == INVALID_OPERATION) {
6925 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006926 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6927 keyValuePair.string());
Eric Laurent10351942014-05-08 18:49:52 -07006928 }
6929 if (reconfig) {
6930 if (status == BAD_VALUE &&
Andy Hung97a893e2015-03-29 01:03:07 -07006931 audio_is_linear_pcm(mInput->stream->common.get_format(&mInput->stream->common)) &&
6932 audio_is_linear_pcm(reqFormat) &&
Eric Laurent10351942014-05-08 18:49:52 -07006933 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
Andy Hung97a893e2015-03-29 01:03:07 -07006934 <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate)) &&
Andy Hunge5412692014-05-16 11:25:07 -07006935 audio_channel_count_from_in_mask(
Andy Hungd1abb8f2015-05-05 23:42:34 -07006936 mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07006937 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006938 }
Eric Laurent10351942014-05-08 18:49:52 -07006939 if (status == NO_ERROR) {
6940 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07006941 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08006942 }
6943 }
Eric Laurent81784c32012-11-19 14:55:58 -08006944 }
Eric Laurent10351942014-05-08 18:49:52 -07006945
Eric Laurent81784c32012-11-19 14:55:58 -08006946 return reconfig;
6947}
6948
6949String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6950{
Eric Laurent81784c32012-11-19 14:55:58 -08006951 Mutex::Autolock _l(mLock);
6952 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07006953 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08006954 }
6955
Glenn Kastend8ea6992013-07-16 14:17:15 -07006956 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
6957 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08006958 free(s);
6959 return out_s8;
6960}
6961
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07006962void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07006963 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
6964
6965 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08006966
6967 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07006968 case AUDIO_INPUT_OPENED:
6969 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07006970 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07006971 desc->mChannelMask = mChannelMask;
6972 desc->mSamplingRate = mSampleRate;
6973 desc->mFormat = mFormat;
6974 desc->mFrameCount = mFrameCount;
6975 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006976 break;
6977
Eric Laurent73e26b62015-04-27 16:55:58 -07006978 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08006979 default:
6980 break;
6981 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07006982 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08006983}
6984
Glenn Kastendeca2ae2014-02-07 10:25:56 -08006985void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006986{
Eric Laurent81784c32012-11-19 14:55:58 -08006987 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
6988 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Andy Hunge5412692014-05-16 11:25:07 -07006989 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Andy Hungd330ee42015-04-20 13:23:41 -07006990 if (mChannelCount > FCC_8) {
6991 ALOGE("HAL channel count %d > %d", mChannelCount, FCC_8);
6992 }
Andy Hung463be252014-07-10 16:56:07 -07006993 mHALFormat = mInput->stream->common.get_format(&mInput->stream->common);
6994 mFormat = mHALFormat;
Andy Hungd330ee42015-04-20 13:23:41 -07006995 if (!audio_is_linear_pcm(mFormat)) {
6996 ALOGE("HAL format %#x is not linear pcm", mFormat);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07006997 }
Eric Laurent665470b2014-07-03 16:37:08 -07006998 mFrameSize = audio_stream_in_frame_size(mInput->stream);
Glenn Kasten548efc92012-11-29 08:48:51 -08006999 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
7000 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007001 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08007002 // 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 -07007003 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08007004 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007005 // A larger value should allow more old data to be read after a track calls start(),
7006 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07007007 //
7008 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08007009 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07007010 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07007011 free(mRsmpInBuffer);
Andy Hung0a01c2f2015-09-21 12:44:54 -07007012 mRsmpInBuffer = NULL;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007013
7014 // TODO optimize audio capture buffer sizes ...
7015 // Here we calculate the size of the sliding buffer used as a source
7016 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
7017 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
7018 // be better to have it derived from the pipe depth in the long term.
7019 // The current value is higher than necessary. However it should not add to latency.
7020
Glenn Kasten85948432013-08-19 12:09:05 -07007021 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Andy Hung0a01c2f2015-09-21 12:44:54 -07007022 size_t bufferSize = (mRsmpInFramesP2 + mFrameCount - 1) * mFrameSize;
7023 (void)posix_memalign(&mRsmpInBuffer, 32, bufferSize);
7024 memset(mRsmpInBuffer, 0, bufferSize); // if posix_memalign fails, will segv here.
Eric Laurent81784c32012-11-19 14:55:58 -08007025
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007026 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
7027 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08007028}
7029
Glenn Kasten5f972c02014-01-13 09:59:31 -08007030uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08007031{
7032 Mutex::Autolock _l(mLock);
7033 if (initCheck() != NO_ERROR) {
7034 return 0;
7035 }
7036
7037 return mInput->stream->get_input_frames_lost(mInput->stream);
7038}
7039
7040uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
7041{
7042 Mutex::Autolock _l(mLock);
7043 uint32_t result = 0;
7044 if (getEffectChain_l(sessionId) != 0) {
7045 result = EFFECT_SESSION;
7046 }
7047
7048 for (size_t i = 0; i < mTracks.size(); ++i) {
7049 if (sessionId == mTracks[i]->sessionId()) {
7050 result |= TRACK_SESSION;
7051 break;
7052 }
7053 }
7054
7055 return result;
7056}
7057
7058KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
7059{
7060 KeyedVector<int, bool> ids;
7061 Mutex::Autolock _l(mLock);
7062 for (size_t j = 0; j < mTracks.size(); ++j) {
7063 sp<RecordThread::RecordTrack> track = mTracks[j];
7064 int sessionId = track->sessionId();
7065 if (ids.indexOfKey(sessionId) < 0) {
7066 ids.add(sessionId, true);
7067 }
7068 }
7069 return ids;
7070}
7071
7072AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
7073{
7074 Mutex::Autolock _l(mLock);
7075 AudioStreamIn *input = mInput;
7076 mInput = NULL;
7077 return input;
7078}
7079
7080// this method must always be called either with ThreadBase mLock held or inside the thread loop
7081audio_stream_t* AudioFlinger::RecordThread::stream() const
7082{
7083 if (mInput == NULL) {
7084 return NULL;
7085 }
7086 return &mInput->stream->common;
7087}
7088
7089status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7090{
7091 // only one chain per input thread
7092 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07007093 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08007094 return INVALID_OPERATION;
7095 }
7096 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07007097 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08007098 chain->setInBuffer(NULL);
7099 chain->setOutBuffer(NULL);
7100
7101 checkSuspendOnAddEffectChain_l(chain);
7102
Eric Laurent1b928682014-10-02 19:41:47 -07007103 // make sure enabled pre processing effects state is communicated to the HAL as we
7104 // just moved them to a new input stream.
7105 chain->syncHalEffectsState();
7106
Eric Laurent81784c32012-11-19 14:55:58 -08007107 mEffectChains.add(chain);
7108
7109 return NO_ERROR;
7110}
7111
7112size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7113{
7114 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
7115 ALOGW_IF(mEffectChains.size() != 1,
7116 "removeEffectChain_l() %p invalid chain size %d on thread %p",
7117 chain.get(), mEffectChains.size(), this);
7118 if (mEffectChains.size() == 1) {
7119 mEffectChains.removeAt(0);
7120 }
7121 return 0;
7122}
7123
Eric Laurent1c333e22014-05-20 10:48:17 -07007124status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
7125 audio_patch_handle_t *handle)
7126{
7127 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007128
7129 // store new device and send to effects
7130 mInDevice = patch->sources[0].ext.device.type;
Eric Laurent296fb132015-05-01 11:38:42 -07007131 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07007132 for (size_t i = 0; i < mEffectChains.size(); i++) {
7133 mEffectChains[i]->setDevice_l(mInDevice);
7134 }
7135
7136 // disable AEC and NS if the device is a BT SCO headset supporting those
7137 // pre processings
7138 if (mTracks.size() > 0) {
7139 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7140 mAudioFlinger->btNrecIsOff();
7141 for (size_t i = 0; i < mTracks.size(); i++) {
7142 sp<RecordTrack> track = mTracks[i];
7143 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7144 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
7145 }
7146 }
7147
7148 // store new source and send to effects
7149 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7150 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07007151 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07007152 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07007153 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007154 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007155
Eric Laurent054d9d32015-04-24 08:48:48 -07007156 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007157 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
7158 status = hwDevice->create_audio_patch(hwDevice,
7159 patch->num_sources,
7160 patch->sources,
7161 patch->num_sinks,
7162 patch->sinks,
7163 handle);
7164 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007165 char *address;
7166 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
7167 address = audio_device_address_to_parameter(
7168 patch->sources[0].ext.device.type,
7169 patch->sources[0].ext.device.address);
7170 } else {
7171 address = (char *)calloc(1, 1);
7172 }
7173 AudioParameter param = AudioParameter(String8(address));
7174 free(address);
7175 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING),
7176 (int)patch->sources[0].ext.device.type);
7177 param.addInt(String8(AUDIO_PARAMETER_STREAM_INPUT_SOURCE),
7178 (int)patch->sinks[0].ext.mix.usecase.source);
7179 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7180 param.toString().string());
7181 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07007182 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007183
Eric Laurente8726fe2015-06-26 09:39:24 -07007184 if (mInDevice != mPrevInDevice) {
7185 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
7186 mPrevInDevice = mInDevice;
7187 }
Eric Laurent296fb132015-05-01 11:38:42 -07007188
Eric Laurent1c333e22014-05-20 10:48:17 -07007189 return status;
7190}
7191
7192status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
7193{
7194 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007195
7196 mInDevice = AUDIO_DEVICE_NONE;
7197
Eric Laurent1c333e22014-05-20 10:48:17 -07007198 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
7199 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
7200 status = hwDevice->release_audio_patch(hwDevice, handle);
7201 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007202 AudioParameter param;
7203 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
7204 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7205 param.toString().string());
Eric Laurent1c333e22014-05-20 10:48:17 -07007206 }
7207 return status;
7208}
7209
Eric Laurent83b88082014-06-20 18:31:16 -07007210void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
7211{
7212 Mutex::Autolock _l(mLock);
7213 mTracks.add(record);
7214}
7215
7216void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
7217{
7218 Mutex::Autolock _l(mLock);
7219 destroyTrack_l(record);
7220}
7221
7222void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
7223{
7224 ThreadBase::getAudioPortConfig(config);
7225 config->role = AUDIO_PORT_ROLE_SINK;
7226 config->ext.mix.hw_module = mInput->audioHwDev->handle();
7227 config->ext.mix.usecase.source = mAudioSource;
7228}
Eric Laurent1c333e22014-05-20 10:48:17 -07007229
Glenn Kasten63238ef2015-03-02 15:50:29 -08007230} // namespace android