blob: 8ae798cc24474278f618d0c217afc9d6f078a05e [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
Eric Laurent81784c32012-11-19 14:55:58 -080056#include "AudioFlinger.h"
57#include "AudioMixer.h"
Andy Hungd330ee42015-04-20 13:23:41 -070058#include "BufferProviders.h"
Eric Laurent81784c32012-11-19 14:55:58 -080059#include "FastMixer.h"
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070060#include "FastCapture.h"
Eric Laurent81784c32012-11-19 14:55:58 -080061#include "ServiceUtilities.h"
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -070062#include "mediautils/SchedulingPolicyService.h"
Eric Laurent81784c32012-11-19 14:55:58 -080063
Eric Laurent81784c32012-11-19 14:55:58 -080064#ifdef ADD_BATTERY_DATA
65#include <media/IMediaPlayerService.h>
66#include <media/IMediaDeathNotifier.h>
67#endif
68
Eric Laurent81784c32012-11-19 14:55:58 -080069#ifdef DEBUG_CPU_USAGE
70#include <cpustats/CentralTendencyStatistics.h>
71#include <cpustats/ThreadCpuUsage.h>
72#endif
73
74// ----------------------------------------------------------------------------
75
76// Note: the following macro is used for extremely verbose logging message. In
77// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
78// 0; but one side effect of this is to turn all LOGV's as well. Some messages
79// are so verbose that we want to suppress them even when we have ALOG_ASSERT
80// turned on. Do not uncomment the #def below unless you really know what you
81// are doing and want to see all of the extremely verbose messages.
82//#define VERY_VERY_VERBOSE_LOGGING
83#ifdef VERY_VERY_VERBOSE_LOGGING
84#define ALOGVV ALOGV
85#else
86#define ALOGVV(a...) do { } while(0)
87#endif
88
Andy Hung6770c6f2015-04-07 13:43:36 -070089// TODO: Move these macro/inlines to a header file.
Glenn Kasten49d00ad2014-07-21 11:22:03 -070090#define max(a, b) ((a) > (b) ? (a) : (b))
Andy Hung6770c6f2015-04-07 13:43:36 -070091template <typename T>
92static inline T min(const T& a, const T& b)
93{
94 return a < b ? a : b;
95}
Glenn Kasten49d00ad2014-07-21 11:22:03 -070096
Andy Hungd330ee42015-04-20 13:23:41 -070097#ifndef ARRAY_SIZE
98#define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
99#endif
100
Eric Laurent81784c32012-11-19 14:55:58 -0800101namespace android {
102
103// retry counts for buffer fill timeout
104// 50 * ~20msecs = 1 second
105static const int8_t kMaxTrackRetries = 50;
106static const int8_t kMaxTrackStartupRetries = 50;
107// allow less retry attempts on direct output thread.
108// direct outputs can be a scarce resource in audio hardware and should
109// be released as quickly as possible.
110static const int8_t kMaxTrackRetriesDirect = 2;
111
112// don't warn about blocked writes or record buffer overflows more often than this
113static const nsecs_t kWarningThrottleNs = seconds(5);
114
115// RecordThread loop sleep time upon application overrun or audio HAL read error
116static const int kRecordThreadSleepUs = 5000;
117
Eric Laurent10351942014-05-08 18:49:52 -0700118// maximum time to wait in sendConfigEvent_l() for a status to be received
119static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800120
121// minimum sleep time for the mixer thread loop when tracks are active but in underrun
122static const uint32_t kMinThreadSleepTimeUs = 5000;
123// maximum divider applied to the active sleep time in the mixer thread loop
124static const uint32_t kMaxThreadSleepTimeShift = 2;
125
Andy Hung09a50072014-02-27 14:30:47 -0800126// minimum normal sink buffer size, expressed in milliseconds rather than frames
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700127// FIXME This should be based on experimentally observed scheduling jitter
Andy Hung09a50072014-02-27 14:30:47 -0800128static const uint32_t kMinNormalSinkBufferSizeMs = 20;
129// maximum normal sink buffer size
130static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800131
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700132// minimum capture buffer size in milliseconds to _not_ need a fast capture thread
133// FIXME This should be based on experimentally observed scheduling jitter
134static const uint32_t kMinNormalCaptureBufferSizeMs = 12;
135
Eric Laurent972a1732013-09-04 09:42:59 -0700136// Offloaded output thread standby delay: allows track transition without going to standby
137static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
138
Eric Laurent81784c32012-11-19 14:55:58 -0800139// Whether to use fast mixer
140static const enum {
141 FastMixer_Never, // never initialize or use: for debugging only
142 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
143 // normal mixer multiplier is 1
144 FastMixer_Static, // initialize if needed, then use all the time if initialized,
145 // multiplier is calculated based on min & max normal mixer buffer size
146 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
147 // multiplier is calculated based on min & max normal mixer buffer size
148 // FIXME for FastMixer_Dynamic:
149 // Supporting this option will require fixing HALs that can't handle large writes.
150 // For example, one HAL implementation returns an error from a large write,
151 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
152 // We could either fix the HAL implementations, or provide a wrapper that breaks
153 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
154} kUseFastMixer = FastMixer_Static;
155
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700156// Whether to use fast capture
157static const enum {
158 FastCapture_Never, // never initialize or use: for debugging only
159 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
160 FastCapture_Static, // initialize if needed, then use all the time if initialized
161} kUseFastCapture = FastCapture_Static;
162
Eric Laurent81784c32012-11-19 14:55:58 -0800163// Priorities for requestPriority
164static const int kPriorityAudioApp = 2;
165static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700166static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800167
168// IAudioFlinger::createTrack() reports back to client the total size of shared memory area
169// for the track. The client then sub-divides this into smaller buffers for its use.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800170// Currently the client uses N-buffering by default, but doesn't tell us about the value of N.
171// So for now we just assume that client is double-buffered for fast tracks.
172// FIXME It would be better for client to tell AudioFlinger the value of N,
173// so AudioFlinger could allocate the right amount of memory.
Eric Laurent81784c32012-11-19 14:55:58 -0800174// See the client's minBufCount and mNotificationFramesAct calculations for details.
Glenn Kasten03490092014-05-27 12:30:54 -0700175
176// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800177static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800178
Glenn Kasten03490092014-05-27 12:30:54 -0700179// The minimum and maximum allowed values
180static const int kFastTrackMultiplierMin = 1;
181static const int kFastTrackMultiplierMax = 2;
182
183// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
184static int sFastTrackMultiplier = kFastTrackMultiplier;
185
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700186// See Thread::readOnlyHeap().
187// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
188// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
189// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Glenn Kasten9f81de32014-07-27 15:02:23 -0700190static const size_t kRecordThreadReadOnlyHeapSize = 0x2000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700191
Eric Laurent81784c32012-11-19 14:55:58 -0800192// ----------------------------------------------------------------------------
193
Glenn Kasten03490092014-05-27 12:30:54 -0700194static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
195
196static void sFastTrackMultiplierInit()
197{
198 char value[PROPERTY_VALUE_MAX];
199 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
200 char *endptr;
201 unsigned long ul = strtoul(value, &endptr, 0);
202 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
203 sFastTrackMultiplier = (int) ul;
204 }
205 }
206}
207
208// ----------------------------------------------------------------------------
209
Eric Laurent81784c32012-11-19 14:55:58 -0800210#ifdef ADD_BATTERY_DATA
211// To collect the amplifier usage
212static void addBatteryData(uint32_t params) {
213 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
214 if (service == NULL) {
215 // it already logged
216 return;
217 }
218
219 service->addBatteryData(params);
220}
221#endif
222
223
224// ----------------------------------------------------------------------------
225// CPU Stats
226// ----------------------------------------------------------------------------
227
228class CpuStats {
229public:
230 CpuStats();
231 void sample(const String8 &title);
232#ifdef DEBUG_CPU_USAGE
233private:
234 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
235 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
236
237 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
238
239 int mCpuNum; // thread's current CPU number
240 int mCpukHz; // frequency of thread's current CPU in kHz
241#endif
242};
243
244CpuStats::CpuStats()
245#ifdef DEBUG_CPU_USAGE
246 : mCpuNum(-1), mCpukHz(-1)
247#endif
248{
249}
250
Glenn Kasten0f11b512014-01-31 16:18:54 -0800251void CpuStats::sample(const String8 &title
252#ifndef DEBUG_CPU_USAGE
253 __unused
254#endif
255 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800256#ifdef DEBUG_CPU_USAGE
257 // get current thread's delta CPU time in wall clock ns
258 double wcNs;
259 bool valid = mCpuUsage.sampleAndEnable(wcNs);
260
261 // record sample for wall clock statistics
262 if (valid) {
263 mWcStats.sample(wcNs);
264 }
265
266 // get the current CPU number
267 int cpuNum = sched_getcpu();
268
269 // get the current CPU frequency in kHz
270 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
271
272 // check if either CPU number or frequency changed
273 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
274 mCpuNum = cpuNum;
275 mCpukHz = cpukHz;
276 // ignore sample for purposes of cycles
277 valid = false;
278 }
279
280 // if no change in CPU number or frequency, then record sample for cycle statistics
281 if (valid && mCpukHz > 0) {
282 double cycles = wcNs * cpukHz * 0.000001;
283 mHzStats.sample(cycles);
284 }
285
286 unsigned n = mWcStats.n();
287 // mCpuUsage.elapsed() is expensive, so don't call it every loop
288 if ((n & 127) == 1) {
289 long long elapsed = mCpuUsage.elapsed();
290 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
291 double perLoop = elapsed / (double) n;
292 double perLoop100 = perLoop * 0.01;
293 double perLoop1k = perLoop * 0.001;
294 double mean = mWcStats.mean();
295 double stddev = mWcStats.stddev();
296 double minimum = mWcStats.minimum();
297 double maximum = mWcStats.maximum();
298 double meanCycles = mHzStats.mean();
299 double stddevCycles = mHzStats.stddev();
300 double minCycles = mHzStats.minimum();
301 double maxCycles = mHzStats.maximum();
302 mCpuUsage.resetElapsed();
303 mWcStats.reset();
304 mHzStats.reset();
305 ALOGD("CPU usage for %s over past %.1f secs\n"
306 " (%u mixer loops at %.1f mean ms per loop):\n"
307 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
308 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
309 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
310 title.string(),
311 elapsed * .000000001, n, perLoop * .000001,
312 mean * .001,
313 stddev * .001,
314 minimum * .001,
315 maximum * .001,
316 mean / perLoop100,
317 stddev / perLoop100,
318 minimum / perLoop100,
319 maximum / perLoop100,
320 meanCycles / perLoop1k,
321 stddevCycles / perLoop1k,
322 minCycles / perLoop1k,
323 maxCycles / perLoop1k);
324
325 }
326 }
327#endif
328};
329
330// ----------------------------------------------------------------------------
331// ThreadBase
332// ----------------------------------------------------------------------------
333
Glenn Kasten97b7b752014-09-28 13:04:24 -0700334// static
335const char *AudioFlinger::ThreadBase::threadTypeToString(AudioFlinger::ThreadBase::type_t type)
336{
337 switch (type) {
338 case MIXER:
339 return "MIXER";
340 case DIRECT:
341 return "DIRECT";
342 case DUPLICATING:
343 return "DUPLICATING";
344 case RECORD:
345 return "RECORD";
346 case OFFLOAD:
347 return "OFFLOAD";
348 default:
349 return "unknown";
350 }
351}
352
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800353String8 devicesToString(audio_devices_t devices)
354{
355 static const struct mapping {
356 audio_devices_t mDevices;
357 const char * mString;
358 } mappingsOut[] = {
Glenn Kasten818da522015-12-02 13:53:26 -0800359 {AUDIO_DEVICE_OUT_EARPIECE, "EARPIECE"},
360 {AUDIO_DEVICE_OUT_SPEAKER, "SPEAKER"},
361 {AUDIO_DEVICE_OUT_WIRED_HEADSET, "WIRED_HEADSET"},
362 {AUDIO_DEVICE_OUT_WIRED_HEADPHONE, "WIRED_HEADPHONE"},
363 {AUDIO_DEVICE_OUT_BLUETOOTH_SCO, "BLUETOOTH_SCO"},
364 {AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET, "BLUETOOTH_SCO_HEADSET"},
365 {AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT, "BLUETOOTH_SCO_CARKIT"},
366 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, "BLUETOOTH_A2DP"},
367 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,"BLUETOOTH_A2DP_HEADPHONES"},
368 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER, "BLUETOOTH_A2DP_SPEAKER"},
369 {AUDIO_DEVICE_OUT_AUX_DIGITAL, "AUX_DIGITAL"},
370 {AUDIO_DEVICE_OUT_HDMI, "HDMI"},
371 {AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET,"ANLG_DOCK_HEADSET"},
372 {AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET,"DGTL_DOCK_HEADSET"},
373 {AUDIO_DEVICE_OUT_USB_ACCESSORY, "USB_ACCESSORY"},
374 {AUDIO_DEVICE_OUT_USB_DEVICE, "USB_DEVICE"},
375 {AUDIO_DEVICE_OUT_TELEPHONY_TX, "TELEPHONY_TX"},
376 {AUDIO_DEVICE_OUT_LINE, "LINE"},
377 {AUDIO_DEVICE_OUT_HDMI_ARC, "HDMI_ARC"},
378 {AUDIO_DEVICE_OUT_SPDIF, "SPDIF"},
379 {AUDIO_DEVICE_OUT_FM, "FM"},
380 {AUDIO_DEVICE_OUT_AUX_LINE, "AUX_LINE"},
381 {AUDIO_DEVICE_OUT_SPEAKER_SAFE, "SPEAKER_SAFE"},
382 {AUDIO_DEVICE_OUT_IP, "IP"},
383 {AUDIO_DEVICE_NONE, "NONE"}, // must be last
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800384 }, mappingsIn[] = {
Glenn Kasten818da522015-12-02 13:53:26 -0800385 {AUDIO_DEVICE_IN_COMMUNICATION, "COMMUNICATION"},
386 {AUDIO_DEVICE_IN_AMBIENT, "AMBIENT"},
387 {AUDIO_DEVICE_IN_BUILTIN_MIC, "BUILTIN_MIC"},
388 {AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET, "BLUETOOTH_SCO_HEADSET"},
389 {AUDIO_DEVICE_IN_WIRED_HEADSET, "WIRED_HEADSET"},
390 {AUDIO_DEVICE_IN_AUX_DIGITAL, "AUX_DIGITAL"},
391 {AUDIO_DEVICE_IN_VOICE_CALL, "VOICE_CALL"},
392 {AUDIO_DEVICE_IN_TELEPHONY_RX, "TELEPHONY_RX"},
393 {AUDIO_DEVICE_IN_BACK_MIC, "BACK_MIC"},
394 {AUDIO_DEVICE_IN_REMOTE_SUBMIX, "REMOTE_SUBMIX"},
395 {AUDIO_DEVICE_IN_ANLG_DOCK_HEADSET, "ANLG_DOCK_HEADSET"},
396 {AUDIO_DEVICE_IN_DGTL_DOCK_HEADSET, "DGTL_DOCK_HEADSET"},
397 {AUDIO_DEVICE_IN_USB_ACCESSORY, "USB_ACCESSORY"},
398 {AUDIO_DEVICE_IN_USB_DEVICE, "USB_DEVICE"},
399 {AUDIO_DEVICE_IN_FM_TUNER, "FM_TUNER"},
400 {AUDIO_DEVICE_IN_TV_TUNER, "TV_TUNER"},
401 {AUDIO_DEVICE_IN_LINE, "LINE"},
402 {AUDIO_DEVICE_IN_SPDIF, "SPDIF"},
403 {AUDIO_DEVICE_IN_BLUETOOTH_A2DP, "BLUETOOTH_A2DP"},
404 {AUDIO_DEVICE_IN_LOOPBACK, "LOOPBACK"},
405 {AUDIO_DEVICE_IN_IP, "IP"},
406 {AUDIO_DEVICE_NONE, "NONE"}, // must be last
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800407 };
408 String8 result;
409 audio_devices_t allDevices = AUDIO_DEVICE_NONE;
410 const mapping *entry;
411 if (devices & AUDIO_DEVICE_BIT_IN) {
412 devices &= ~AUDIO_DEVICE_BIT_IN;
413 entry = mappingsIn;
414 } else {
415 entry = mappingsOut;
416 }
417 for ( ; entry->mDevices != AUDIO_DEVICE_NONE; entry++) {
418 allDevices = (audio_devices_t) (allDevices | entry->mDevices);
419 if (devices & entry->mDevices) {
420 if (!result.isEmpty()) {
421 result.append("|");
422 }
423 result.append(entry->mString);
424 }
425 }
426 if (devices & ~allDevices) {
427 if (!result.isEmpty()) {
428 result.append("|");
429 }
430 result.appendFormat("0x%X", devices & ~allDevices);
431 }
432 if (result.isEmpty()) {
433 result.append(entry->mString);
434 }
435 return result;
436}
437
438String8 inputFlagsToString(audio_input_flags_t flags)
439{
440 static const struct mapping {
441 audio_input_flags_t mFlag;
442 const char * mString;
443 } mappings[] = {
Glenn Kasten818da522015-12-02 13:53:26 -0800444 {AUDIO_INPUT_FLAG_FAST, "FAST"},
445 {AUDIO_INPUT_FLAG_HW_HOTWORD, "HW_HOTWORD"},
446 {AUDIO_INPUT_FLAG_RAW, "RAW"},
447 {AUDIO_INPUT_FLAG_SYNC, "SYNC"},
448 {AUDIO_INPUT_FLAG_NONE, "NONE"}, // must be last
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800449 };
450 String8 result;
451 audio_input_flags_t allFlags = AUDIO_INPUT_FLAG_NONE;
452 const mapping *entry;
453 for (entry = mappings; entry->mFlag != AUDIO_INPUT_FLAG_NONE; entry++) {
454 allFlags = (audio_input_flags_t) (allFlags | entry->mFlag);
455 if (flags & entry->mFlag) {
456 if (!result.isEmpty()) {
457 result.append("|");
458 }
459 result.append(entry->mString);
460 }
461 }
462 if (flags & ~allFlags) {
463 if (!result.isEmpty()) {
464 result.append("|");
465 }
466 result.appendFormat("0x%X", flags & ~allFlags);
467 }
468 if (result.isEmpty()) {
469 result.append(entry->mString);
470 }
471 return result;
472}
473
474String8 outputFlagsToString(audio_output_flags_t flags)
Glenn Kasten97b7b752014-09-28 13:04:24 -0700475{
476 static const struct mapping {
477 audio_output_flags_t mFlag;
478 const char * mString;
479 } mappings[] = {
Glenn Kasten818da522015-12-02 13:53:26 -0800480 {AUDIO_OUTPUT_FLAG_DIRECT, "DIRECT"},
481 {AUDIO_OUTPUT_FLAG_PRIMARY, "PRIMARY"},
482 {AUDIO_OUTPUT_FLAG_FAST, "FAST"},
483 {AUDIO_OUTPUT_FLAG_DEEP_BUFFER, "DEEP_BUFFER"},
484 {AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,"COMPRESS_OFFLOAD"},
485 {AUDIO_OUTPUT_FLAG_NON_BLOCKING, "NON_BLOCKING"},
486 {AUDIO_OUTPUT_FLAG_HW_AV_SYNC, "HW_AV_SYNC"},
487 {AUDIO_OUTPUT_FLAG_RAW, "RAW"},
488 {AUDIO_OUTPUT_FLAG_SYNC, "SYNC"},
489 {AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO, "IEC958_NONAUDIO"},
490 {AUDIO_OUTPUT_FLAG_NONE, "NONE"}, // must be last
Glenn Kasten97b7b752014-09-28 13:04:24 -0700491 };
492 String8 result;
493 audio_output_flags_t allFlags = AUDIO_OUTPUT_FLAG_NONE;
494 const mapping *entry;
495 for (entry = mappings; entry->mFlag != AUDIO_OUTPUT_FLAG_NONE; entry++) {
496 allFlags = (audio_output_flags_t) (allFlags | entry->mFlag);
497 if (flags & entry->mFlag) {
498 if (!result.isEmpty()) {
499 result.append("|");
500 }
501 result.append(entry->mString);
502 }
503 }
504 if (flags & ~allFlags) {
505 if (!result.isEmpty()) {
506 result.append("|");
507 }
508 result.appendFormat("0x%X", flags & ~allFlags);
509 }
510 if (result.isEmpty()) {
511 result.append(entry->mString);
512 }
513 return result;
514}
515
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800516const char *sourceToString(audio_source_t source)
517{
518 switch (source) {
519 case AUDIO_SOURCE_DEFAULT: return "default";
520 case AUDIO_SOURCE_MIC: return "mic";
521 case AUDIO_SOURCE_VOICE_UPLINK: return "voice uplink";
522 case AUDIO_SOURCE_VOICE_DOWNLINK: return "voice downlink";
523 case AUDIO_SOURCE_VOICE_CALL: return "voice call";
524 case AUDIO_SOURCE_CAMCORDER: return "camcorder";
525 case AUDIO_SOURCE_VOICE_RECOGNITION: return "voice recognition";
526 case AUDIO_SOURCE_VOICE_COMMUNICATION: return "voice communication";
527 case AUDIO_SOURCE_REMOTE_SUBMIX: return "remote submix";
rago8a397d52015-12-02 11:27:57 -0800528 case AUDIO_SOURCE_UNPROCESSED: return "unprocessed";
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800529 case AUDIO_SOURCE_FM_TUNER: return "FM tuner";
530 case AUDIO_SOURCE_HOTWORD: return "hotword";
531 default: return "unknown";
532 }
533}
534
Eric Laurent81784c32012-11-19 14:55:58 -0800535AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -0700536 audio_devices_t outDevice, audio_devices_t inDevice, type_t type, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -0800537 : Thread(false /*canCallJava*/),
538 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700539 mAudioFlinger(audioFlinger),
Glenn Kasten70949c42013-08-06 07:40:12 -0700540 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800541 // are set by PlaybackThread::readOutputParameters_l() or
542 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700543 //FIXME: mStandby should be true here. Is this some kind of hack?
Eric Laurent81784c32012-11-19 14:55:58 -0800544 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700545 mPrevOutDevice(AUDIO_DEVICE_NONE), mPrevInDevice(AUDIO_DEVICE_NONE),
546 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Eric Laurent81784c32012-11-19 14:55:58 -0800547 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700548 mDeathRecipient(new PMDeathRecipient(this)),
Wei Jia3f273d12015-11-24 09:06:49 -0800549 mSystemReady(systemReady),
550 mNotifiedBatteryStart(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800551{
Eric Laurent296fb132015-05-01 11:38:42 -0700552 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800553}
554
555AudioFlinger::ThreadBase::~ThreadBase()
556{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700557 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700558 mConfigEvents.clear();
559
Eric Laurent81784c32012-11-19 14:55:58 -0800560 // do not lock the mutex in destructor
561 releaseWakeLock_l();
562 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800563 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800564 binder->unlinkToDeath(mDeathRecipient);
565 }
566}
567
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700568status_t AudioFlinger::ThreadBase::readyToRun()
569{
570 status_t status = initCheck();
571 if (status == NO_ERROR) {
572 ALOGI("AudioFlinger's thread %p ready to run", this);
573 } else {
574 ALOGE("No working audio driver found.");
575 }
576 return status;
577}
578
Eric Laurent81784c32012-11-19 14:55:58 -0800579void AudioFlinger::ThreadBase::exit()
580{
581 ALOGV("ThreadBase::exit");
582 // do any cleanup required for exit to succeed
583 preExit();
584 {
585 // This lock prevents the following race in thread (uniprocessor for illustration):
586 // if (!exitPending()) {
587 // // context switch from here to exit()
588 // // exit() calls requestExit(), what exitPending() observes
589 // // exit() calls signal(), which is dropped since no waiters
590 // // context switch back from exit() to here
591 // mWaitWorkCV.wait(...);
592 // // now thread is hung
593 // }
594 AutoMutex lock(mLock);
595 requestExit();
596 mWaitWorkCV.broadcast();
597 }
598 // When Thread::requestExitAndWait is made virtual and this method is renamed to
599 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
600 requestExitAndWait();
601}
602
603status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
604{
605 status_t status;
606
607 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
608 Mutex::Autolock _l(mLock);
609
Eric Laurent10351942014-05-08 18:49:52 -0700610 return sendSetParameterConfigEvent_l(keyValuePairs);
611}
612
613// sendConfigEvent_l() must be called with ThreadBase::mLock held
614// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
615status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
616{
617 status_t status = NO_ERROR;
618
Eric Laurent72e3f392015-05-20 14:43:50 -0700619 if (event->mRequiresSystemReady && !mSystemReady) {
620 event->mWaitStatus = false;
621 mPendingConfigEvents.add(event);
622 return status;
623 }
Eric Laurent10351942014-05-08 18:49:52 -0700624 mConfigEvents.add(event);
625 ALOGV("sendConfigEvent_l() num events %d event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800626 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700627 mLock.unlock();
628 {
629 Mutex::Autolock _l(event->mLock);
630 while (event->mWaitStatus) {
631 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
632 event->mStatus = TIMED_OUT;
633 event->mWaitStatus = false;
634 }
635 }
636 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800637 }
Eric Laurent10351942014-05-08 18:49:52 -0700638 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800639 return status;
640}
641
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700642void AudioFlinger::ThreadBase::sendIoConfigEvent(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800643{
644 Mutex::Autolock _l(mLock);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700645 sendIoConfigEvent_l(event, pid);
Eric Laurent81784c32012-11-19 14:55:58 -0800646}
647
648// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700649void AudioFlinger::ThreadBase::sendIoConfigEvent_l(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800650{
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700651 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid);
Eric Laurent10351942014-05-08 18:49:52 -0700652 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800653}
654
Eric Laurent72e3f392015-05-20 14:43:50 -0700655void AudioFlinger::ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio)
656{
657 Mutex::Autolock _l(mLock);
658 sendPrioConfigEvent_l(pid, tid, prio);
659}
660
Eric Laurent81784c32012-11-19 14:55:58 -0800661// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
662void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
663{
Eric Laurent10351942014-05-08 18:49:52 -0700664 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio);
665 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800666}
667
Eric Laurent10351942014-05-08 18:49:52 -0700668// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
669status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800670{
Andy Hung2ddee192015-12-18 17:34:44 -0800671 sp<ConfigEvent> configEvent;
672 AudioParameter param(keyValuePair);
673 int value;
674 if (param.getInt(String8(AUDIO_PARAMETER_MONO_OUTPUT), value) == NO_ERROR) {
675 setMasterMono_l(value != 0);
676 if (param.size() == 1) {
677 return NO_ERROR; // should be a solo parameter - we don't pass down
678 }
679 param.remove(String8(AUDIO_PARAMETER_MONO_OUTPUT));
680 configEvent = new SetParameterConfigEvent(param.toString());
681 } else {
682 configEvent = new SetParameterConfigEvent(keyValuePair);
683 }
Eric Laurent10351942014-05-08 18:49:52 -0700684 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700685}
686
Eric Laurent1c333e22014-05-20 10:48:17 -0700687status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
688 const struct audio_patch *patch,
689 audio_patch_handle_t *handle)
690{
691 Mutex::Autolock _l(mLock);
692 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
693 status_t status = sendConfigEvent_l(configEvent);
694 if (status == NO_ERROR) {
695 CreateAudioPatchConfigEventData *data =
696 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
697 *handle = data->mHandle;
698 }
699 return status;
700}
701
702status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
703 const audio_patch_handle_t handle)
704{
705 Mutex::Autolock _l(mLock);
706 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
707 return sendConfigEvent_l(configEvent);
708}
709
710
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700711// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700712void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700713{
Eric Laurent10351942014-05-08 18:49:52 -0700714 bool configChanged = false;
715
Eric Laurent81784c32012-11-19 14:55:58 -0800716 while (!mConfigEvents.isEmpty()) {
Eric Laurent10351942014-05-08 18:49:52 -0700717 ALOGV("processConfigEvents_l() remaining events %d", mConfigEvents.size());
718 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800719 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700720 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700721 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700722 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
723 // FIXME Need to understand why this has to be done asynchronously
724 int err = requestPriority(data->mPid, data->mTid, data->mPrio,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700725 true /*asynchronous*/);
726 if (err != 0) {
727 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700728 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700729 }
730 } break;
731 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700732 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700733 ioConfigChanged(data->mEvent, data->mPid);
Eric Laurent10351942014-05-08 18:49:52 -0700734 } break;
735 case CFG_EVENT_SET_PARAMETER: {
736 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
737 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
738 configChanged = true;
Glenn Kastend5418eb2013-08-14 13:11:06 -0700739 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700740 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700741 case CFG_EVENT_CREATE_AUDIO_PATCH: {
742 CreateAudioPatchConfigEventData *data =
743 (CreateAudioPatchConfigEventData *)event->mData.get();
744 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
745 } break;
746 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
747 ReleaseAudioPatchConfigEventData *data =
748 (ReleaseAudioPatchConfigEventData *)event->mData.get();
749 event->mStatus = releaseAudioPatch_l(data->mHandle);
750 } break;
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700751 default:
Eric Laurent10351942014-05-08 18:49:52 -0700752 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700753 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800754 }
Eric Laurent10351942014-05-08 18:49:52 -0700755 {
756 Mutex::Autolock _l(event->mLock);
757 if (event->mWaitStatus) {
758 event->mWaitStatus = false;
759 event->mCond.signal();
760 }
761 }
762 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
763 }
764
765 if (configChanged) {
766 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800767 }
Eric Laurent81784c32012-11-19 14:55:58 -0800768}
769
Marco Nelissenb2208842014-02-07 14:00:50 -0800770String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
771 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700772 const audio_channel_representation_t representation =
773 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700774
775 switch (representation) {
776 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
777 if (output) {
778 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
779 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
780 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
781 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
782 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
783 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
784 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
785 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
786 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
787 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
788 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
789 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
790 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
791 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
792 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
793 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
794 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
795 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
796 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
797 } else {
798 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
799 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
800 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
801 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
802 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
803 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
804 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
805 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
806 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
807 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
808 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
809 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
810 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
811 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
812 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
813 }
814 const int len = s.length();
815 if (len > 2) {
816 char *str = s.lockBuffer(len); // needed?
817 s.unlockBuffer(len - 2); // remove trailing ", "
818 }
819 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800820 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700821 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
822 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
823 return s;
824 default:
825 s.appendFormat("unknown mask, representation:%d bits:%#x",
826 representation, audio_channel_mask_get_bits(mask));
827 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800828 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800829}
830
Glenn Kasten0f11b512014-01-31 16:18:54 -0800831void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800832{
833 const size_t SIZE = 256;
834 char buffer[SIZE];
835 String8 result;
836
837 bool locked = AudioFlinger::dumpTryLock(mLock);
838 if (!locked) {
Glenn Kasten97b7b752014-09-28 13:04:24 -0700839 dprintf(fd, "thread %p may be deadlocked\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -0800840 }
841
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800842 dprintf(fd, " Thread name: %s\n", mThreadName);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700843 dprintf(fd, " I/O handle: %d\n", mId);
844 dprintf(fd, " TID: %d\n", getTid());
845 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700846 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700847 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700848 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat));
Elliott Hughes87cebad2014-05-22 10:14:43 -0700849 dprintf(fd, " HAL buffer size: %u bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700850 dprintf(fd, " Channel count: %u\n", mChannelCount);
851 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800852 channelMaskToString(mChannelMask, mType != RECORD).string());
Glenn Kastenf87c2f52015-08-21 08:03:57 -0700853 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat, formatToString(mFormat));
854 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700855 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800856 size_t numConfig = mConfigEvents.size();
857 if (numConfig) {
858 for (size_t i = 0; i < numConfig; i++) {
859 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700860 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800861 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700862 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800863 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700864 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800865 }
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800866 dprintf(fd, " Output device: %#x (%s)\n", mOutDevice, devicesToString(mOutDevice).string());
867 dprintf(fd, " Input device: %#x (%s)\n", mInDevice, devicesToString(mInDevice).string());
868 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, sourceToString(mAudioSource));
Eric Laurent81784c32012-11-19 14:55:58 -0800869
870 if (locked) {
871 mLock.unlock();
872 }
873}
874
875void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
876{
877 const size_t SIZE = 256;
878 char buffer[SIZE];
879 String8 result;
880
Marco Nelissenb2208842014-02-07 14:00:50 -0800881 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000882 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800883 write(fd, buffer, strlen(buffer));
884
Marco Nelissenb2208842014-02-07 14:00:50 -0800885 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800886 sp<EffectChain> chain = mEffectChains[i];
887 if (chain != 0) {
888 chain->dump(fd, args);
889 }
890 }
891}
892
Marco Nelissene14a5d62013-10-03 08:51:24 -0700893void AudioFlinger::ThreadBase::acquireWakeLock(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800894{
895 Mutex::Autolock _l(mLock);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700896 acquireWakeLock_l(uid);
Eric Laurent81784c32012-11-19 14:55:58 -0800897}
898
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100899String16 AudioFlinger::ThreadBase::getWakeLockTag()
900{
901 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -0800902 case MIXER:
903 return String16("AudioMix");
904 case DIRECT:
905 return String16("AudioDirectOut");
906 case DUPLICATING:
907 return String16("AudioDup");
908 case RECORD:
909 return String16("AudioIn");
910 case OFFLOAD:
911 return String16("AudioOffload");
912 default:
913 ALOG_ASSERT(false);
914 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100915 }
916}
917
Marco Nelissene14a5d62013-10-03 08:51:24 -0700918void AudioFlinger::ThreadBase::acquireWakeLock_l(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800919{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800920 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800921 if (mPowerManager != 0) {
922 sp<IBinder> binder = new BBinder();
Marco Nelissene14a5d62013-10-03 08:51:24 -0700923 status_t status;
924 if (uid >= 0) {
Eric Laurent547789d2013-10-04 11:46:55 -0700925 status = mPowerManager->acquireWakeLockWithUid(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700926 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100927 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -0700928 String16("audioserver"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700929 uid,
930 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700931 } else {
Eric Laurent547789d2013-10-04 11:46:55 -0700932 status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700933 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100934 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -0700935 String16("audioserver"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700936 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700937 }
Eric Laurent81784c32012-11-19 14:55:58 -0800938 if (status == NO_ERROR) {
939 mWakeLockToken = binder;
940 }
Glenn Kastend7dca052015-03-05 16:05:54 -0800941 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Eric Laurent81784c32012-11-19 14:55:58 -0800942 }
Wei Jia3f273d12015-11-24 09:06:49 -0800943
944 if (!mNotifiedBatteryStart) {
945 BatteryNotifier::getInstance().noteStartAudio();
946 mNotifiedBatteryStart = true;
947 }
Eric Laurent81784c32012-11-19 14:55:58 -0800948}
949
950void AudioFlinger::ThreadBase::releaseWakeLock()
951{
952 Mutex::Autolock _l(mLock);
953 releaseWakeLock_l();
954}
955
956void AudioFlinger::ThreadBase::releaseWakeLock_l()
957{
958 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800959 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -0800960 if (mPowerManager != 0) {
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700961 mPowerManager->releaseWakeLock(mWakeLockToken, 0,
962 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800963 }
964 mWakeLockToken.clear();
965 }
Wei Jia3f273d12015-11-24 09:06:49 -0800966
967 if (mNotifiedBatteryStart) {
968 BatteryNotifier::getInstance().noteStopAudio();
969 mNotifiedBatteryStart = false;
970 }
Eric Laurent81784c32012-11-19 14:55:58 -0800971}
972
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800973void AudioFlinger::ThreadBase::updateWakeLockUids(const SortedVector<int> &uids) {
974 Mutex::Autolock _l(mLock);
975 updateWakeLockUids_l(uids);
976}
977
978void AudioFlinger::ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -0700979 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800980 // use checkService() to avoid blocking if power service is not up yet
981 sp<IBinder> binder =
982 defaultServiceManager()->checkService(String16("power"));
983 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800984 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800985 } else {
986 mPowerManager = interface_cast<IPowerManager>(binder);
987 binder->linkToDeath(mDeathRecipient);
988 }
989 }
990}
991
992void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<int> &uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800993 getPowerManager_l();
Andy Hung438e7572015-12-14 15:51:17 -0800994 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
995 if (mSystemReady) {
996 ALOGE("no wake lock to update, but system ready!");
997 } else {
998 ALOGW("no wake lock to update, system not ready yet");
999 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001000 return;
1001 }
1002 if (mPowerManager != 0) {
1003 sp<IBinder> binder = new BBinder();
1004 status_t status;
Glenn Kasten3abc2de2014-09-05 16:45:52 -07001005 status = mPowerManager->updateWakeLockUids(mWakeLockToken, uids.size(), uids.array(),
1006 true /* FIXME force oneway contrary to .aidl */);
Glenn Kastend7dca052015-03-05 16:05:54 -08001007 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001008 }
1009}
1010
Eric Laurent81784c32012-11-19 14:55:58 -08001011void AudioFlinger::ThreadBase::clearPowerManager()
1012{
1013 Mutex::Autolock _l(mLock);
1014 releaseWakeLock_l();
1015 mPowerManager.clear();
1016}
1017
Glenn Kasten0f11b512014-01-31 16:18:54 -08001018void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001019{
1020 sp<ThreadBase> thread = mThread.promote();
1021 if (thread != 0) {
1022 thread->clearPowerManager();
1023 }
1024 ALOGW("power manager service died !!!");
1025}
1026
1027void AudioFlinger::ThreadBase::setEffectSuspended(
1028 const effect_uuid_t *type, bool suspend, int sessionId)
1029{
1030 Mutex::Autolock _l(mLock);
1031 setEffectSuspended_l(type, suspend, sessionId);
1032}
1033
1034void AudioFlinger::ThreadBase::setEffectSuspended_l(
1035 const effect_uuid_t *type, bool suspend, int sessionId)
1036{
1037 sp<EffectChain> chain = getEffectChain_l(sessionId);
1038 if (chain != 0) {
1039 if (type != NULL) {
1040 chain->setEffectSuspended_l(type, suspend);
1041 } else {
1042 chain->setEffectSuspendedAll_l(suspend);
1043 }
1044 }
1045
1046 updateSuspendedSessions_l(type, suspend, sessionId);
1047}
1048
1049void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1050{
1051 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1052 if (index < 0) {
1053 return;
1054 }
1055
1056 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1057 mSuspendedSessions.valueAt(index);
1058
1059 for (size_t i = 0; i < sessionEffects.size(); i++) {
1060 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
1061 for (int j = 0; j < desc->mRefCount; j++) {
1062 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1063 chain->setEffectSuspendedAll_l(true);
1064 } else {
1065 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1066 desc->mType.timeLow);
1067 chain->setEffectSuspended_l(&desc->mType, true);
1068 }
1069 }
1070 }
1071}
1072
1073void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1074 bool suspend,
1075 int sessionId)
1076{
1077 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1078
1079 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1080
1081 if (suspend) {
1082 if (index >= 0) {
1083 sessionEffects = mSuspendedSessions.valueAt(index);
1084 } else {
1085 mSuspendedSessions.add(sessionId, sessionEffects);
1086 }
1087 } else {
1088 if (index < 0) {
1089 return;
1090 }
1091 sessionEffects = mSuspendedSessions.valueAt(index);
1092 }
1093
1094
1095 int key = EffectChain::kKeyForSuspendAll;
1096 if (type != NULL) {
1097 key = type->timeLow;
1098 }
1099 index = sessionEffects.indexOfKey(key);
1100
1101 sp<SuspendedSessionDesc> desc;
1102 if (suspend) {
1103 if (index >= 0) {
1104 desc = sessionEffects.valueAt(index);
1105 } else {
1106 desc = new SuspendedSessionDesc();
1107 if (type != NULL) {
1108 desc->mType = *type;
1109 }
1110 sessionEffects.add(key, desc);
1111 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1112 }
1113 desc->mRefCount++;
1114 } else {
1115 if (index < 0) {
1116 return;
1117 }
1118 desc = sessionEffects.valueAt(index);
1119 if (--desc->mRefCount == 0) {
1120 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1121 sessionEffects.removeItemsAt(index);
1122 if (sessionEffects.isEmpty()) {
1123 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1124 sessionId);
1125 mSuspendedSessions.removeItem(sessionId);
1126 }
1127 }
1128 }
1129 if (!sessionEffects.isEmpty()) {
1130 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1131 }
1132}
1133
1134void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1135 bool enabled,
1136 int sessionId)
1137{
1138 Mutex::Autolock _l(mLock);
1139 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1140}
1141
1142void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1143 bool enabled,
1144 int sessionId)
1145{
1146 if (mType != RECORD) {
1147 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1148 // another session. This gives the priority to well behaved effect control panels
1149 // and applications not using global effects.
1150 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1151 // global effects
1152 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
1153 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1154 }
1155 }
1156
1157 sp<EffectChain> chain = getEffectChain_l(sessionId);
1158 if (chain != 0) {
1159 chain->checkSuspendOnEffectEnabled(effect, enabled);
1160 }
1161}
1162
1163// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1164sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1165 const sp<AudioFlinger::Client>& client,
1166 const sp<IEffectClient>& effectClient,
1167 int32_t priority,
1168 int sessionId,
1169 effect_descriptor_t *desc,
1170 int *enabled,
Glenn Kasten9156ef32013-08-06 15:39:08 -07001171 status_t *status)
Eric Laurent81784c32012-11-19 14:55:58 -08001172{
1173 sp<EffectModule> effect;
1174 sp<EffectHandle> handle;
1175 status_t lStatus;
1176 sp<EffectChain> chain;
1177 bool chainCreated = false;
1178 bool effectCreated = false;
1179 bool effectRegistered = false;
1180
1181 lStatus = initCheck();
1182 if (lStatus != NO_ERROR) {
1183 ALOGW("createEffect_l() Audio driver not initialized.");
1184 goto Exit;
1185 }
1186
Andy Hung98ef9782014-03-04 14:46:50 -08001187 // Reject any effect on Direct output threads for now, since the format of
1188 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1189 if (mType == DIRECT) {
1190 ALOGW("createEffect_l() Cannot add effect %s on Direct output type thread %s",
Glenn Kastend7dca052015-03-05 16:05:54 -08001191 desc->name, mThreadName);
Andy Hung98ef9782014-03-04 14:46:50 -08001192 lStatus = BAD_VALUE;
1193 goto Exit;
1194 }
1195
Andy Hung389cfdb2014-08-07 17:49:53 -07001196 // Reject any effect on mixer or duplicating multichannel sinks.
Andy Hung9a592762014-07-21 21:56:01 -07001197 // TODO: fix both format and multichannel issues with effects.
Andy Hung389cfdb2014-08-07 17:49:53 -07001198 if ((mType == MIXER || mType == DUPLICATING) && mChannelCount != FCC_2) {
1199 ALOGW("createEffect_l() Cannot add effect %s for multichannel(%d) %s threads",
1200 desc->name, mChannelCount, mType == MIXER ? "MIXER" : "DUPLICATING");
Andy Hung9a592762014-07-21 21:56:01 -07001201 lStatus = BAD_VALUE;
1202 goto Exit;
1203 }
1204
Eric Laurent5baf2af2013-09-12 17:37:00 -07001205 // Allow global effects only on offloaded and mixer threads
1206 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1207 switch (mType) {
1208 case MIXER:
1209 case OFFLOAD:
1210 break;
1211 case DIRECT:
1212 case DUPLICATING:
1213 case RECORD:
1214 default:
Glenn Kastend7dca052015-03-05 16:05:54 -08001215 ALOGW("createEffect_l() Cannot add global effect %s on thread %s",
1216 desc->name, mThreadName);
Eric Laurent5baf2af2013-09-12 17:37:00 -07001217 lStatus = BAD_VALUE;
1218 goto Exit;
1219 }
Eric Laurent81784c32012-11-19 14:55:58 -08001220 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07001221
Eric Laurent81784c32012-11-19 14:55:58 -08001222 // Only Pre processor effects are allowed on input threads and only on input threads
1223 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
1224 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
1225 desc->name, desc->flags, mType);
1226 lStatus = BAD_VALUE;
1227 goto Exit;
1228 }
1229
1230 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1231
1232 { // scope for mLock
1233 Mutex::Autolock _l(mLock);
1234
1235 // check for existing effect chain with the requested audio session
1236 chain = getEffectChain_l(sessionId);
1237 if (chain == 0) {
1238 // create a new chain for this session
1239 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1240 chain = new EffectChain(this, sessionId);
1241 addEffectChain_l(chain);
1242 chain->setStrategy(getStrategyForSession_l(sessionId));
1243 chainCreated = true;
1244 } else {
1245 effect = chain->getEffectFromDesc_l(desc);
1246 }
1247
1248 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1249
1250 if (effect == 0) {
1251 int id = mAudioFlinger->nextUniqueId();
1252 // Check CPU and memory usage
1253 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
1254 if (lStatus != NO_ERROR) {
1255 goto Exit;
1256 }
1257 effectRegistered = true;
1258 // create a new effect module if none present in the chain
1259 effect = new EffectModule(this, chain, desc, id, sessionId);
1260 lStatus = effect->status();
1261 if (lStatus != NO_ERROR) {
1262 goto Exit;
1263 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07001264 effect->setOffloaded(mType == OFFLOAD, mId);
1265
Eric Laurent81784c32012-11-19 14:55:58 -08001266 lStatus = chain->addEffect_l(effect);
1267 if (lStatus != NO_ERROR) {
1268 goto Exit;
1269 }
1270 effectCreated = true;
1271
1272 effect->setDevice(mOutDevice);
1273 effect->setDevice(mInDevice);
1274 effect->setMode(mAudioFlinger->getMode());
1275 effect->setAudioSource(mAudioSource);
1276 }
1277 // create effect handle and connect it to effect module
1278 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001279 lStatus = handle->initCheck();
1280 if (lStatus == OK) {
1281 lStatus = effect->addHandle(handle.get());
1282 }
Eric Laurent81784c32012-11-19 14:55:58 -08001283 if (enabled != NULL) {
1284 *enabled = (int)effect->isEnabled();
1285 }
1286 }
1287
1288Exit:
1289 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1290 Mutex::Autolock _l(mLock);
1291 if (effectCreated) {
1292 chain->removeEffect_l(effect);
1293 }
1294 if (effectRegistered) {
1295 AudioSystem::unregisterEffect(effect->id());
1296 }
1297 if (chainCreated) {
1298 removeEffectChain_l(chain);
1299 }
1300 handle.clear();
1301 }
1302
Glenn Kasten9156ef32013-08-06 15:39:08 -07001303 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001304 return handle;
1305}
1306
1307sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
1308{
1309 Mutex::Autolock _l(mLock);
1310 return getEffect_l(sessionId, effectId);
1311}
1312
1313sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
1314{
1315 sp<EffectChain> chain = getEffectChain_l(sessionId);
1316 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1317}
1318
1319// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1320// PlaybackThread::mLock held
1321status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1322{
1323 // check for existing effect chain with the requested audio session
1324 int sessionId = effect->sessionId();
1325 sp<EffectChain> chain = getEffectChain_l(sessionId);
1326 bool chainCreated = false;
1327
Eric Laurent5baf2af2013-09-12 17:37:00 -07001328 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
1329 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
1330 this, effect->desc().name, effect->desc().flags);
1331
Eric Laurent81784c32012-11-19 14:55:58 -08001332 if (chain == 0) {
1333 // create a new chain for this session
1334 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1335 chain = new EffectChain(this, sessionId);
1336 addEffectChain_l(chain);
1337 chain->setStrategy(getStrategyForSession_l(sessionId));
1338 chainCreated = true;
1339 }
1340 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1341
1342 if (chain->getEffectFromId_l(effect->id()) != 0) {
1343 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1344 this, effect->desc().name, chain.get());
1345 return BAD_VALUE;
1346 }
1347
Eric Laurent5baf2af2013-09-12 17:37:00 -07001348 effect->setOffloaded(mType == OFFLOAD, mId);
1349
Eric Laurent81784c32012-11-19 14:55:58 -08001350 status_t status = chain->addEffect_l(effect);
1351 if (status != NO_ERROR) {
1352 if (chainCreated) {
1353 removeEffectChain_l(chain);
1354 }
1355 return status;
1356 }
1357
1358 effect->setDevice(mOutDevice);
1359 effect->setDevice(mInDevice);
1360 effect->setMode(mAudioFlinger->getMode());
1361 effect->setAudioSource(mAudioSource);
1362 return NO_ERROR;
1363}
1364
1365void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
1366
1367 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
1368 effect_descriptor_t desc = effect->desc();
1369 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1370 detachAuxEffect_l(effect->id());
1371 }
1372
1373 sp<EffectChain> chain = effect->chain().promote();
1374 if (chain != 0) {
1375 // remove effect chain if removing last effect
1376 if (chain->removeEffect_l(effect) == 0) {
1377 removeEffectChain_l(chain);
1378 }
1379 } else {
1380 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1381 }
1382}
1383
1384void AudioFlinger::ThreadBase::lockEffectChains_l(
1385 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1386{
1387 effectChains = mEffectChains;
1388 for (size_t i = 0; i < mEffectChains.size(); i++) {
1389 mEffectChains[i]->lock();
1390 }
1391}
1392
1393void AudioFlinger::ThreadBase::unlockEffectChains(
1394 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1395{
1396 for (size_t i = 0; i < effectChains.size(); i++) {
1397 effectChains[i]->unlock();
1398 }
1399}
1400
1401sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
1402{
1403 Mutex::Autolock _l(mLock);
1404 return getEffectChain_l(sessionId);
1405}
1406
1407sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const
1408{
1409 size_t size = mEffectChains.size();
1410 for (size_t i = 0; i < size; i++) {
1411 if (mEffectChains[i]->sessionId() == sessionId) {
1412 return mEffectChains[i];
1413 }
1414 }
1415 return 0;
1416}
1417
1418void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1419{
1420 Mutex::Autolock _l(mLock);
1421 size_t size = mEffectChains.size();
1422 for (size_t i = 0; i < size; i++) {
1423 mEffectChains[i]->setMode_l(mode);
1424 }
1425}
1426
Eric Laurent83b88082014-06-20 18:31:16 -07001427void AudioFlinger::ThreadBase::getAudioPortConfig(struct audio_port_config *config)
1428{
1429 config->type = AUDIO_PORT_TYPE_MIX;
1430 config->ext.mix.handle = mId;
1431 config->sample_rate = mSampleRate;
1432 config->format = mFormat;
1433 config->channel_mask = mChannelMask;
1434 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1435 AUDIO_PORT_CONFIG_FORMAT;
1436}
1437
Eric Laurent72e3f392015-05-20 14:43:50 -07001438void AudioFlinger::ThreadBase::systemReady()
1439{
1440 Mutex::Autolock _l(mLock);
1441 if (mSystemReady) {
1442 return;
1443 }
1444 mSystemReady = true;
1445
1446 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1447 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1448 }
1449 mPendingConfigEvents.clear();
1450}
1451
Eric Laurent83b88082014-06-20 18:31:16 -07001452
Eric Laurent81784c32012-11-19 14:55:58 -08001453// ----------------------------------------------------------------------------
1454// Playback
1455// ----------------------------------------------------------------------------
1456
1457AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1458 AudioStreamOut* output,
1459 audio_io_handle_t id,
1460 audio_devices_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07001461 type_t type,
1462 bool systemReady)
1463 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type, systemReady),
Andy Hung2098f272014-02-27 14:00:06 -08001464 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001465 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001466 mMixerBuffer(NULL),
1467 mMixerBufferSize(0),
1468 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1469 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001470 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001471 mEffectBuffer(NULL),
1472 mEffectBufferSize(0),
1473 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1474 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001475 mSuspended(0), mBytesWritten(0),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001476 mActiveTracksGeneration(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001477 // mStreamTypes[] initialized in constructor body
1478 mOutput(output),
1479 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
1480 mMixerStatus(MIXER_IDLE),
1481 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001482 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001483 mBytesRemaining(0),
1484 mCurrentWriteLength(0),
1485 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001486 mWriteAckSequence(0),
1487 mDrainSequence(0),
Eric Laurentede6c3b2013-09-19 14:37:46 -07001488 mSignalPending(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001489 mScreenState(AudioFlinger::mScreenState),
1490 // index 0 is reserved for normal mixer's submix
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001491 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1),
Eric Laurentd1f69b02014-12-15 14:33:13 -08001492 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001493 // mLatchD, mLatchQ,
1494 mLatchDValid(false), mLatchQValid(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001495{
Glenn Kastend7dca052015-03-05 16:05:54 -08001496 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1497 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001498
1499 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1500 // it would be safer to explicitly pass initial masterVolume/masterMute as
1501 // parameter.
1502 //
1503 // If the HAL we are using has support for master volume or master mute,
1504 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1505 // and the mute set to false).
1506 mMasterVolume = audioFlinger->masterVolume_l();
1507 mMasterMute = audioFlinger->masterMute_l();
1508 if (mOutput && mOutput->audioHwDev) {
1509 if (mOutput->audioHwDev->canSetMasterVolume()) {
1510 mMasterVolume = 1.0;
1511 }
1512
1513 if (mOutput->audioHwDev->canSetMasterMute()) {
1514 mMasterMute = false;
1515 }
1516 }
1517
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001518 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001519
Eric Laurent223fd5c2014-11-11 13:43:36 -08001520 // ++ operator does not compile
Glenn Kasten66e46352014-01-16 17:44:23 -08001521 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001522 stream = (audio_stream_type_t) (stream + 1)) {
1523 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1524 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1525 }
Eric Laurent81784c32012-11-19 14:55:58 -08001526}
1527
1528AudioFlinger::PlaybackThread::~PlaybackThread()
1529{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001530 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001531 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001532 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001533 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001534}
1535
1536void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1537{
1538 dumpInternals(fd, args);
1539 dumpTracks(fd, args);
1540 dumpEffectChains(fd, args);
1541}
1542
Glenn Kasten0f11b512014-01-31 16:18:54 -08001543void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001544{
1545 const size_t SIZE = 256;
1546 char buffer[SIZE];
1547 String8 result;
1548
Marco Nelissenb2208842014-02-07 14:00:50 -08001549 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001550 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1551 const stream_type_t *st = &mStreamTypes[i];
1552 if (i > 0) {
1553 result.appendFormat(", ");
1554 }
1555 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1556 if (st->mute) {
1557 result.append("M");
1558 }
1559 }
1560 result.append("\n");
1561 write(fd, result.string(), result.length());
1562 result.clear();
1563
Eric Laurent81784c32012-11-19 14:55:58 -08001564 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1565 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001566 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001567 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001568
1569 size_t numtracks = mTracks.size();
1570 size_t numactive = mActiveTracks.size();
Elliott Hughes87cebad2014-05-22 10:14:43 -07001571 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001572 size_t numactiveseen = 0;
1573 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07001574 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08001575 Track::appendDumpHeader(result);
1576 for (size_t i = 0; i < numtracks; ++i) {
1577 sp<Track> track = mTracks[i];
1578 if (track != 0) {
1579 bool active = mActiveTracks.indexOf(track) >= 0;
1580 if (active) {
1581 numactiveseen++;
1582 }
1583 track->dump(buffer, SIZE, active);
1584 result.append(buffer);
1585 }
1586 }
1587 } else {
1588 result.append("\n");
1589 }
1590 if (numactiveseen != numactive) {
1591 // some tracks in the active list were not in the tracks list
1592 snprintf(buffer, SIZE, " The following tracks are in the active list but"
1593 " not in the track list\n");
1594 result.append(buffer);
1595 Track::appendDumpHeader(result);
1596 for (size_t i = 0; i < numactive; ++i) {
1597 sp<Track> track = mActiveTracks[i].promote();
1598 if (track != 0 && mTracks.indexOf(track) < 0) {
1599 track->dump(buffer, SIZE, true);
1600 result.append(buffer);
1601 }
1602 }
1603 }
1604
1605 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001606}
1607
1608void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1609{
Glenn Kasten97b7b752014-09-28 13:04:24 -07001610 dprintf(fd, "\nOutput thread %p type %d (%s):\n", this, type(), threadTypeToString(type()));
Glenn Kasten44182c22015-03-05 17:12:23 -08001611
1612 dumpBase(fd, args);
1613
Elliott Hughes87cebad2014-05-22 10:14:43 -07001614 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
1615 dprintf(fd, " Last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1616 dprintf(fd, " Total writes: %d\n", mNumWrites);
1617 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1618 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1619 dprintf(fd, " Suspend count: %d\n", mSuspended);
1620 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1621 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1622 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1623 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08001624 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001625 AudioStreamOut *output = mOutput;
1626 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
1627 String8 flagsAsString = outputFlagsToString(flags);
1628 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n", output, flags, flagsAsString.string());
Eric Laurent81784c32012-11-19 14:55:58 -08001629}
1630
1631// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001632
1633void AudioFlinger::PlaybackThread::onFirstRef()
1634{
Glenn Kastend7dca052015-03-05 16:05:54 -08001635 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001636}
1637
1638// ThreadBase virtuals
1639void AudioFlinger::PlaybackThread::preExit()
1640{
1641 ALOGV(" preExit()");
1642 // FIXME this is using hard-coded strings but in the future, this functionality will be
1643 // converted to use audio HAL extensions required to support tunneling
1644 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1645}
1646
1647// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1648sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1649 const sp<AudioFlinger::Client>& client,
1650 audio_stream_type_t streamType,
1651 uint32_t sampleRate,
1652 audio_format_t format,
1653 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001654 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001655 const sp<IMemory>& sharedBuffer,
1656 int sessionId,
1657 IAudioFlinger::track_flags_t *flags,
1658 pid_t tid,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001659 int uid,
Eric Laurent81784c32012-11-19 14:55:58 -08001660 status_t *status)
1661{
Glenn Kasten74935e42013-12-19 08:56:45 -08001662 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001663 sp<Track> track;
1664 status_t lStatus;
1665
Eric Laurent81784c32012-11-19 14:55:58 -08001666 // client expresses a preference for FAST, but we get the final say
1667 if (*flags & IAudioFlinger::TRACK_FAST) {
1668 if (
Eric Laurent81784c32012-11-19 14:55:58 -08001669 // either of these use cases:
1670 (
1671 // use case 1: shared buffer with any frame count
1672 (
1673 (sharedBuffer != 0)
1674 ) ||
Glenn Kasten1dfe2f92015-03-09 12:03:14 -07001675 // use case 2: frame count is default or at least as large as HAL
Eric Laurent81784c32012-11-19 14:55:58 -08001676 (
Glenn Kasten1dfe2f92015-03-09 12:03:14 -07001677 // we formerly checked for a callback handler (non-0 tid),
1678 // but that is no longer required for TRANSFER_OBTAIN mode
Eric Laurent81784c32012-11-19 14:55:58 -08001679 ((frameCount == 0) ||
Glenn Kastenb5fed682013-12-03 09:06:43 -08001680 (frameCount >= mFrameCount))
Eric Laurent81784c32012-11-19 14:55:58 -08001681 )
1682 ) &&
1683 // PCM data
1684 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07001685 // TODO: extract as a data library function that checks that a computationally
1686 // expensive downmixer is not required: isFastOutputChannelConversion()
Andy Hung9a592762014-07-21 21:56:01 -07001687 (channelMask == mChannelMask ||
Andy Hung1f439e12015-05-19 12:57:41 -07001688 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
1689 (channelMask == AUDIO_CHANNEL_OUT_MONO
1690 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001691 // hardware sample rate
1692 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001693 // normal mixer has an associated fast mixer
1694 hasFastMixer() &&
1695 // there are sufficient fast track slots available
1696 (mFastTrackAvailMask != 0)
1697 // FIXME test that MixerThread for this fast track has a capable output HAL
1698 // FIXME add a permission test also?
1699 ) {
1700 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1701 if (frameCount == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001702 // read the fast track multiplier property the first time it is needed
1703 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1704 if (ok != 0) {
1705 ALOGE("%s pthread_once failed: %d", __func__, ok);
1706 }
1707 frameCount = mFrameCount * sFastTrackMultiplier;
Eric Laurent81784c32012-11-19 14:55:58 -08001708 }
1709 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
1710 frameCount, mFrameCount);
1711 } else {
Glenn Kastend79072e2016-01-06 08:41:20 -08001712 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%d "
Andy Hung6146c082014-03-18 11:56:15 -07001713 "mFrameCount=%d format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
1714 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001715 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08001716 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001717 audio_is_linear_pcm(format),
1718 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
1719 *flags &= ~IAudioFlinger::TRACK_FAST;
Andy Hung0e48d252015-01-26 11:43:15 -08001720 }
1721 }
1722 // For normal PCM streaming tracks, update minimum frame count.
1723 // For compatibility with AudioTrack calculation, buffer depth is forced
1724 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1725 // This is probably too conservative, but legacy application code may depend on it.
1726 // If you change this calculation, also review the start threshold which is related.
1727 if (!(*flags & IAudioFlinger::TRACK_FAST)
1728 && audio_is_linear_pcm(format) && sharedBuffer == 0) {
Andy Hung8edb8dc2015-03-26 19:13:55 -07001729 // this must match AudioTrack.cpp calculateMinFrameCount().
1730 // TODO: Move to a common library
Eric Laurent81784c32012-11-19 14:55:58 -08001731 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1732 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1733 if (minBufCount < 2) {
1734 minBufCount = 2;
1735 }
Andy Hung8edb8dc2015-03-26 19:13:55 -07001736 // For normal mixing tracks, if speed is > 1.0f (normal), AudioTrack
1737 // or the client should compute and pass in a larger buffer request.
Andy Hung0e48d252015-01-26 11:43:15 -08001738 size_t minFrameCount =
Andy Hung8edb8dc2015-03-26 19:13:55 -07001739 minBufCount * sourceFramesNeededWithTimestretch(
1740 sampleRate, mNormalFrameCount,
1741 mSampleRate, AUDIO_TIMESTRETCH_SPEED_NORMAL /*speed*/);
Andy Hung0e48d252015-01-26 11:43:15 -08001742 if (frameCount < minFrameCount) { // including frameCount == 0
Eric Laurent81784c32012-11-19 14:55:58 -08001743 frameCount = minFrameCount;
1744 }
Eric Laurent81784c32012-11-19 14:55:58 -08001745 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001746 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001747
Glenn Kastenc3df8382014-03-13 15:05:25 -07001748 switch (mType) {
1749
1750 case DIRECT:
Glenn Kasten993fa062014-05-02 11:14:34 -07001751 if (audio_is_linear_pcm(format)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001752 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001753 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1754 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001755 sampleRate, format, channelMask, mOutput, mFormat);
1756 lStatus = BAD_VALUE;
1757 goto Exit;
1758 }
1759 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001760 break;
1761
1762 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001763 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001764 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1765 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001766 sampleRate, format, channelMask, mOutput, mFormat);
1767 lStatus = BAD_VALUE;
1768 goto Exit;
1769 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001770 break;
1771
1772 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07001773 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001774 ALOGE("createTrack_l() Bad parameter: format %#x \""
1775 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001776 format, mOutput, mFormat);
1777 lStatus = BAD_VALUE;
1778 goto Exit;
1779 }
Andy Hungcd044842014-08-07 11:04:34 -07001780 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08001781 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1782 lStatus = BAD_VALUE;
1783 goto Exit;
1784 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001785 break;
1786
Eric Laurent81784c32012-11-19 14:55:58 -08001787 }
1788
1789 lStatus = initCheck();
1790 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07001791 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08001792 goto Exit;
1793 }
1794
1795 { // scope for mLock
1796 Mutex::Autolock _l(mLock);
1797
1798 // all tracks in same audio session must share the same routing strategy otherwise
1799 // conflicts will happen when tracks are moved from one output to another by audio policy
1800 // manager
1801 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1802 for (size_t i = 0; i < mTracks.size(); ++i) {
1803 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07001804 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001805 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1806 if (sessionId == t->sessionId() && strategy != actual) {
1807 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1808 strategy, actual);
1809 lStatus = BAD_VALUE;
1810 goto Exit;
1811 }
1812 }
1813 }
1814
Glenn Kastend79072e2016-01-06 08:41:20 -08001815 track = new Track(this, client, streamType, sampleRate, format,
1816 channelMask, frameCount, NULL, sharedBuffer,
1817 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT);
Glenn Kasten03003332013-08-06 15:40:54 -07001818
Glenn Kasten03003332013-08-06 15:40:54 -07001819 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
1820 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08001821 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001822 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08001823 goto Exit;
1824 }
1825 mTracks.add(track);
1826
1827 sp<EffectChain> chain = getEffectChain_l(sessionId);
1828 if (chain != 0) {
1829 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1830 track->setMainBuffer(chain->inBuffer());
1831 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1832 chain->incTrackCnt();
1833 }
1834
1835 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1836 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1837 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1838 // so ask activity manager to do this on our behalf
1839 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1840 }
1841 }
1842
1843 lStatus = NO_ERROR;
1844
1845Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001846 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001847 return track;
1848}
1849
1850uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1851{
1852 return latency;
1853}
1854
1855uint32_t AudioFlinger::PlaybackThread::latency() const
1856{
1857 Mutex::Autolock _l(mLock);
1858 return latency_l();
1859}
1860uint32_t AudioFlinger::PlaybackThread::latency_l() const
1861{
1862 if (initCheck() == NO_ERROR) {
1863 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
1864 } else {
1865 return 0;
1866 }
1867}
1868
1869void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1870{
1871 Mutex::Autolock _l(mLock);
1872 // Don't apply master volume in SW if our HAL can do it for us.
1873 if (mOutput && mOutput->audioHwDev &&
1874 mOutput->audioHwDev->canSetMasterVolume()) {
1875 mMasterVolume = 1.0;
1876 } else {
1877 mMasterVolume = value;
1878 }
1879}
1880
1881void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1882{
1883 Mutex::Autolock _l(mLock);
1884 // Don't apply master mute in SW if our HAL can do it for us.
1885 if (mOutput && mOutput->audioHwDev &&
1886 mOutput->audioHwDev->canSetMasterMute()) {
1887 mMasterMute = false;
1888 } else {
1889 mMasterMute = muted;
1890 }
1891}
1892
1893void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
1894{
1895 Mutex::Autolock _l(mLock);
1896 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001897 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001898}
1899
1900void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
1901{
1902 Mutex::Autolock _l(mLock);
1903 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001904 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001905}
1906
1907float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
1908{
1909 Mutex::Autolock _l(mLock);
1910 return mStreamTypes[stream].volume;
1911}
1912
1913// addTrack_l() must be called with ThreadBase::mLock held
1914status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1915{
1916 status_t status = ALREADY_EXISTS;
1917
1918 // set retry count for buffer fill
1919 track->mRetryCount = kMaxTrackStartupRetries;
1920 if (mActiveTracks.indexOf(track) < 0) {
1921 // the track is newly added, make sure it fills up all its
1922 // buffers before playing. This is to ensure the client will
1923 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07001924 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001925 TrackBase::track_state state = track->mState;
1926 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08001927 status = AudioSystem::startOutput(mId, track->streamType(),
1928 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001929 mLock.lock();
1930 // abort track was stopped/paused while we released the lock
1931 if (state != track->mState) {
1932 if (status == NO_ERROR) {
1933 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08001934 AudioSystem::stopOutput(mId, track->streamType(),
1935 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001936 mLock.lock();
1937 }
1938 return INVALID_OPERATION;
1939 }
1940 // abort if start is rejected by audio policy manager
1941 if (status != NO_ERROR) {
1942 return PERMISSION_DENIED;
1943 }
1944#ifdef ADD_BATTERY_DATA
1945 // to track the speaker usage
1946 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
1947#endif
1948 }
1949
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001950 track->mFillingUpStatus = track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent81784c32012-11-19 14:55:58 -08001951 track->mResetDone = false;
1952 track->mPresentationCompleteFrames = 0;
1953 mActiveTracks.add(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001954 mWakeLockUids.add(track->uid());
1955 mActiveTracksGeneration++;
Eric Laurentfd477972013-10-25 18:10:40 -07001956 mLatestActiveTrack = track;
Eric Laurentd0107bc2013-06-11 14:38:48 -07001957 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1958 if (chain != 0) {
1959 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
1960 track->sessionId());
1961 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08001962 }
1963
1964 status = NO_ERROR;
1965 }
1966
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08001967 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001968 return status;
1969}
1970
Eric Laurentbfb1b832013-01-07 09:53:42 -08001971bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08001972{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001973 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08001974 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001975 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
1976 track->mState = TrackBase::STOPPED;
1977 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08001978 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07001979 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001980 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08001981 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001982
1983 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08001984}
1985
1986void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1987{
1988 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
1989 mTracks.remove(track);
1990 deleteTrackName_l(track->name());
1991 // redundant as track is about to be destroyed, for dumpsys only
1992 track->mName = -1;
1993 if (track->isFastTrack()) {
1994 int index = track->mFastIndex;
1995 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
1996 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1997 mFastTrackAvailMask |= 1 << index;
1998 // redundant as track is about to be destroyed, for dumpsys only
1999 track->mFastIndex = -1;
2000 }
2001 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2002 if (chain != 0) {
2003 chain->decTrackCnt();
2004 }
2005}
2006
Eric Laurentede6c3b2013-09-19 14:37:46 -07002007void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002008{
2009 // Thread could be blocked waiting for async
2010 // so signal it to handle state changes immediately
2011 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
2012 // be lost so we also flag to prevent it blocking on mWaitWorkCV
2013 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002014 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002015}
2016
Eric Laurent81784c32012-11-19 14:55:58 -08002017String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2018{
Eric Laurent81784c32012-11-19 14:55:58 -08002019 Mutex::Autolock _l(mLock);
2020 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07002021 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002022 }
2023
Glenn Kastend8ea6992013-07-16 14:17:15 -07002024 char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
2025 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08002026 free(s);
2027 return out_s8;
2028}
2029
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002030void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002031 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2032 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002033
Eric Laurent73e26b62015-04-27 16:55:58 -07002034 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002035
2036 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002037 case AUDIO_OUTPUT_OPENED:
2038 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002039 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002040 desc->mChannelMask = mChannelMask;
2041 desc->mSamplingRate = mSampleRate;
2042 desc->mFormat = mFormat;
2043 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002044 // AudioFlinger::frameCount(audio_io_handle_t)
Eric Laurent73e26b62015-04-27 16:55:58 -07002045 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002046 break;
2047
Eric Laurent73e26b62015-04-27 16:55:58 -07002048 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002049 default:
2050 break;
2051 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002052 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002053}
2054
Eric Laurentbfb1b832013-01-07 09:53:42 -08002055void AudioFlinger::PlaybackThread::writeCallback()
2056{
2057 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002058 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002059}
2060
2061void AudioFlinger::PlaybackThread::drainCallback()
2062{
2063 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002064 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002065}
2066
Eric Laurent3b4529e2013-09-05 18:09:19 -07002067void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002068{
2069 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002070 // reject out of sequence requests
2071 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2072 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002073 mWaitWorkCV.signal();
2074 }
2075}
2076
Eric Laurent3b4529e2013-09-05 18:09:19 -07002077void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002078{
2079 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002080 // reject out of sequence requests
2081 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
2082 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002083 mWaitWorkCV.signal();
2084 }
2085}
2086
2087// static
2088int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
Glenn Kasten0f11b512014-01-31 16:18:54 -08002089 void *param __unused,
Eric Laurentbfb1b832013-01-07 09:53:42 -08002090 void *cookie)
2091{
2092 AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
2093 ALOGV("asyncCallback() event %d", event);
2094 switch (event) {
2095 case STREAM_CBK_EVENT_WRITE_READY:
2096 me->writeCallback();
2097 break;
2098 case STREAM_CBK_EVENT_DRAIN_READY:
2099 me->drainCallback();
2100 break;
2101 default:
2102 ALOGW("asyncCallback() unknown event %d", event);
2103 break;
2104 }
2105 return 0;
2106}
2107
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002108void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002109{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002110 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Phil Burkca5e6142015-07-14 09:42:29 -07002111 mSampleRate = mOutput->getSampleRate();
2112 mChannelMask = mOutput->getChannelMask();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002113 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002114 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002115 }
Andy Hung9a592762014-07-21 21:56:01 -07002116 if ((mType == MIXER || mType == DUPLICATING)
2117 && !isValidPcmSinkChannelMask(mChannelMask)) {
2118 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2119 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002120 }
Andy Hunge5412692014-05-16 11:25:07 -07002121 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002122
2123 // Get actual HAL format.
Andy Hung463be252014-07-10 16:56:07 -07002124 mHALFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Phil Burkca5e6142015-07-14 09:42:29 -07002125 // Get format from the shim, which will be different than the HAL format
2126 // if playing compressed audio over HDMI passthrough.
2127 mFormat = mOutput->getFormat();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002128 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002129 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002130 }
Andy Hung6146c082014-03-18 11:56:15 -07002131 if ((mType == MIXER || mType == DUPLICATING)
2132 && !isValidPcmSinkFormat(mFormat)) {
2133 LOG_FATAL("HAL format %#x not supported for mixed output",
2134 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002135 }
Phil Burk062e67a2015-02-11 13:40:50 -08002136 mFrameSize = mOutput->getFrameSize();
Glenn Kasten70949c42013-08-06 07:40:12 -07002137 mBufferSize = mOutput->stream->common.get_buffer_size(&mOutput->stream->common);
2138 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002139 if (mFrameCount & 15) {
2140 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
2141 mFrameCount);
2142 }
2143
Eric Laurentbfb1b832013-01-07 09:53:42 -08002144 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
2145 (mOutput->stream->set_callback != NULL)) {
2146 if (mOutput->stream->set_callback(mOutput->stream,
2147 AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
2148 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002149 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002150 }
2151 }
2152
Eric Laurentd1f69b02014-12-15 14:33:13 -08002153 mHwSupportsPause = false;
2154 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
2155 if (mOutput->stream->pause != NULL) {
2156 if (mOutput->stream->resume != NULL) {
2157 mHwSupportsPause = true;
2158 } else {
2159 ALOGW("direct output implements pause but not resume");
2160 }
2161 } else if (mOutput->stream->resume != NULL) {
2162 ALOGW("direct output implements resume but not pause");
2163 }
2164 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002165 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2166 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2167 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002168
Andy Hungfbfc3952015-01-15 13:33:51 -08002169 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2170 // For best precision, we use float instead of the associated output
2171 // device format (typically PCM 16 bit).
2172
2173 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2174 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2175 mBufferSize = mFrameSize * mFrameCount;
2176
2177 // TODO: We currently use the associated output device channel mask and sample rate.
2178 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2179 // (if a valid mask) to avoid premature downmix.
2180 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2181 // instead of the output device sample rate to avoid loss of high frequency information.
2182 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2183 }
2184
Andy Hung09a50072014-02-27 14:30:47 -08002185 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002186 double multiplier = 1.0;
2187 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2188 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002189 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2190 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Eric Laurent81784c32012-11-19 14:55:58 -08002191 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2192 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2193 maxNormalFrameCount = maxNormalFrameCount & ~15;
2194 if (maxNormalFrameCount < minNormalFrameCount) {
2195 maxNormalFrameCount = minNormalFrameCount;
2196 }
2197 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2198 if (multiplier <= 1.0) {
2199 multiplier = 1.0;
2200 } else if (multiplier <= 2.0) {
2201 if (2 * mFrameCount <= maxNormalFrameCount) {
2202 multiplier = 2.0;
2203 } else {
2204 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2205 }
2206 } else {
2207 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
Andy Hung09a50072014-02-27 14:30:47 -08002208 // SRC (it would be unusual for the normal sink buffer size to not be a multiple of fast
Eric Laurent81784c32012-11-19 14:55:58 -08002209 // track, but we sometimes have to do this to satisfy the maximum frame count
2210 // constraint)
2211 // FIXME this rounding up should not be done if no HAL SRC
2212 uint32_t truncMult = (uint32_t) multiplier;
2213 if ((truncMult & 1)) {
2214 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
2215 ++truncMult;
2216 }
2217 }
2218 multiplier = (double) truncMult;
2219 }
2220 }
2221 mNormalFrameCount = multiplier * mFrameCount;
2222 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002223 if (mType == MIXER || mType == DUPLICATING) {
2224 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2225 }
Andy Hung09a50072014-02-27 14:30:47 -08002226 ALOGI("HAL output buffer size %u frames, normal sink buffer size %u frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002227 mNormalFrameCount);
2228
Andy Hung08fb1742015-05-31 23:22:10 -07002229 // Check if we want to throttle the processing to no more than 2x normal rate
2230 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002231 mThreadThrottleTimeMs = 0;
2232 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002233 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2234
Andy Hung010a1a12014-03-13 13:57:33 -07002235 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2236 // Originally this was int16_t[] array, need to remove legacy implications.
2237 free(mSinkBuffer);
2238 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002239 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2240 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2241 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002242 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002243
Andy Hung69aed5f2014-02-25 17:24:40 -08002244 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2245 // drives the output.
2246 free(mMixerBuffer);
2247 mMixerBuffer = NULL;
2248 if (mMixerBufferEnabled) {
2249 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2250 mMixerBufferSize = mNormalFrameCount * mChannelCount
2251 * audio_bytes_per_sample(mMixerBufferFormat);
2252 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2253 }
Andy Hung98ef9782014-03-04 14:46:50 -08002254 free(mEffectBuffer);
2255 mEffectBuffer = NULL;
2256 if (mEffectBufferEnabled) {
2257 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
2258 mEffectBufferSize = mNormalFrameCount * mChannelCount
2259 * audio_bytes_per_sample(mEffectBufferFormat);
2260 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2261 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002262
Eric Laurent81784c32012-11-19 14:55:58 -08002263 // force reconfiguration of effect chains and engines to take new buffer size and audio
2264 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002265 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002266 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2267 // matter.
2268 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2269 Vector< sp<EffectChain> > effectChains = mEffectChains;
2270 for (size_t i = 0; i < effectChains.size(); i ++) {
2271 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2272 }
2273}
2274
2275
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002276status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002277{
2278 if (halFrames == NULL || dspFrames == NULL) {
2279 return BAD_VALUE;
2280 }
2281 Mutex::Autolock _l(mLock);
2282 if (initCheck() != NO_ERROR) {
2283 return INVALID_OPERATION;
2284 }
2285 size_t framesWritten = mBytesWritten / mFrameSize;
2286 *halFrames = framesWritten;
2287
2288 if (isSuspended()) {
2289 // return an estimation of rendered frames when the output is suspended
2290 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
2291 *dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0;
2292 return NO_ERROR;
2293 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002294 status_t status;
2295 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002296 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002297 *dspFrames = (size_t)frames;
2298 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002299 }
2300}
2301
2302uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
2303{
2304 Mutex::Autolock _l(mLock);
2305 uint32_t result = 0;
2306 if (getEffectChain_l(sessionId) != 0) {
2307 result = EFFECT_SESSION;
2308 }
2309
2310 for (size_t i = 0; i < mTracks.size(); ++i) {
2311 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002312 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002313 result |= TRACK_SESSION;
2314 break;
2315 }
2316 }
2317
2318 return result;
2319}
2320
2321uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
2322{
2323 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2324 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2325 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2326 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2327 }
2328 for (size_t i = 0; i < mTracks.size(); i++) {
2329 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002330 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002331 return AudioSystem::getStrategyForStream(track->streamType());
2332 }
2333 }
2334 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2335}
2336
2337
Phil Burk062e67a2015-02-11 13:40:50 -08002338AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002339{
2340 Mutex::Autolock _l(mLock);
2341 return mOutput;
2342}
2343
Phil Burk062e67a2015-02-11 13:40:50 -08002344AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002345{
2346 Mutex::Autolock _l(mLock);
2347 AudioStreamOut *output = mOutput;
2348 mOutput = NULL;
2349 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2350 // must push a NULL and wait for ack
2351 mOutputSink.clear();
2352 mPipeSink.clear();
2353 mNormalSink.clear();
2354 return output;
2355}
2356
2357// this method must always be called either with ThreadBase mLock held or inside the thread loop
2358audio_stream_t* AudioFlinger::PlaybackThread::stream() const
2359{
2360 if (mOutput == NULL) {
2361 return NULL;
2362 }
2363 return &mOutput->stream->common;
2364}
2365
2366uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2367{
2368 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2369}
2370
2371status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2372{
2373 if (!isValidSyncEvent(event)) {
2374 return BAD_VALUE;
2375 }
2376
2377 Mutex::Autolock _l(mLock);
2378
2379 for (size_t i = 0; i < mTracks.size(); ++i) {
2380 sp<Track> track = mTracks[i];
2381 if (event->triggerSession() == track->sessionId()) {
2382 (void) track->setSyncEvent(event);
2383 return NO_ERROR;
2384 }
2385 }
2386
2387 return NAME_NOT_FOUND;
2388}
2389
2390bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2391{
2392 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2393}
2394
2395void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2396 const Vector< sp<Track> >& tracksToRemove)
2397{
2398 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002399 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002400 for (size_t i = 0 ; i < count ; i++) {
2401 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002402 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002403 AudioSystem::stopOutput(mId, track->streamType(),
2404 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002405#ifdef ADD_BATTERY_DATA
2406 // to track the speaker usage
2407 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2408#endif
2409 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002410 AudioSystem::releaseOutput(mId, track->streamType(),
2411 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002412 }
Eric Laurent81784c32012-11-19 14:55:58 -08002413 }
2414 }
2415 }
Eric Laurent81784c32012-11-19 14:55:58 -08002416}
2417
2418void AudioFlinger::PlaybackThread::checkSilentMode_l()
2419{
2420 if (!mMasterMute) {
2421 char value[PROPERTY_VALUE_MAX];
2422 if (property_get("ro.audio.silent", value, "0") > 0) {
2423 char *endptr;
2424 unsigned long ul = strtoul(value, &endptr, 0);
2425 if (*endptr == '\0' && ul != 0) {
2426 ALOGD("Silence is golden");
2427 // The setprop command will not allow a property to be changed after
2428 // the first time it is set, so we don't have to worry about un-muting.
2429 setMasterMute_l(true);
2430 }
2431 }
2432 }
2433}
2434
2435// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002436ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002437{
2438 // FIXME rewrite to reduce number of system calls
2439 mLastWriteTime = systemTime();
2440 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002441 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002442 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002443
2444 // If an NBAIO sink is present, use it to write the normal mixer's submix
2445 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002446
Andy Hung010a1a12014-03-13 13:57:33 -07002447 const size_t count = mBytesRemaining / mFrameSize;
2448
Simon Wilson2d590962012-11-29 15:18:50 -08002449 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002450 // update the setpoint when AudioFlinger::mScreenState changes
2451 uint32_t screenState = AudioFlinger::mScreenState;
2452 if (screenState != mScreenState) {
2453 mScreenState = screenState;
2454 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2455 if (pipe != NULL) {
2456 pipe->setAvgFrames((mScreenState & 1) ?
2457 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2458 }
2459 }
Andy Hung010a1a12014-03-13 13:57:33 -07002460 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002461 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002462 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002463 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002464 } else {
2465 bytesWritten = framesWritten;
2466 }
Glenn Kastenefaa7ab2014-08-20 08:48:54 -07002467 mLatchDValid = false;
Glenn Kasten767094d2013-08-23 13:51:43 -07002468 status_t status = mNormalSink->getTimestamp(mLatchD.mTimestamp);
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002469 if (status == NO_ERROR) {
2470 size_t totalFramesWritten = mNormalSink->framesWritten();
2471 if (totalFramesWritten >= mLatchD.mTimestamp.mPosition) {
2472 mLatchD.mUnpresentedFrames = totalFramesWritten - mLatchD.mTimestamp.mPosition;
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002473 // mLatchD.mFramesReleased is set immediately before D is clocked into Q
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002474 mLatchDValid = true;
2475 }
2476 }
Eric Laurent81784c32012-11-19 14:55:58 -08002477 // otherwise use the HAL / AudioStreamOut directly
2478 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002479 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002480
Eric Laurentbfb1b832013-01-07 09:53:42 -08002481 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002482 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2483 mWriteAckSequence += 2;
2484 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002485 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002486 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002487 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002488 // FIXME We should have an implementation of timestamps for direct output threads.
2489 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002490 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002491 if (mUseAsyncWrite &&
2492 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2493 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002494 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002495 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002496 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002497 }
Eric Laurent81784c32012-11-19 14:55:58 -08002498 }
2499
Eric Laurent81784c32012-11-19 14:55:58 -08002500 mNumWrites++;
2501 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002502 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002503 return bytesWritten;
2504}
2505
2506void AudioFlinger::PlaybackThread::threadLoop_drain()
2507{
2508 if (mOutput->stream->drain) {
2509 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2510 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002511 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2512 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002513 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002514 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002515 }
2516 mOutput->stream->drain(mOutput->stream,
2517 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
2518 : AUDIO_DRAIN_ALL);
2519 }
2520}
2521
2522void AudioFlinger::PlaybackThread::threadLoop_exit()
2523{
Eric Laurent275e8e92014-11-30 15:14:47 -08002524 {
2525 Mutex::Autolock _l(mLock);
2526 for (size_t i = 0; i < mTracks.size(); i++) {
2527 sp<Track> track = mTracks[i];
2528 track->invalidate();
2529 }
2530 }
Eric Laurent81784c32012-11-19 14:55:58 -08002531}
2532
2533/*
2534The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002535 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002536 - mActiveSleepTimeUs from activeSleepTimeUs()
2537 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08002538 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
2539 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08002540 - maxPeriod from frame count and sample rate (MIXER only)
2541
2542The parameters that affect these derived values are:
2543 - frame count
2544 - frame size
2545 - sample rate
2546 - device type: A2DP or not
2547 - device latency
2548 - format: PCM or not
2549 - active sleep time
2550 - idle sleep time
2551*/
2552
2553void AudioFlinger::PlaybackThread::cacheParameters_l()
2554{
Andy Hung25c2dac2014-02-27 14:56:00 -08002555 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002556 mActiveSleepTimeUs = activeSleepTimeUs();
2557 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08002558
2559 // make sure standby delay is not too short when connected to an A2DP sink to avoid
2560 // truncating audio when going to standby.
2561 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
2562 if ((mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != 0) {
2563 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
2564 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
2565 }
2566 }
Eric Laurent81784c32012-11-19 14:55:58 -08002567}
2568
2569void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2570{
Glenn Kasten7c027242012-12-26 14:43:16 -08002571 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurent81784c32012-11-19 14:55:58 -08002572 this, streamType, mTracks.size());
2573 Mutex::Autolock _l(mLock);
2574
2575 size_t size = mTracks.size();
2576 for (size_t i = 0; i < size; i++) {
2577 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07002578 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002579 t->invalidate();
Eric Laurent81784c32012-11-19 14:55:58 -08002580 }
2581 }
2582}
2583
2584status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2585{
2586 int session = chain->sessionId();
Andy Hung010a1a12014-03-13 13:57:33 -07002587 int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled
2588 ? mEffectBuffer : mSinkBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002589 bool ownsBuffer = false;
2590
2591 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
2592 if (session > 0) {
2593 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002594 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002595 if (mType != DIRECT) {
2596 size_t numSamples = mNormalFrameCount * mChannelCount;
2597 buffer = new int16_t[numSamples];
2598 memset(buffer, 0, numSamples * sizeof(int16_t));
2599 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2600 ownsBuffer = true;
2601 }
2602
2603 // Attach all tracks with same session ID to this chain.
2604 for (size_t i = 0; i < mTracks.size(); ++i) {
2605 sp<Track> track = mTracks[i];
2606 if (session == track->sessionId()) {
2607 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2608 buffer);
2609 track->setMainBuffer(buffer);
2610 chain->incTrackCnt();
2611 }
2612 }
2613
2614 // indicate all active tracks in the chain
2615 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2616 sp<Track> track = mActiveTracks[i].promote();
2617 if (track == 0) {
2618 continue;
2619 }
2620 if (session == track->sessionId()) {
2621 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2622 chain->incActiveTrackCnt();
2623 }
2624 }
2625 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002626 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08002627 chain->setInBuffer(buffer, ownsBuffer);
Andy Hung010a1a12014-03-13 13:57:33 -07002628 chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled
2629 ? mEffectBuffer : mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002630 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
2631 // chains list in order to be processed last as it contains output stage effects
2632 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2633 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
2634 // after track specific effects and before output stage
2635 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
2636 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
2637 // Effect chain for other sessions are inserted at beginning of effect
2638 // chains list to be processed before output mix effects. Relative order between other
2639 // sessions is not important
2640 size_t size = mEffectChains.size();
2641 size_t i = 0;
2642 for (i = 0; i < size; i++) {
2643 if (mEffectChains[i]->sessionId() < session) {
2644 break;
2645 }
2646 }
2647 mEffectChains.insertAt(chain, i);
2648 checkSuspendOnAddEffectChain_l(chain);
2649
2650 return NO_ERROR;
2651}
2652
2653size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2654{
2655 int session = chain->sessionId();
2656
2657 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2658
2659 for (size_t i = 0; i < mEffectChains.size(); i++) {
2660 if (chain == mEffectChains[i]) {
2661 mEffectChains.removeAt(i);
2662 // detach all active tracks from the chain
2663 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2664 sp<Track> track = mActiveTracks[i].promote();
2665 if (track == 0) {
2666 continue;
2667 }
2668 if (session == track->sessionId()) {
2669 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2670 chain.get(), session);
2671 chain->decActiveTrackCnt();
2672 }
2673 }
2674
2675 // detach all tracks with same session ID from this chain
2676 for (size_t i = 0; i < mTracks.size(); ++i) {
2677 sp<Track> track = mTracks[i];
2678 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002679 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002680 chain->decTrackCnt();
2681 }
2682 }
2683 break;
2684 }
2685 }
2686 return mEffectChains.size();
2687}
2688
2689status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2690 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2691{
2692 Mutex::Autolock _l(mLock);
2693 return attachAuxEffect_l(track, EffectId);
2694}
2695
2696status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2697 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2698{
2699 status_t status = NO_ERROR;
2700
2701 if (EffectId == 0) {
2702 track->setAuxBuffer(0, NULL);
2703 } else {
2704 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2705 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2706 if (effect != 0) {
2707 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2708 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2709 } else {
2710 status = INVALID_OPERATION;
2711 }
2712 } else {
2713 status = BAD_VALUE;
2714 }
2715 }
2716 return status;
2717}
2718
2719void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2720{
2721 for (size_t i = 0; i < mTracks.size(); ++i) {
2722 sp<Track> track = mTracks[i];
2723 if (track->auxEffectId() == effectId) {
2724 attachAuxEffect_l(track, 0);
2725 }
2726 }
2727}
2728
2729bool AudioFlinger::PlaybackThread::threadLoop()
2730{
2731 Vector< sp<Track> > tracksToRemove;
2732
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002733 mStandbyTimeNs = systemTime();
Eric Laurent81784c32012-11-19 14:55:58 -08002734
2735 // MIXER
2736 nsecs_t lastWarning = 0;
2737
2738 // DUPLICATING
2739 // FIXME could this be made local to while loop?
2740 writeFrames = 0;
2741
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002742 int lastGeneration = 0;
2743
Eric Laurent81784c32012-11-19 14:55:58 -08002744 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002745 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08002746
2747 if (mType == MIXER) {
2748 sleepTimeShift = 0;
2749 }
2750
2751 CpuStats cpuStats;
2752 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2753
2754 acquireWakeLock();
2755
Glenn Kasten9e58b552013-01-18 15:09:48 -08002756 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2757 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2758 // and then that string will be logged at the next convenient opportunity.
2759 const char *logString = NULL;
2760
Eric Laurent664539d2013-09-23 18:24:31 -07002761 checkSilentMode_l();
2762
Eric Laurent81784c32012-11-19 14:55:58 -08002763 while (!exitPending())
2764 {
2765 cpuStats.sample(myName);
2766
2767 Vector< sp<EffectChain> > effectChains;
2768
Eric Laurent81784c32012-11-19 14:55:58 -08002769 { // scope for mLock
2770
2771 Mutex::Autolock _l(mLock);
2772
Eric Laurent021cf962014-05-13 10:18:14 -07002773 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07002774
Glenn Kasten9e58b552013-01-18 15:09:48 -08002775 if (logString != NULL) {
2776 mNBLogWriter->logTimestamp();
2777 mNBLogWriter->log(logString);
2778 logString = NULL;
2779 }
2780
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002781 // Gather the framesReleased counters for all active tracks,
2782 // and latch them atomically with the timestamp.
2783 // FIXME We're using raw pointers as indices. A unique track ID would be a better index.
2784 mLatchD.mFramesReleased.clear();
2785 size_t size = mActiveTracks.size();
2786 for (size_t i = 0; i < size; i++) {
2787 sp<Track> t = mActiveTracks[i].promote();
2788 if (t != 0) {
2789 mLatchD.mFramesReleased.add(t.get(),
2790 t->mAudioTrackServerProxy->framesReleased());
2791 }
2792 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002793 if (mLatchDValid) {
2794 mLatchQ = mLatchD;
2795 mLatchDValid = false;
2796 mLatchQValid = true;
2797 }
2798
Eric Laurent81784c32012-11-19 14:55:58 -08002799 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002800 if (mSignalPending) {
2801 // A signal was raised while we were unlocked
2802 mSignalPending = false;
2803 } else if (waitingAsyncCallback_l()) {
2804 if (exitPending()) {
2805 break;
2806 }
Marco Nelissen078538c2015-05-12 09:17:57 -07002807 bool released = false;
2808 // The following works around a bug in the offload driver. Ideally we would release
2809 // the wake lock every time, but that causes the last offload buffer(s) to be
2810 // dropped while the device is on battery, so we need to hold a wake lock during
2811 // the drain phase.
2812 if (mBytesRemaining && !(mDrainSequence & 1)) {
2813 releaseWakeLock_l();
2814 released = true;
2815 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002816 mWakeLockUids.clear();
2817 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002818 ALOGV("wait async completion");
2819 mWaitWorkCV.wait(mLock);
2820 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07002821 if (released) {
2822 acquireWakeLock_l();
2823 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002824 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
2825 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002826
2827 continue;
2828 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002829 if ((!mActiveTracks.size() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08002830 isSuspended()) {
2831 // put audio hardware into standby after short delay
2832 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002833
2834 threadLoop_standby();
2835
2836 mStandby = true;
2837 }
2838
2839 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2840 // we're about to wait, flush the binder command buffer
2841 IPCThreadState::self()->flushCommands();
2842
2843 clearOutputTracks();
2844
2845 if (exitPending()) {
2846 break;
2847 }
2848
2849 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002850 mWakeLockUids.clear();
2851 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002852 // wait until we have something to do...
2853 ALOGV("%s going to sleep", myName.string());
2854 mWaitWorkCV.wait(mLock);
2855 ALOGV("%s waking up", myName.string());
2856 acquireWakeLock_l();
2857
2858 mMixerStatus = MIXER_IDLE;
2859 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2860 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002861 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002862 checkSilentMode_l();
2863
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002864 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
2865 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08002866 if (mType == MIXER) {
2867 sleepTimeShift = 0;
2868 }
2869
2870 continue;
2871 }
2872 }
Eric Laurent81784c32012-11-19 14:55:58 -08002873 // mMixerStatusIgnoringFastTracks is also updated internally
2874 mMixerStatus = prepareTracks_l(&tracksToRemove);
2875
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002876 // compare with previously applied list
2877 if (lastGeneration != mActiveTracksGeneration) {
2878 // update wakelock
2879 updateWakeLockUids_l(mWakeLockUids);
2880 lastGeneration = mActiveTracksGeneration;
2881 }
2882
Eric Laurent81784c32012-11-19 14:55:58 -08002883 // prevent any changes in effect chain list and in each effect chain
2884 // during mixing and effect process as the audio buffers could be deleted
2885 // or modified if an effect is created or deleted
2886 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002887 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08002888
Eric Laurentbfb1b832013-01-07 09:53:42 -08002889 if (mBytesRemaining == 0) {
2890 mCurrentWriteLength = 0;
2891 if (mMixerStatus == MIXER_TRACKS_READY) {
2892 // threadLoop_mix() sets mCurrentWriteLength
2893 threadLoop_mix();
2894 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
2895 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002896 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08002897 // must be written to HAL
2898 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002899 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08002900 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002901 }
2902 }
Andy Hung98ef9782014-03-04 14:46:50 -08002903 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002904 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08002905 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
2906 // or mSinkBuffer (if there are no effects).
2907 //
2908 // This is done pre-effects computation; if effects change to
2909 // support higher precision, this needs to move.
2910 //
2911 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002912 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08002913 if (mMixerBufferValid) {
2914 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
2915 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
2916
Andy Hung2ddee192015-12-18 17:34:44 -08002917 // mono blend occurs for mixer threads only (not direct or offloaded)
2918 // and is handled here if we're going directly to the sink.
2919 if (requireMonoBlend() && !mEffectBufferValid) {
2920 mono_blend(
2921 mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount);
2922 }
2923
Andy Hung98ef9782014-03-04 14:46:50 -08002924 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
2925 mNormalFrameCount * mChannelCount);
2926 }
2927
Eric Laurentbfb1b832013-01-07 09:53:42 -08002928 mBytesRemaining = mCurrentWriteLength;
2929 if (isSuspended()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002930 mSleepTimeUs = suspendSleepTimeUs();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002931 // simulate write to HAL when suspended
Andy Hung25c2dac2014-02-27 14:56:00 -08002932 mBytesWritten += mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002933 mBytesRemaining = 0;
2934 }
Eric Laurent81784c32012-11-19 14:55:58 -08002935
Eric Laurentbfb1b832013-01-07 09:53:42 -08002936 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002937 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002938 for (size_t i = 0; i < effectChains.size(); i ++) {
2939 effectChains[i]->process_l();
2940 }
Eric Laurent81784c32012-11-19 14:55:58 -08002941 }
2942 }
Eric Laurent59fe0102013-09-27 18:48:26 -07002943 // Process effect chains for offloaded thread even if no audio
2944 // was read from audio track: process only updates effect state
2945 // and thus does have to be synchronized with audio writes but may have
2946 // to be called while waiting for async write callback
2947 if (mType == OFFLOAD) {
2948 for (size_t i = 0; i < effectChains.size(); i ++) {
2949 effectChains[i]->process_l();
2950 }
2951 }
Eric Laurent81784c32012-11-19 14:55:58 -08002952
Andy Hung98ef9782014-03-04 14:46:50 -08002953 // Only if the Effects buffer is enabled and there is data in the
2954 // Effects buffer (buffer valid), we need to
2955 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002956 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08002957 if (mEffectBufferValid) {
2958 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08002959
2960 if (requireMonoBlend()) {
2961 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount);
2962 }
2963
Andy Hung98ef9782014-03-04 14:46:50 -08002964 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
2965 mNormalFrameCount * mChannelCount);
2966 }
2967
Eric Laurent81784c32012-11-19 14:55:58 -08002968 // enable changes in effect chain
2969 unlockEffectChains(effectChains);
2970
Eric Laurentbfb1b832013-01-07 09:53:42 -08002971 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002972 // mSleepTimeUs == 0 means we must write to audio hardware
2973 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07002974 ssize_t ret = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002975 if (mBytesRemaining) {
Andy Hung08fb1742015-05-31 23:22:10 -07002976 ret = threadLoop_write();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002977 if (ret < 0) {
2978 mBytesRemaining = 0;
2979 } else {
2980 mBytesWritten += ret;
2981 mBytesRemaining -= ret;
2982 }
2983 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
2984 (mMixerStatus == MIXER_DRAIN_ALL)) {
2985 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08002986 }
Andy Hung08fb1742015-05-31 23:22:10 -07002987 if (mType == MIXER && !mStandby) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07002988 // write blocked detection
2989 nsecs_t now = systemTime();
2990 nsecs_t delta = now - mLastWriteTime;
Andy Hung08fb1742015-05-31 23:22:10 -07002991 if (delta > maxPeriod) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07002992 mNumDelayedWrites++;
2993 if ((now - lastWarning) > kWarningThrottleNs) {
2994 ATRACE_NAME("underrun");
2995 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2996 ns2ms(delta), mNumDelayedWrites, this);
2997 lastWarning = now;
2998 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002999 }
Andy Hung08fb1742015-05-31 23:22:10 -07003000
3001 if (mThreadThrottle
3002 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
3003 && ret > 0) { // we wrote something
3004 // Limit MixerThread data processing to no more than twice the
3005 // expected processing rate.
3006 //
3007 // This helps prevent underruns with NuPlayer and other applications
3008 // which may set up buffers that are close to the minimum size, or use
3009 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3010 //
3011 // The throttle smooths out sudden large data drains from the device,
3012 // e.g. when it comes out of standby, which often causes problems with
3013 // (1) mixer threads without a fast mixer (which has its own warm-up)
3014 // (2) minimum buffer sized tracks (even if the track is full,
3015 // the app won't fill fast enough to handle the sudden draw).
3016
3017 const int32_t deltaMs = delta / 1000000;
3018 const int32_t throttleMs = mHalfBufferMs - deltaMs;
3019 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
3020 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003021 // notify of throttle start on verbose log
3022 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3023 "mixer(%p) throttle begin:"
3024 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003025 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07003026 mThreadThrottleTimeMs += throttleMs;
3027 } else {
3028 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3029 if (diff > 0) {
3030 // notify of throttle end on debug log
3031 ALOGD("mixer(%p) throttle end: throttle time(%u)", this, diff);
3032 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3033 }
Andy Hung08fb1742015-05-31 23:22:10 -07003034 }
3035 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003036 }
Eric Laurent81784c32012-11-19 14:55:58 -08003037
Eric Laurentbfb1b832013-01-07 09:53:42 -08003038 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003039 ATRACE_BEGIN("sleep");
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003040 usleep(mSleepTimeUs);
Glenn Kastene7754022014-10-31 12:11:26 -07003041 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003042 }
Eric Laurent81784c32012-11-19 14:55:58 -08003043 }
3044
3045 // Finally let go of removed track(s), without the lock held
3046 // since we can't guarantee the destructors won't acquire that
3047 // same lock. This will also mutate and push a new fast mixer state.
3048 threadLoop_removeTracks(tracksToRemove);
3049 tracksToRemove.clear();
3050
3051 // FIXME I don't understand the need for this here;
3052 // it was in the original code but maybe the
3053 // assignment in saveOutputTracks() makes this unnecessary?
3054 clearOutputTracks();
3055
3056 // Effect chains will be actually deleted here if they were removed from
3057 // mEffectChains list during mixing or effects processing
3058 effectChains.clear();
3059
3060 // FIXME Note that the above .clear() is no longer necessary since effectChains
3061 // is now local to this block, but will keep it for now (at least until merge done).
3062 }
3063
Eric Laurentbfb1b832013-01-07 09:53:42 -08003064 threadLoop_exit();
3065
Eric Laurentcf817a22014-08-04 20:36:31 -07003066 if (!mStandby) {
3067 threadLoop_standby();
3068 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003069 }
3070
3071 releaseWakeLock();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003072 mWakeLockUids.clear();
3073 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08003074
3075 ALOGV("Thread %p type %d exiting", this, mType);
3076 return false;
3077}
3078
Eric Laurentbfb1b832013-01-07 09:53:42 -08003079// removeTracks_l() must be called with ThreadBase::mLock held
3080void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3081{
3082 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07003083 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003084 for (size_t i=0 ; i<count ; i++) {
3085 const sp<Track>& track = tracksToRemove.itemAt(i);
3086 mActiveTracks.remove(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003087 mWakeLockUids.remove(track->uid());
3088 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003089 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
3090 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3091 if (chain != 0) {
3092 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
3093 track->sessionId());
3094 chain->decActiveTrackCnt();
3095 }
3096 if (track->isTerminated()) {
3097 removeTrack_l(track);
3098 }
3099 }
3100 }
3101
3102}
Eric Laurent81784c32012-11-19 14:55:58 -08003103
Eric Laurentaccc1472013-09-20 09:36:34 -07003104status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3105{
3106 if (mNormalSink != 0) {
3107 return mNormalSink->getTimestamp(timestamp);
3108 }
Andy Hung9a1c8892014-12-03 11:37:42 -08003109 if ((mType == OFFLOAD || mType == DIRECT)
3110 && mOutput != NULL && mOutput->stream->get_presentation_position) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003111 uint64_t position64;
Phil Burk062e67a2015-02-11 13:40:50 -08003112 int ret = mOutput->getPresentationPosition(&position64, &timestamp.mTime);
Eric Laurentaccc1472013-09-20 09:36:34 -07003113 if (ret == 0) {
3114 timestamp.mPosition = (uint32_t)position64;
3115 return NO_ERROR;
3116 }
3117 }
3118 return INVALID_OPERATION;
3119}
Eric Laurent1c333e22014-05-20 10:48:17 -07003120
Eric Laurent054d9d32015-04-24 08:48:48 -07003121status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
3122 audio_patch_handle_t *handle)
3123{
3124 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3125 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3126 if (mFastMixer != 0) {
3127 FastMixerStateQueue *sq = mFastMixer->sq();
3128 FastMixerState *state = sq->begin();
3129 if (!(state->mCommand & FastMixerState::IDLE)) {
3130 previousCommand = state->mCommand;
3131 state->mCommand = FastMixerState::HOT_IDLE;
3132 sq->end();
3133 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3134 } else {
3135 sq->end(false /*didModify*/);
3136 }
3137 }
3138 status_t status = PlaybackThread::createAudioPatch_l(patch, handle);
3139
3140 if (!(previousCommand & FastMixerState::IDLE)) {
3141 ALOG_ASSERT(mFastMixer != 0);
3142 FastMixerStateQueue *sq = mFastMixer->sq();
3143 FastMixerState *state = sq->begin();
3144 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3145 state->mCommand = previousCommand;
3146 sq->end();
3147 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3148 }
3149
3150 return status;
3151}
3152
Eric Laurent1c333e22014-05-20 10:48:17 -07003153status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3154 audio_patch_handle_t *handle)
3155{
3156 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003157
3158 // store new device and send to effects
3159 audio_devices_t type = AUDIO_DEVICE_NONE;
3160 for (unsigned int i = 0; i < patch->num_sinks; i++) {
3161 type |= patch->sinks[i].ext.device.type;
3162 }
3163
3164#ifdef ADD_BATTERY_DATA
3165 // when changing the audio output device, call addBatteryData to notify
3166 // the change
3167 if (mOutDevice != type) {
3168 uint32_t params = 0;
3169 // check whether speaker is on
3170 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3171 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003172 }
3173
Eric Laurent054d9d32015-04-24 08:48:48 -07003174 audio_devices_t deviceWithoutSpeaker
3175 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3176 // check if any other device (except speaker) is on
3177 if (type & deviceWithoutSpeaker) {
3178 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3179 }
3180
3181 if (params != 0) {
3182 addBatteryData(params);
3183 }
3184 }
3185#endif
3186
3187 for (size_t i = 0; i < mEffectChains.size(); i++) {
3188 mEffectChains[i]->setDevice_l(type);
3189 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003190
3191 // mPrevOutDevice is the latest device set by createAudioPatch_l(). It is not set when
3192 // the thread is created so that the first patch creation triggers an ioConfigChanged callback
3193 bool configChanged = mPrevOutDevice != type;
Eric Laurent054d9d32015-04-24 08:48:48 -07003194 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003195 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003196
3197 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003198 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
3199 status = hwDevice->create_audio_patch(hwDevice,
3200 patch->num_sources,
3201 patch->sources,
3202 patch->num_sinks,
3203 patch->sinks,
3204 handle);
3205 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003206 char *address;
3207 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3208 //FIXME: we only support address on first sink with HAL version < 3.0
3209 address = audio_device_address_to_parameter(
3210 patch->sinks[0].ext.device.type,
3211 patch->sinks[0].ext.device.address);
3212 } else {
3213 address = (char *)calloc(1, 1);
3214 }
3215 AudioParameter param = AudioParameter(String8(address));
3216 free(address);
3217 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), (int)type);
3218 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3219 param.toString().string());
3220 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003221 }
Eric Laurente8726fe2015-06-26 09:39:24 -07003222 if (configChanged) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003223 mPrevOutDevice = type;
Eric Laurente8726fe2015-06-26 09:39:24 -07003224 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
3225 }
Eric Laurent1c333e22014-05-20 10:48:17 -07003226 return status;
3227}
3228
Eric Laurent054d9d32015-04-24 08:48:48 -07003229status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3230{
3231 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3232 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3233 if (mFastMixer != 0) {
3234 FastMixerStateQueue *sq = mFastMixer->sq();
3235 FastMixerState *state = sq->begin();
3236 if (!(state->mCommand & FastMixerState::IDLE)) {
3237 previousCommand = state->mCommand;
3238 state->mCommand = FastMixerState::HOT_IDLE;
3239 sq->end();
3240 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3241 } else {
3242 sq->end(false /*didModify*/);
3243 }
3244 }
3245
3246 status_t status = PlaybackThread::releaseAudioPatch_l(handle);
3247
3248 if (!(previousCommand & FastMixerState::IDLE)) {
3249 ALOG_ASSERT(mFastMixer != 0);
3250 FastMixerStateQueue *sq = mFastMixer->sq();
3251 FastMixerState *state = sq->begin();
3252 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3253 state->mCommand = previousCommand;
3254 sq->end();
3255 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3256 }
3257
3258 return status;
3259}
3260
Eric Laurent1c333e22014-05-20 10:48:17 -07003261status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3262{
3263 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003264
3265 mOutDevice = AUDIO_DEVICE_NONE;
3266
Eric Laurent1c333e22014-05-20 10:48:17 -07003267 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
3268 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
3269 status = hwDevice->release_audio_patch(hwDevice, handle);
3270 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003271 AudioParameter param;
3272 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
3273 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3274 param.toString().string());
Eric Laurent1c333e22014-05-20 10:48:17 -07003275 }
3276 return status;
3277}
3278
Eric Laurent83b88082014-06-20 18:31:16 -07003279void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3280{
3281 Mutex::Autolock _l(mLock);
3282 mTracks.add(track);
3283}
3284
3285void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3286{
3287 Mutex::Autolock _l(mLock);
3288 destroyTrack_l(track);
3289}
3290
3291void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
3292{
3293 ThreadBase::getAudioPortConfig(config);
3294 config->role = AUDIO_PORT_ROLE_SOURCE;
3295 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3296 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
3297}
3298
Eric Laurent81784c32012-11-19 14:55:58 -08003299// ----------------------------------------------------------------------------
3300
3301AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurent72e3f392015-05-20 14:43:50 -07003302 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
3303 : PlaybackThread(audioFlinger, output, id, device, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08003304 // mAudioMixer below
3305 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08003306 mFastMixerFutex(0),
3307 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08003308 // mOutputSink below
3309 // mPipeSink below
3310 // mNormalSink below
3311{
3312 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07003313 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, "
Eric Laurent81784c32012-11-19 14:55:58 -08003314 "mFrameCount=%d, mNormalFrameCount=%d",
3315 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3316 mNormalFrameCount);
3317 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3318
Andy Hungfbfc3952015-01-15 13:33:51 -08003319 if (type == DUPLICATING) {
3320 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3321 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3322 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3323 return;
3324 }
Eric Laurent81784c32012-11-19 14:55:58 -08003325 // create an NBAIO sink for the HAL output stream, and negotiate
3326 mOutputSink = new AudioStreamOutSink(output->stream);
3327 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003328 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Eric Laurent81784c32012-11-19 14:55:58 -08003329 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
3330 ALOG_ASSERT(index == 0);
3331
3332 // initialize fast mixer depending on configuration
3333 bool initFastMixer;
3334 switch (kUseFastMixer) {
3335 case FastMixer_Never:
3336 initFastMixer = false;
3337 break;
3338 case FastMixer_Always:
3339 initFastMixer = true;
3340 break;
3341 case FastMixer_Static:
3342 case FastMixer_Dynamic:
3343 initFastMixer = mFrameCount < mNormalFrameCount;
3344 break;
3345 }
3346 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003347 audio_format_t fastMixerFormat;
3348 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3349 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3350 } else {
3351 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3352 }
3353 if (mFormat != fastMixerFormat) {
3354 // change our Sink format to accept our intermediate precision
3355 mFormat = fastMixerFormat;
3356 free(mSinkBuffer);
3357 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3358 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3359 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3360 }
Eric Laurent81784c32012-11-19 14:55:58 -08003361
3362 // create a MonoPipe to connect our submix to FastMixer
3363 NBAIO_Format format = mOutputSink->format();
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003364 NBAIO_Format origformat = format;
Andy Hung1258c1a2014-05-23 21:22:17 -07003365 // adjust format to match that of the Fast Mixer
Glenn Kasten97b7b752014-09-28 13:04:24 -07003366 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003367 format.mFormat = fastMixerFormat;
3368 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3369
Eric Laurent81784c32012-11-19 14:55:58 -08003370 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3371 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3372 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3373 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3374 const NBAIO_Format offers[1] = {format};
3375 size_t numCounterOffers = 0;
3376 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
3377 ALOG_ASSERT(index == 0);
3378 monoPipe->setAvgFrames((mScreenState & 1) ?
3379 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3380 mPipeSink = monoPipe;
3381
Glenn Kasten46909e72013-02-26 09:20:22 -08003382#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08003383 if (mTeeSinkOutputEnabled) {
3384 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003385 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
3386 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08003387 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003388 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003389 ALOG_ASSERT(index == 0);
3390 mTeeSink = teeSink;
3391 PipeReader *teeSource = new PipeReader(*teeSink);
3392 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003393 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003394 ALOG_ASSERT(index == 0);
3395 mTeeSource = teeSource;
3396 }
Glenn Kasten46909e72013-02-26 09:20:22 -08003397#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003398
3399 // create fast mixer and configure it initially with just one fast track for our submix
3400 mFastMixer = new FastMixer();
3401 FastMixerStateQueue *sq = mFastMixer->sq();
3402#ifdef STATE_QUEUE_DUMP
3403 sq->setObserverDump(&mStateQueueObserverDump);
3404 sq->setMutatorDump(&mStateQueueMutatorDump);
3405#endif
3406 FastMixerState *state = sq->begin();
3407 FastTrack *fastTrack = &state->mFastTracks[0];
3408 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3409 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3410 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003411 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3412 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003413 fastTrack->mGeneration++;
3414 state->mFastTracksGen++;
3415 state->mTrackMask = 1;
3416 // fast mixer will use the HAL output sink
3417 state->mOutputSink = mOutputSink.get();
3418 state->mOutputSinkGen++;
3419 state->mFrameCount = mFrameCount;
3420 state->mCommand = FastMixerState::COLD_IDLE;
3421 // already done in constructor initialization list
3422 //mFastMixerFutex = 0;
3423 state->mColdFutexAddr = &mFastMixerFutex;
3424 state->mColdGen++;
3425 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08003426#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003427 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08003428#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08003429 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3430 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003431 sq->end();
3432 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3433
3434 // start the fast mixer
3435 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3436 pid_t tid = mFastMixer->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003437 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003438
3439#ifdef AUDIO_WATCHDOG
3440 // create and start the watchdog
3441 mAudioWatchdog = new AudioWatchdog();
3442 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3443 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3444 tid = mAudioWatchdog->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003445 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003446#endif
3447
Eric Laurent81784c32012-11-19 14:55:58 -08003448 }
3449
3450 switch (kUseFastMixer) {
3451 case FastMixer_Never:
3452 case FastMixer_Dynamic:
3453 mNormalSink = mOutputSink;
3454 break;
3455 case FastMixer_Always:
3456 mNormalSink = mPipeSink;
3457 break;
3458 case FastMixer_Static:
3459 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3460 break;
3461 }
3462}
3463
3464AudioFlinger::MixerThread::~MixerThread()
3465{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003466 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003467 FastMixerStateQueue *sq = mFastMixer->sq();
3468 FastMixerState *state = sq->begin();
3469 if (state->mCommand == FastMixerState::COLD_IDLE) {
3470 int32_t old = android_atomic_inc(&mFastMixerFutex);
3471 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003472 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003473 }
3474 }
3475 state->mCommand = FastMixerState::EXIT;
3476 sq->end();
3477 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3478 mFastMixer->join();
3479 // Though the fast mixer thread has exited, it's state queue is still valid.
3480 // We'll use that extract the final state which contains one remaining fast track
3481 // corresponding to our sub-mix.
3482 state = sq->begin();
3483 ALOG_ASSERT(state->mTrackMask == 1);
3484 FastTrack *fastTrack = &state->mFastTracks[0];
3485 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3486 delete fastTrack->mBufferProvider;
3487 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003488 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003489#ifdef AUDIO_WATCHDOG
3490 if (mAudioWatchdog != 0) {
3491 mAudioWatchdog->requestExit();
3492 mAudioWatchdog->requestExitAndWait();
3493 mAudioWatchdog.clear();
3494 }
3495#endif
3496 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003497 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003498 delete mAudioMixer;
3499}
3500
3501
3502uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3503{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003504 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003505 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3506 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3507 }
3508 return latency;
3509}
3510
3511
3512void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3513{
3514 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3515}
3516
Eric Laurentbfb1b832013-01-07 09:53:42 -08003517ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003518{
3519 // FIXME we should only do one push per cycle; confirm this is true
3520 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003521 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003522 FastMixerStateQueue *sq = mFastMixer->sq();
3523 FastMixerState *state = sq->begin();
3524 if (state->mCommand != FastMixerState::MIX_WRITE &&
3525 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3526 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07003527
3528 // FIXME workaround for first HAL write being CPU bound on some devices
3529 ATRACE_BEGIN("write");
3530 mOutput->write((char *)mSinkBuffer, 0);
3531 ATRACE_END();
3532
Eric Laurent81784c32012-11-19 14:55:58 -08003533 int32_t old = android_atomic_inc(&mFastMixerFutex);
3534 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003535 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003536 }
3537#ifdef AUDIO_WATCHDOG
3538 if (mAudioWatchdog != 0) {
3539 mAudioWatchdog->resume();
3540 }
3541#endif
3542 }
3543 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08003544#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003545 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08003546 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08003547#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003548 sq->end();
3549 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3550 if (kUseFastMixer == FastMixer_Dynamic) {
3551 mNormalSink = mPipeSink;
3552 }
3553 } else {
3554 sq->end(false /*didModify*/);
3555 }
3556 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003557 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003558}
3559
3560void AudioFlinger::MixerThread::threadLoop_standby()
3561{
3562 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003563 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003564 FastMixerStateQueue *sq = mFastMixer->sq();
3565 FastMixerState *state = sq->begin();
3566 if (!(state->mCommand & FastMixerState::IDLE)) {
3567 state->mCommand = FastMixerState::COLD_IDLE;
3568 state->mColdFutexAddr = &mFastMixerFutex;
3569 state->mColdGen++;
3570 mFastMixerFutex = 0;
3571 sq->end();
3572 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3573 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3574 if (kUseFastMixer == FastMixer_Dynamic) {
3575 mNormalSink = mOutputSink;
3576 }
3577#ifdef AUDIO_WATCHDOG
3578 if (mAudioWatchdog != 0) {
3579 mAudioWatchdog->pause();
3580 }
3581#endif
3582 } else {
3583 sq->end(false /*didModify*/);
3584 }
3585 }
3586 PlaybackThread::threadLoop_standby();
3587}
3588
Eric Laurentbfb1b832013-01-07 09:53:42 -08003589bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3590{
3591 return false;
3592}
3593
3594bool AudioFlinger::PlaybackThread::shouldStandby_l()
3595{
3596 return !mStandby;
3597}
3598
3599bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3600{
3601 Mutex::Autolock _l(mLock);
3602 return waitingAsyncCallback_l();
3603}
3604
Eric Laurent81784c32012-11-19 14:55:58 -08003605// shared by MIXER and DIRECT, overridden by DUPLICATING
3606void AudioFlinger::PlaybackThread::threadLoop_standby()
3607{
3608 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08003609 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003610 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003611 // discard any pending drain or write ack by incrementing sequence
3612 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3613 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003614 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003615 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3616 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003617 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003618 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003619}
3620
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003621void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3622{
3623 ALOGV("signal playback thread");
3624 broadcast_l();
3625}
3626
Eric Laurent81784c32012-11-19 14:55:58 -08003627void AudioFlinger::MixerThread::threadLoop_mix()
3628{
Eric Laurent81784c32012-11-19 14:55:58 -08003629 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08003630 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08003631 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003632 // increase sleep time progressively when application underrun condition clears.
3633 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3634 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3635 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003636 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003637 sleepTimeShift--;
3638 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003639 mSleepTimeUs = 0;
3640 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08003641 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003642
Eric Laurent81784c32012-11-19 14:55:58 -08003643}
3644
3645void AudioFlinger::MixerThread::threadLoop_sleepTime()
3646{
3647 // If no tracks are ready, sleep once for the duration of an output
3648 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003649 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003650 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003651 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
3652 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
3653 mSleepTimeUs = kMinThreadSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003654 }
3655 // reduce sleep time in case of consecutive application underruns to avoid
3656 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3657 // duration we would end up writing less data than needed by the audio HAL if
3658 // the condition persists.
3659 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3660 sleepTimeShift++;
3661 }
3662 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003663 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003664 }
3665 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003666 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3667 // before effects processing or output.
3668 if (mMixerBufferValid) {
3669 memset(mMixerBuffer, 0, mMixerBufferSize);
3670 } else {
3671 memset(mSinkBuffer, 0, mSinkBufferSize);
3672 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003673 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003674 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3675 "anticipated start");
3676 }
3677 // TODO add standby time extension fct of effect tail
3678}
3679
3680// prepareTracks_l() must be called with ThreadBase::mLock held
3681AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3682 Vector< sp<Track> > *tracksToRemove)
3683{
3684
3685 mixer_state mixerStatus = MIXER_IDLE;
3686 // find out which tracks need to be processed
3687 size_t count = mActiveTracks.size();
3688 size_t mixedTracks = 0;
3689 size_t tracksWithEffect = 0;
3690 // counts only _active_ fast tracks
3691 size_t fastTracks = 0;
3692 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
3693
3694 float masterVolume = mMasterVolume;
3695 bool masterMute = mMasterMute;
3696
3697 if (masterMute) {
3698 masterVolume = 0;
3699 }
3700 // Delegate master volume control to effect in output mix effect chain if needed
3701 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3702 if (chain != 0) {
3703 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
3704 chain->setVolume_l(&v, &v);
3705 masterVolume = (float)((v + (1 << 23)) >> 24);
3706 chain.clear();
3707 }
3708
3709 // prepare a new state to push
3710 FastMixerStateQueue *sq = NULL;
3711 FastMixerState *state = NULL;
3712 bool didModify = false;
3713 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003714 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003715 sq = mFastMixer->sq();
3716 state = sq->begin();
3717 }
3718
Andy Hung69aed5f2014-02-25 17:24:40 -08003719 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08003720 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08003721
Eric Laurent81784c32012-11-19 14:55:58 -08003722 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003723 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003724 if (t == 0) {
3725 continue;
3726 }
3727
3728 // this const just means the local variable doesn't change
3729 Track* const track = t.get();
3730
3731 // process fast tracks
3732 if (track->isFastTrack()) {
3733
3734 // It's theoretically possible (though unlikely) for a fast track to be created
3735 // and then removed within the same normal mix cycle. This is not a problem, as
3736 // the track never becomes active so it's fast mixer slot is never touched.
3737 // The converse, of removing an (active) track and then creating a new track
3738 // at the identical fast mixer slot within the same normal mix cycle,
3739 // is impossible because the slot isn't marked available until the end of each cycle.
3740 int j = track->mFastIndex;
3741 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
3742 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
3743 FastTrack *fastTrack = &state->mFastTracks[j];
3744
3745 // Determine whether the track is currently in underrun condition,
3746 // and whether it had a recent underrun.
3747 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
3748 FastTrackUnderruns underruns = ftDump->mUnderruns;
3749 uint32_t recentFull = (underruns.mBitFields.mFull -
3750 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
3751 uint32_t recentPartial = (underruns.mBitFields.mPartial -
3752 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
3753 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
3754 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
3755 uint32_t recentUnderruns = recentPartial + recentEmpty;
3756 track->mObservedUnderruns = underruns;
3757 // don't count underruns that occur while stopping or pausing
3758 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07003759 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
3760 recentUnderruns > 0) {
3761 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
3762 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Phil Burk2812d9e2016-01-04 10:34:30 -08003763 } else {
3764 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Eric Laurent81784c32012-11-19 14:55:58 -08003765 }
3766
3767 // This is similar to the state machine for normal tracks,
3768 // with a few modifications for fast tracks.
3769 bool isActive = true;
3770 switch (track->mState) {
3771 case TrackBase::STOPPING_1:
3772 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08003773 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003774 track->mState = TrackBase::STOPPING_2;
3775 }
3776 break;
3777 case TrackBase::PAUSING:
3778 // ramp down is not yet implemented
3779 track->setPaused();
3780 break;
3781 case TrackBase::RESUMING:
3782 // ramp up is not yet implemented
3783 track->mState = TrackBase::ACTIVE;
3784 break;
3785 case TrackBase::ACTIVE:
3786 if (recentFull > 0 || recentPartial > 0) {
3787 // track has provided at least some frames recently: reset retry count
3788 track->mRetryCount = kMaxTrackRetries;
3789 }
3790 if (recentUnderruns == 0) {
3791 // no recent underruns: stay active
3792 break;
3793 }
3794 // there has recently been an underrun of some kind
3795 if (track->sharedBuffer() == 0) {
3796 // were any of the recent underruns "empty" (no frames available)?
3797 if (recentEmpty == 0) {
3798 // no, then ignore the partial underruns as they are allowed indefinitely
3799 break;
3800 }
3801 // there has recently been an "empty" underrun: decrement the retry counter
3802 if (--(track->mRetryCount) > 0) {
3803 break;
3804 }
3805 // indicate to client process that the track was disabled because of underrun;
3806 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003807 android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003808 // remove from active list, but state remains ACTIVE [confusing but true]
3809 isActive = false;
3810 break;
3811 }
3812 // fall through
3813 case TrackBase::STOPPING_2:
3814 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003815 case TrackBase::STOPPED:
3816 case TrackBase::FLUSHED: // flush() while active
3817 // Check for presentation complete if track is inactive
3818 // We have consumed all the buffers of this track.
3819 // This would be incomplete if we auto-paused on underrun
3820 {
3821 size_t audioHALFrames =
3822 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3823 size_t framesWritten = mBytesWritten / mFrameSize;
3824 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
3825 // track stays in active list until presentation is complete
3826 break;
3827 }
3828 }
3829 if (track->isStopping_2()) {
3830 track->mState = TrackBase::STOPPED;
3831 }
3832 if (track->isStopped()) {
3833 // Can't reset directly, as fast mixer is still polling this track
3834 // track->reset();
3835 // So instead mark this track as needing to be reset after push with ack
3836 resetMask |= 1 << i;
3837 }
3838 isActive = false;
3839 break;
3840 case TrackBase::IDLE:
3841 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08003842 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08003843 }
3844
3845 if (isActive) {
3846 // was it previously inactive?
3847 if (!(state->mTrackMask & (1 << j))) {
3848 ExtendedAudioBufferProvider *eabp = track;
3849 VolumeProvider *vp = track;
3850 fastTrack->mBufferProvider = eabp;
3851 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08003852 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003853 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08003854 fastTrack->mGeneration++;
3855 state->mTrackMask |= 1 << j;
3856 didModify = true;
3857 // no acknowledgement required for newly active tracks
3858 }
3859 // cache the combined master volume and stream type volume for fast mixer; this
3860 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08003861 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08003862 ++fastTracks;
3863 } else {
3864 // was it previously active?
3865 if (state->mTrackMask & (1 << j)) {
3866 fastTrack->mBufferProvider = NULL;
3867 fastTrack->mGeneration++;
3868 state->mTrackMask &= ~(1 << j);
3869 didModify = true;
3870 // If any fast tracks were removed, we must wait for acknowledgement
3871 // because we're about to decrement the last sp<> on those tracks.
3872 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3873 } else {
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08003874 LOG_ALWAYS_FATAL("fast track %d should have been active; "
3875 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
3876 j, track->mState, state->mTrackMask, recentUnderruns,
3877 track->sharedBuffer() != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08003878 }
3879 tracksToRemove->add(track);
3880 // Avoids a misleading display in dumpsys
3881 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
3882 }
3883 continue;
3884 }
3885
3886 { // local variable scope to avoid goto warning
3887
3888 audio_track_cblk_t* cblk = track->cblk();
3889
3890 // The first time a track is added we wait
3891 // for all its buffers to be filled before processing it
3892 int name = track->name();
3893 // make sure that we have enough frames to mix one full buffer.
3894 // enforce this condition only once to enable draining the buffer in case the client
3895 // app does not call stop() and relies on underrun to stop:
3896 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
3897 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003898 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07003899 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07003900 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07003901
3902 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07003903 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07003904 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
3905 // add frames already consumed but not yet released by the resampler
3906 // because mAudioTrackServerProxy->framesReady() will include these frames
3907 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
3908
Eric Laurent81784c32012-11-19 14:55:58 -08003909 uint32_t minFrames = 1;
3910 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
3911 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003912 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08003913 }
Eric Laurent13e4c962013-12-20 17:36:01 -08003914
3915 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07003916 if (ATRACE_ENABLED()) {
3917 // I wish we had formatted trace names
3918 char traceName[16];
3919 strcpy(traceName, "nRdy");
3920 int name = track->name();
3921 if (AudioMixer::TRACK0 <= name &&
3922 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
3923 name -= AudioMixer::TRACK0;
3924 traceName[4] = (name / 10) + '0';
3925 traceName[5] = (name % 10) + '0';
3926 } else {
3927 traceName[4] = '?';
3928 traceName[5] = '?';
3929 }
3930 traceName[6] = '\0';
3931 ATRACE_INT(traceName, framesReady);
3932 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003933 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08003934 !track->isPaused() && !track->isTerminated())
3935 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003936 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003937
3938 mixedTracks++;
3939
Andy Hung69aed5f2014-02-25 17:24:40 -08003940 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
3941 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08003942 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08003943 if (track->mainBuffer() != mSinkBuffer &&
3944 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08003945 if (mEffectBufferEnabled) {
3946 mEffectBufferValid = true; // Later can set directly.
3947 }
Eric Laurent81784c32012-11-19 14:55:58 -08003948 chain = getEffectChain_l(track->sessionId());
3949 // Delegate volume control to effect in track effect chain if needed
3950 if (chain != 0) {
3951 tracksWithEffect++;
3952 } else {
3953 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
3954 "session %d",
3955 name, track->sessionId());
3956 }
3957 }
3958
3959
3960 int param = AudioMixer::VOLUME;
3961 if (track->mFillingUpStatus == Track::FS_FILLED) {
3962 // no ramp for the first volume setting
3963 track->mFillingUpStatus = Track::FS_ACTIVE;
3964 if (track->mState == TrackBase::RESUMING) {
3965 track->mState = TrackBase::ACTIVE;
3966 param = AudioMixer::RAMP_VOLUME;
3967 }
3968 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003969 // FIXME should not make a decision based on mServer
3970 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003971 // If the track is stopped before the first frame was mixed,
3972 // do not apply ramp
3973 param = AudioMixer::RAMP_VOLUME;
3974 }
3975
3976 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07003977 uint32_t vl, vr; // in U8.24 integer format
3978 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08003979 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07003980 vl = vr = 0;
3981 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08003982 if (track->isPausing()) {
3983 track->setPaused();
3984 }
3985 } else {
3986
3987 // read original volumes with volume control
3988 float typeVolume = mStreamTypes[track->streamType()].volume;
3989 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003990 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07003991 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07003992 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
3993 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08003994 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07003995 if (vlf > GAIN_FLOAT_UNITY) {
3996 ALOGV("Track left volume out of range: %.3g", vlf);
3997 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003998 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07003999 if (vrf > GAIN_FLOAT_UNITY) {
4000 ALOGV("Track right volume out of range: %.3g", vrf);
4001 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004002 }
4003 // now apply the master volume and stream type volume
Andy Hung6be49402014-05-30 10:42:03 -07004004 vlf *= v;
4005 vrf *= v;
Eric Laurent81784c32012-11-19 14:55:58 -08004006 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07004007 // then derive vl and vr as U8.24 versions for the effect chain
4008 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
4009 vl = (uint32_t) (scaleto8_24 * vlf);
4010 vr = (uint32_t) (scaleto8_24 * vrf);
4011 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08004012 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08004013 // send level comes from shared memory and so may be corrupt
4014 if (sendLevel > MAX_GAIN_INT) {
4015 ALOGV("Track send level out of range: %04X", sendLevel);
4016 sendLevel = MAX_GAIN_INT;
4017 }
Andy Hung6be49402014-05-30 10:42:03 -07004018 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
4019 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08004020 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004021
Eric Laurent81784c32012-11-19 14:55:58 -08004022 // Delegate volume control to effect in track effect chain if needed
4023 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
4024 // Do not ramp volume if volume is controlled by effect
4025 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08004026 // Update remaining floating point volume levels
4027 vlf = (float)vl / (1 << 24);
4028 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08004029 track->mHasVolumeController = true;
4030 } else {
4031 // force no volume ramp when volume controller was just disabled or removed
4032 // from effect chain to avoid volume spike
4033 if (track->mHasVolumeController) {
4034 param = AudioMixer::VOLUME;
4035 }
4036 track->mHasVolumeController = false;
4037 }
4038
Eric Laurent81784c32012-11-19 14:55:58 -08004039 // XXX: these things DON'T need to be done each time
4040 mAudioMixer->setBufferProvider(name, track);
4041 mAudioMixer->enable(name);
4042
Andy Hung6be49402014-05-30 10:42:03 -07004043 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
4044 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
4045 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08004046 mAudioMixer->setParameter(
4047 name,
4048 AudioMixer::TRACK,
4049 AudioMixer::FORMAT, (void *)track->format());
4050 mAudioMixer->setParameter(
4051 name,
4052 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004053 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07004054 mAudioMixer->setParameter(
4055 name,
4056 AudioMixer::TRACK,
4057 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08004058 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07004059 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004060 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08004061 if (reqSampleRate == 0) {
4062 reqSampleRate = mSampleRate;
4063 } else if (reqSampleRate > maxSampleRate) {
4064 reqSampleRate = maxSampleRate;
4065 }
Eric Laurent81784c32012-11-19 14:55:58 -08004066 mAudioMixer->setParameter(
4067 name,
4068 AudioMixer::RESAMPLE,
4069 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004070 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004071
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004072 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004073 mAudioMixer->setParameter(
4074 name,
4075 AudioMixer::TIMESTRETCH,
4076 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004077 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004078
Andy Hung69aed5f2014-02-25 17:24:40 -08004079 /*
4080 * Select the appropriate output buffer for the track.
4081 *
Andy Hung98ef9782014-03-04 14:46:50 -08004082 * Tracks with effects go into their own effects chain buffer
4083 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08004084 *
4085 * Other tracks can use mMixerBuffer for higher precision
4086 * channel accumulation. If this buffer is enabled
4087 * (mMixerBufferEnabled true), then selected tracks will accumulate
4088 * into it.
4089 *
4090 */
4091 if (mMixerBufferEnabled
4092 && (track->mainBuffer() == mSinkBuffer
4093 || track->mainBuffer() == mMixerBuffer)) {
4094 mAudioMixer->setParameter(
4095 name,
4096 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004097 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08004098 mAudioMixer->setParameter(
4099 name,
4100 AudioMixer::TRACK,
4101 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
4102 // TODO: override track->mainBuffer()?
4103 mMixerBufferValid = true;
4104 } else {
4105 mAudioMixer->setParameter(
4106 name,
4107 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004108 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08004109 mAudioMixer->setParameter(
4110 name,
4111 AudioMixer::TRACK,
4112 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
4113 }
Eric Laurent81784c32012-11-19 14:55:58 -08004114 mAudioMixer->setParameter(
4115 name,
4116 AudioMixer::TRACK,
4117 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
4118
4119 // reset retry count
4120 track->mRetryCount = kMaxTrackRetries;
4121
4122 // If one track is ready, set the mixer ready if:
4123 // - the mixer was not ready during previous round OR
4124 // - no other track is not ready
4125 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
4126 mixerStatus != MIXER_TRACKS_ENABLED) {
4127 mixerStatus = MIXER_TRACKS_READY;
4128 }
4129 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004130 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hung08fb1742015-05-31 23:22:10 -07004131 ALOGV("track(%p) underrun, framesReady(%zu) < framesDesired(%zd)",
4132 track, framesReady, desiredFrames);
Glenn Kasten82aaf942013-07-17 16:05:07 -07004133 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08004134 } else {
4135 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004136 }
Phil Burk2812d9e2016-01-04 10:34:30 -08004137
Eric Laurent81784c32012-11-19 14:55:58 -08004138 // clear effect chain input buffer if an active track underruns to avoid sending
4139 // previous audio buffer again to effects
4140 chain = getEffectChain_l(track->sessionId());
4141 if (chain != 0) {
4142 chain->clearInputBuffer();
4143 }
4144
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004145 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004146 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
4147 track->isStopped() || track->isPaused()) {
4148 // We have consumed all the buffers of this track.
4149 // Remove it from the list of active tracks.
4150 // TODO: use actual buffer filling status instead of latency when available from
4151 // audio HAL
4152 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
4153 size_t framesWritten = mBytesWritten / mFrameSize;
4154 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
4155 if (track->isStopped()) {
4156 track->reset();
4157 }
4158 tracksToRemove->add(track);
4159 }
4160 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08004161 // No buffers for this track. Give it a few chances to
4162 // fill a buffer, then remove it from active list.
4163 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004164 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004165 tracksToRemove->add(track);
4166 // indicate to client process that the track was disabled because of underrun;
4167 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07004168 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08004169 // If one track is not ready, mark the mixer also not ready if:
4170 // - the mixer was ready during previous round OR
4171 // - no other track is ready
4172 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
4173 mixerStatus != MIXER_TRACKS_READY) {
4174 mixerStatus = MIXER_TRACKS_ENABLED;
4175 }
4176 }
4177 mAudioMixer->disable(name);
4178 }
4179
4180 } // local variable scope to avoid goto warning
4181track_is_ready: ;
4182
4183 }
4184
4185 // Push the new FastMixer state if necessary
4186 bool pauseAudioWatchdog = false;
4187 if (didModify) {
4188 state->mFastTracksGen++;
4189 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4190 if (kUseFastMixer == FastMixer_Dynamic &&
4191 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4192 state->mCommand = FastMixerState::COLD_IDLE;
4193 state->mColdFutexAddr = &mFastMixerFutex;
4194 state->mColdGen++;
4195 mFastMixerFutex = 0;
4196 if (kUseFastMixer == FastMixer_Dynamic) {
4197 mNormalSink = mOutputSink;
4198 }
4199 // If we go into cold idle, need to wait for acknowledgement
4200 // so that fast mixer stops doing I/O.
4201 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4202 pauseAudioWatchdog = true;
4203 }
Eric Laurent81784c32012-11-19 14:55:58 -08004204 }
4205 if (sq != NULL) {
4206 sq->end(didModify);
4207 sq->push(block);
4208 }
4209#ifdef AUDIO_WATCHDOG
4210 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4211 mAudioWatchdog->pause();
4212 }
4213#endif
4214
4215 // Now perform the deferred reset on fast tracks that have stopped
4216 while (resetMask != 0) {
4217 size_t i = __builtin_ctz(resetMask);
4218 ALOG_ASSERT(i < count);
4219 resetMask &= ~(1 << i);
4220 sp<Track> t = mActiveTracks[i].promote();
4221 if (t == 0) {
4222 continue;
4223 }
4224 Track* track = t.get();
4225 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
4226 track->reset();
4227 }
4228
4229 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004230 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004231
Eric Laurent97d547d2014-09-02 14:45:53 -07004232 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
4233 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07004234 }
4235
4236 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07004237 // as long as there are effects we should clear the effects buffer, to avoid
4238 // passing a non-clean buffer to the effect chain
4239 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07004240 }
Andy Hung69aed5f2014-02-25 17:24:40 -08004241 // sink or mix buffer must be cleared if all tracks are connected to an
4242 // effect chain as in this case the mixer will not write to the sink or mix buffer
4243 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08004244 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4245 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08004246 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08004247 if (mMixerBufferValid) {
4248 memset(mMixerBuffer, 0, mMixerBufferSize);
4249 // TODO: In testing, mSinkBuffer below need not be cleared because
4250 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
4251 // after mixing.
4252 //
4253 // To enforce this guarantee:
4254 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4255 // (mixedTracks == 0 && fastTracks > 0))
4256 // must imply MIXER_TRACKS_READY.
4257 // Later, we may clear buffers regardless, and skip much of this logic.
4258 }
Andy Hung98ef9782014-03-04 14:46:50 -08004259 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07004260 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004261 }
4262
4263 // if any fast tracks, then status is ready
4264 mMixerStatusIgnoringFastTracks = mixerStatus;
4265 if (fastTracks > 0) {
4266 mixerStatus = MIXER_TRACKS_READY;
4267 }
4268 return mixerStatus;
4269}
4270
4271// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07004272int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
4273 audio_format_t format, int sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08004274{
Andy Hunge8a1ced2014-05-09 15:02:21 -07004275 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08004276}
4277
4278// deleteTrackName_l() must be called with ThreadBase::mLock held
4279void AudioFlinger::MixerThread::deleteTrackName_l(int name)
4280{
4281 ALOGV("remove track (%d) and delete from mixer", name);
4282 mAudioMixer->deleteTrackName(name);
4283}
4284
Eric Laurent10351942014-05-08 18:49:52 -07004285// checkForNewParameter_l() must be called with ThreadBase::mLock held
4286bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
4287 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004288{
Eric Laurent81784c32012-11-19 14:55:58 -08004289 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08004290 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004291
Eric Laurent10351942014-05-08 18:49:52 -07004292 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004293
Eric Laurent10351942014-05-08 18:49:52 -07004294 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
4295 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004296 if (mFastMixer != 0) {
Eric Laurent10351942014-05-08 18:49:52 -07004297 FastMixerStateQueue *sq = mFastMixer->sq();
4298 FastMixerState *state = sq->begin();
4299 if (!(state->mCommand & FastMixerState::IDLE)) {
4300 previousCommand = state->mCommand;
4301 state->mCommand = FastMixerState::HOT_IDLE;
4302 sq->end();
4303 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
4304 } else {
4305 sq->end(false /*didModify*/);
Eric Laurent81784c32012-11-19 14:55:58 -08004306 }
Eric Laurent10351942014-05-08 18:49:52 -07004307 }
Eric Laurent81784c32012-11-19 14:55:58 -08004308
Eric Laurent10351942014-05-08 18:49:52 -07004309 AudioParameter param = AudioParameter(keyValuePair);
4310 int value;
4311 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4312 reconfig = true;
4313 }
4314 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004315 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004316 status = BAD_VALUE;
4317 } else {
4318 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08004319 reconfig = true;
4320 }
Eric Laurent10351942014-05-08 18:49:52 -07004321 }
4322 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004323 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004324 status = BAD_VALUE;
4325 } else {
4326 // no need to save value, since it's constant
4327 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004328 }
Eric Laurent10351942014-05-08 18:49:52 -07004329 }
4330 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4331 // do not accept frame count changes if tracks are open as the track buffer
4332 // size depends on frame count and correct behavior would not be guaranteed
4333 // if frame count is changed after track creation
4334 if (!mTracks.isEmpty()) {
4335 status = INVALID_OPERATION;
4336 } else {
4337 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004338 }
Eric Laurent10351942014-05-08 18:49:52 -07004339 }
4340 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004341#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07004342 // when changing the audio output device, call addBatteryData to notify
4343 // the change
4344 if (mOutDevice != value) {
4345 uint32_t params = 0;
4346 // check whether speaker is on
4347 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
4348 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08004349 }
Eric Laurent10351942014-05-08 18:49:52 -07004350
4351 audio_devices_t deviceWithoutSpeaker
4352 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
4353 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07004354 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07004355 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4356 }
4357
4358 if (params != 0) {
4359 addBatteryData(params);
4360 }
4361 }
Eric Laurent81784c32012-11-19 14:55:58 -08004362#endif
4363
Eric Laurent10351942014-05-08 18:49:52 -07004364 // forward device change to effects that have requested to be
4365 // aware of attached audio device.
4366 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08004367 a2dpDeviceChanged =
4368 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07004369 mOutDevice = value;
4370 for (size_t i = 0; i < mEffectChains.size(); i++) {
4371 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08004372 }
4373 }
Eric Laurent10351942014-05-08 18:49:52 -07004374 }
Eric Laurent81784c32012-11-19 14:55:58 -08004375
Eric Laurent10351942014-05-08 18:49:52 -07004376 if (status == NO_ERROR) {
4377 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4378 keyValuePair.string());
4379 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004380 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004381 mStandby = true;
4382 mBytesWritten = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004383 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Eric Laurent10351942014-05-08 18:49:52 -07004384 keyValuePair.string());
Eric Laurent81784c32012-11-19 14:55:58 -08004385 }
Eric Laurent10351942014-05-08 18:49:52 -07004386 if (status == NO_ERROR && reconfig) {
4387 readOutputParameters_l();
4388 delete mAudioMixer;
4389 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4390 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07004391 int name = getTrackName_l(mTracks[i]->mChannelMask,
4392 mTracks[i]->mFormat, mTracks[i]->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07004393 if (name < 0) {
4394 break;
4395 }
4396 mTracks[i]->mName = name;
4397 }
Eric Laurent73e26b62015-04-27 16:55:58 -07004398 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004399 }
Eric Laurent81784c32012-11-19 14:55:58 -08004400 }
4401
4402 if (!(previousCommand & FastMixerState::IDLE)) {
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004403 ALOG_ASSERT(mFastMixer != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08004404 FastMixerStateQueue *sq = mFastMixer->sq();
4405 FastMixerState *state = sq->begin();
4406 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
4407 state->mCommand = previousCommand;
4408 sq->end();
4409 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4410 }
4411
Eric Laurent42537be2016-01-08 17:16:42 -08004412 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08004413}
4414
4415
4416void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
4417{
4418 const size_t SIZE = 256;
4419 char buffer[SIZE];
4420 String8 result;
4421
4422 PlaybackThread::dumpInternals(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07004423 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Elliott Hughes87cebad2014-05-22 10:14:43 -07004424 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Andy Hung2ddee192015-12-18 17:34:44 -08004425 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Eric Laurent81784c32012-11-19 14:55:58 -08004426
4427 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten2f90c512015-12-02 11:40:09 -08004428 // while we are dumping it. It may be inconsistent, but it won't mutate!
4429 // This is a large object so we place it on the heap.
4430 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
4431 const FastMixerDumpState *copy = new FastMixerDumpState(mFastMixerDumpState);
4432 copy->dump(fd);
4433 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08004434
4435#ifdef STATE_QUEUE_DUMP
4436 // Similar for state queue
4437 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4438 observerCopy.dump(fd);
4439 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4440 mutatorCopy.dump(fd);
4441#endif
4442
Glenn Kasten46909e72013-02-26 09:20:22 -08004443#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08004444 // Write the tee output to a .wav file
4445 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08004446#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004447
4448#ifdef AUDIO_WATCHDOG
4449 if (mAudioWatchdog != 0) {
4450 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4451 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4452 wdCopy.dump(fd);
4453 }
4454#endif
4455}
4456
4457uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4458{
4459 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4460}
4461
4462uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4463{
4464 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4465}
4466
4467void AudioFlinger::MixerThread::cacheParameters_l()
4468{
4469 PlaybackThread::cacheParameters_l();
4470
4471 // FIXME: Relaxed timing because of a certain device that can't meet latency
4472 // Should be reduced to 2x after the vendor fixes the driver issue
4473 // increase threshold again due to low power audio mode. The way this warning
4474 // threshold is calculated and its usefulness should be reconsidered anyway.
4475 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4476}
4477
4478// ----------------------------------------------------------------------------
4479
4480AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07004481 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device, bool systemReady)
4482 : PlaybackThread(audioFlinger, output, id, device, DIRECT, systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08004483 // mLeftVolFloat, mRightVolFloat
4484{
4485}
4486
Eric Laurentbfb1b832013-01-07 09:53:42 -08004487AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4488 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07004489 ThreadBase::type_t type, bool systemReady)
4490 : PlaybackThread(audioFlinger, output, id, device, type, systemReady)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004491 // mLeftVolFloat, mRightVolFloat
4492{
4493}
4494
Eric Laurent81784c32012-11-19 14:55:58 -08004495AudioFlinger::DirectOutputThread::~DirectOutputThread()
4496{
4497}
4498
Eric Laurentbfb1b832013-01-07 09:53:42 -08004499void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
4500{
4501 audio_track_cblk_t* cblk = track->cblk();
4502 float left, right;
4503
4504 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4505 left = right = 0;
4506 } else {
4507 float typeVolume = mStreamTypes[track->streamType()].volume;
4508 float v = mMasterVolume * typeVolume;
4509 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004510 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4511 left = float_from_gain(gain_minifloat_unpack_left(vlr));
4512 if (left > GAIN_FLOAT_UNITY) {
4513 left = GAIN_FLOAT_UNITY;
4514 }
4515 left *= v;
4516 right = float_from_gain(gain_minifloat_unpack_right(vlr));
4517 if (right > GAIN_FLOAT_UNITY) {
4518 right = GAIN_FLOAT_UNITY;
4519 }
4520 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004521 }
4522
4523 if (lastTrack) {
4524 if (left != mLeftVolFloat || right != mRightVolFloat) {
4525 mLeftVolFloat = left;
4526 mRightVolFloat = right;
4527
4528 // Convert volumes from float to 8.24
4529 uint32_t vl = (uint32_t)(left * (1 << 24));
4530 uint32_t vr = (uint32_t)(right * (1 << 24));
4531
4532 // Delegate volume control to effect in track effect chain if needed
4533 // only one effect chain can be present on DirectOutputThread, so if
4534 // there is one, the track is connected to it
4535 if (!mEffectChains.isEmpty()) {
4536 mEffectChains[0]->setVolume_l(&vl, &vr);
4537 left = (float)vl / (1 << 24);
4538 right = (float)vr / (1 << 24);
4539 }
4540 if (mOutput->stream->set_volume) {
4541 mOutput->stream->set_volume(mOutput->stream, left, right);
4542 }
4543 }
4544 }
4545}
4546
Phil Burk43b4dcc2015-06-09 16:53:44 -07004547void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
4548{
4549 sp<Track> previousTrack = mPreviousTrack.promote();
4550 sp<Track> latestTrack = mLatestActiveTrack.promote();
4551
Eric Laurent0f0631e2015-07-06 18:01:25 -07004552 if (previousTrack != 0 && latestTrack != 0) {
4553 if (mType == DIRECT) {
4554 if (previousTrack.get() != latestTrack.get()) {
4555 mFlushPending = true;
4556 }
4557 } else /* mType == OFFLOAD */ {
4558 if (previousTrack->sessionId() != latestTrack->sessionId()) {
4559 mFlushPending = true;
4560 }
4561 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004562 }
4563 PlaybackThread::onAddNewTrack_l();
4564}
Eric Laurentbfb1b832013-01-07 09:53:42 -08004565
Eric Laurent81784c32012-11-19 14:55:58 -08004566AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4567 Vector< sp<Track> > *tracksToRemove
4568)
4569{
Eric Laurentd595b7c2013-04-03 17:27:56 -07004570 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08004571 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004572 bool doHwPause = false;
4573 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004574
4575 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07004576 for (size_t i = 0; i < count; i++) {
4577 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08004578 // The track died recently
4579 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004580 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08004581 }
4582
Phil Burk43b4dcc2015-06-09 16:53:44 -07004583 if (t->isInvalid()) {
4584 ALOGW("An invalidated track shouldn't be in active list");
4585 tracksToRemove->add(t);
4586 continue;
4587 }
4588
Eric Laurent81784c32012-11-19 14:55:58 -08004589 Track* const track = t.get();
4590 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07004591 // Only consider last track started for volume and mixer state control.
4592 // In theory an older track could underrun and restart after the new one starts
4593 // but as we only care about the transition phase between two tracks on a
4594 // direct output, it is not a problem to ignore the underrun case.
4595 sp<Track> l = mLatestActiveTrack.promote();
4596 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08004597
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004598 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004599 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004600 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004601 doHwPause = true;
4602 mHwPaused = true;
4603 }
4604 tracksToRemove->add(track);
4605 } else if (track->isFlushPending()) {
4606 track->flushAck();
4607 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004608 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004609 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004610 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004611 track->resumeAck();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004612 if (last && mHwPaused) {
4613 doHwResume = true;
4614 mHwPaused = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004615 }
4616 }
4617
Eric Laurent81784c32012-11-19 14:55:58 -08004618 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08004619 // for all its buffers to be filled before processing it.
4620 // Allow draining the buffer in case the client
4621 // app does not call stop() and relies on underrun to stop:
4622 // hence the test on (track->mRetryCount > 1).
4623 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07004624 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08004625 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08004626 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkca5e6142015-07-14 09:42:29 -07004627 && (track->mRetryCount > 1) && audio_is_linear_pcm(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004628 minFrames = mNormalFrameCount;
4629 } else {
4630 minFrames = 1;
4631 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004632
Eric Laurentab5cdba2014-06-09 17:22:27 -07004633 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4634 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08004635 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004636 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08004637
4638 if (track->mFillingUpStatus == Track::FS_FILLED) {
4639 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004640 // make sure processVolume_l() will apply new volume even if 0
4641 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004642 if (!mHwSupportsPause) {
4643 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08004644 }
4645 }
4646
4647 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004648 processVolume_l(track, last);
4649 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004650 sp<Track> previousTrack = mPreviousTrack.promote();
4651 if (previousTrack != 0) {
4652 if (track != previousTrack.get()) {
4653 // Flush any data still being written from last track
4654 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07004655 // Invalidate previous track to force a seek when resuming.
4656 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004657 }
4658 }
4659 mPreviousTrack = track;
4660
Eric Laurentd595b7c2013-04-03 17:27:56 -07004661 // reset retry count
4662 track->mRetryCount = kMaxTrackRetriesDirect;
4663 mActiveTrack = t;
4664 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07004665 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004666 doHwResume = true;
4667 mHwPaused = false;
4668 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004669 }
Eric Laurent81784c32012-11-19 14:55:58 -08004670 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004671 // clear effect chain input buffer if the last active track started underruns
4672 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07004673 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004674 mEffectChains[0]->clearInputBuffer();
4675 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004676 if (track->isStopping_1()) {
4677 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07004678 if (last && mHwPaused) {
4679 doHwResume = true;
4680 mHwPaused = false;
4681 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004682 }
4683 if ((track->sharedBuffer() != 0) || track->isStopped() ||
4684 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004685 // We have consumed all the buffers of this track.
4686 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07004687 size_t audioHALFrames;
4688 if (audio_is_linear_pcm(mFormat)) {
4689 audioHALFrames = (latency_l() * mSampleRate) / 1000;
4690 } else {
4691 audioHALFrames = 0;
4692 }
4693
Eric Laurent81784c32012-11-19 14:55:58 -08004694 size_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07004695 if (mStandby || !last ||
4696 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004697 if (track->isStopping_2()) {
4698 track->mState = TrackBase::STOPPED;
4699 }
Eric Laurent81784c32012-11-19 14:55:58 -08004700 if (track->isStopped()) {
4701 track->reset();
4702 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004703 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08004704 }
4705 } else {
4706 // No buffers for this track. Give it a few chances to
4707 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07004708 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08004709 if (--(track->mRetryCount) <= 0) {
4710 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07004711 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004712 // indicate to client process that the track was disabled because of underrun;
4713 // it will then automatically call start() when data is available
4714 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004715 } else if (last) {
Phil Burkca5e6142015-07-14 09:42:29 -07004716 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
4717 "minFrames = %u, mFormat = %#x",
4718 track->framesReady(), minFrames, mFormat);
Eric Laurent81784c32012-11-19 14:55:58 -08004719 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07004720 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004721 doHwPause = true;
4722 mHwPaused = true;
4723 }
Eric Laurent81784c32012-11-19 14:55:58 -08004724 }
4725 }
4726 }
4727 }
4728
Eric Laurentd1f69b02014-12-15 14:33:13 -08004729 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07004730 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004731 for (size_t i = 0; i < mTracks.size(); i++) {
4732 if (mTracks[i]->isFlushPending()) {
4733 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004734 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004735 }
4736 }
4737 }
4738
4739 // make sure the pause/flush/resume sequence is executed in the right order.
4740 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4741 // before flush and then resume HW. This can happen in case of pause/flush/resume
4742 // if resume is received before pause is executed.
4743 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07004744 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004745 mOutput->stream->pause(mOutput->stream);
4746 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004747 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004748 flushHw_l();
4749 }
4750 if (mHwSupportsPause && !mStandby && doHwResume) {
4751 mOutput->stream->resume(mOutput->stream);
4752 }
Eric Laurent81784c32012-11-19 14:55:58 -08004753 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004754 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004755
4756 return mixerStatus;
4757}
4758
4759void AudioFlinger::DirectOutputThread::threadLoop_mix()
4760{
Eric Laurent81784c32012-11-19 14:55:58 -08004761 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08004762 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004763 // output audio to hardware
4764 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07004765 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004766 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08004767 status_t status = mActiveTrack->getNextBuffer(&buffer);
4768 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08004769 memset(curBuf, 0, frameCount * mFrameSize);
4770 break;
4771 }
4772 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
4773 frameCount -= buffer.frameCount;
4774 curBuf += buffer.frameCount * mFrameSize;
4775 mActiveTrack->releaseBuffer(&buffer);
4776 }
Andy Hung2098f272014-02-27 14:00:06 -08004777 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004778 mSleepTimeUs = 0;
4779 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08004780 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004781}
4782
4783void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
4784{
Eric Laurentd1f69b02014-12-15 14:33:13 -08004785 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004786 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004787 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004788 return;
4789 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004790 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004791 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004792 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004793 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004794 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004795 }
4796 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08004797 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004798 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004799 }
4800}
4801
Eric Laurentd1f69b02014-12-15 14:33:13 -08004802void AudioFlinger::DirectOutputThread::threadLoop_exit()
4803{
4804 {
4805 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08004806 for (size_t i = 0; i < mTracks.size(); i++) {
4807 if (mTracks[i]->isFlushPending()) {
4808 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004809 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004810 }
4811 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004812 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004813 flushHw_l();
4814 }
4815 }
4816 PlaybackThread::threadLoop_exit();
4817}
4818
4819// must be called with thread mutex locked
4820bool AudioFlinger::DirectOutputThread::shouldStandby_l()
4821{
4822 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07004823 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004824
4825 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4826 // after a timeout and we will enter standby then.
4827 if (mTracks.size() > 0) {
4828 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07004829 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
4830 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004831 }
4832
Eric Laurent5cff4032015-05-26 13:49:58 -07004833 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08004834}
4835
Eric Laurent81784c32012-11-19 14:55:58 -08004836// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004837int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Andy Hunge8a1ced2014-05-09 15:02:21 -07004838 audio_format_t format __unused, int sessionId __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004839{
4840 return 0;
4841}
4842
4843// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004844void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004845{
4846}
4847
Eric Laurent10351942014-05-08 18:49:52 -07004848// checkForNewParameter_l() must be called with ThreadBase::mLock held
4849bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
4850 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004851{
4852 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08004853 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004854
Eric Laurent10351942014-05-08 18:49:52 -07004855 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004856
Eric Laurent10351942014-05-08 18:49:52 -07004857 AudioParameter param = AudioParameter(keyValuePair);
4858 int value;
4859 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4860 // forward device change to effects that have requested to be
4861 // aware of attached audio device.
4862 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08004863 a2dpDeviceChanged =
4864 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07004865 mOutDevice = value;
4866 for (size_t i = 0; i < mEffectChains.size(); i++) {
4867 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07004868 }
4869 }
Eric Laurent81784c32012-11-19 14:55:58 -08004870 }
Eric Laurent10351942014-05-08 18:49:52 -07004871 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4872 // do not accept frame count changes if tracks are open as the track buffer
4873 // size depends on frame count and correct behavior would not be garantied
4874 // if frame count is changed after track creation
4875 if (!mTracks.isEmpty()) {
4876 status = INVALID_OPERATION;
4877 } else {
4878 reconfig = true;
4879 }
4880 }
4881 if (status == NO_ERROR) {
4882 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4883 keyValuePair.string());
4884 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004885 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004886 mStandby = true;
4887 mBytesWritten = 0;
4888 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4889 keyValuePair.string());
4890 }
4891 if (status == NO_ERROR && reconfig) {
4892 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07004893 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004894 }
4895 }
4896
Eric Laurent42537be2016-01-08 17:16:42 -08004897 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08004898}
4899
4900uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
4901{
4902 uint32_t time;
4903 if (audio_is_linear_pcm(mFormat)) {
4904 time = PlaybackThread::activeSleepTimeUs();
4905 } else {
4906 time = 10000;
4907 }
4908 return time;
4909}
4910
4911uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
4912{
4913 uint32_t time;
4914 if (audio_is_linear_pcm(mFormat)) {
4915 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
4916 } else {
4917 time = 10000;
4918 }
4919 return time;
4920}
4921
4922uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
4923{
4924 uint32_t time;
4925 if (audio_is_linear_pcm(mFormat)) {
4926 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
4927 } else {
4928 time = 10000;
4929 }
4930 return time;
4931}
4932
4933void AudioFlinger::DirectOutputThread::cacheParameters_l()
4934{
4935 PlaybackThread::cacheParameters_l();
4936
4937 // use shorter standby delay as on normal output to release
4938 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07004939 // no delay on outputs with HW A/V sync
4940 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004941 mStandbyDelayNs = 0;
Eric Laurent5cff4032015-05-26 13:49:58 -07004942 } else if ((mType == OFFLOAD) && !audio_is_linear_pcm(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004943 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07004944 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004945 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07004946 }
Eric Laurent81784c32012-11-19 14:55:58 -08004947}
4948
Eric Laurente659ef42014-09-29 13:06:46 -07004949void AudioFlinger::DirectOutputThread::flushHw_l()
4950{
Phil Burk062e67a2015-02-11 13:40:50 -08004951 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08004952 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07004953 mFlushPending = false;
Eric Laurente659ef42014-09-29 13:06:46 -07004954}
4955
Eric Laurent81784c32012-11-19 14:55:58 -08004956// ----------------------------------------------------------------------------
4957
Eric Laurentbfb1b832013-01-07 09:53:42 -08004958AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07004959 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004960 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07004961 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07004962 mWriteAckSequence(0),
4963 mDrainSequence(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004964{
4965}
4966
4967AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
4968{
4969}
4970
4971void AudioFlinger::AsyncCallbackThread::onFirstRef()
4972{
4973 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
4974}
4975
4976bool AudioFlinger::AsyncCallbackThread::threadLoop()
4977{
4978 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004979 uint32_t writeAckSequence;
4980 uint32_t drainSequence;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004981
4982 {
4983 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08004984 while (!((mWriteAckSequence & 1) ||
4985 (mDrainSequence & 1) ||
4986 exitPending())) {
4987 mWaitWorkCV.wait(mLock);
4988 }
4989
Eric Laurentbfb1b832013-01-07 09:53:42 -08004990 if (exitPending()) {
4991 break;
4992 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004993 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
4994 mWriteAckSequence, mDrainSequence);
4995 writeAckSequence = mWriteAckSequence;
4996 mWriteAckSequence &= ~1;
4997 drainSequence = mDrainSequence;
4998 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004999 }
5000 {
Eric Laurent4de95592013-09-26 15:28:21 -07005001 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
5002 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005003 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005004 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005005 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005006 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005007 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005008 }
5009 }
5010 }
5011 }
5012 return false;
5013}
5014
5015void AudioFlinger::AsyncCallbackThread::exit()
5016{
5017 ALOGV("AsyncCallbackThread::exit");
5018 Mutex::Autolock _l(mLock);
5019 requestExit();
5020 mWaitWorkCV.broadcast();
5021}
5022
Eric Laurent3b4529e2013-09-05 18:09:19 -07005023void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005024{
5025 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005026 // bit 0 is cleared
5027 mWriteAckSequence = sequence << 1;
5028}
5029
5030void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
5031{
5032 Mutex::Autolock _l(mLock);
5033 // ignore unexpected callbacks
5034 if (mWriteAckSequence & 2) {
5035 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005036 mWaitWorkCV.signal();
5037 }
5038}
5039
Eric Laurent3b4529e2013-09-05 18:09:19 -07005040void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005041{
5042 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005043 // bit 0 is cleared
5044 mDrainSequence = sequence << 1;
5045}
5046
5047void AudioFlinger::AsyncCallbackThread::resetDraining()
5048{
5049 Mutex::Autolock _l(mLock);
5050 // ignore unexpected callbacks
5051 if (mDrainSequence & 2) {
5052 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005053 mWaitWorkCV.signal();
5054 }
5055}
5056
5057
5058// ----------------------------------------------------------------------------
5059AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07005060 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady)
5061 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady),
Eric Laurentd7e59222013-11-15 12:02:28 -08005062 mPausedBytesRemaining(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005063{
Eric Laurentfd477972013-10-25 18:10:40 -07005064 //FIXME: mStandby should be set to true by ThreadBase constructor
5065 mStandby = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005066}
5067
Eric Laurentbfb1b832013-01-07 09:53:42 -08005068void AudioFlinger::OffloadThread::threadLoop_exit()
5069{
5070 if (mFlushPending || mHwPaused) {
5071 // If a flush is pending or track was paused, just discard buffered data
5072 flushHw_l();
5073 } else {
5074 mMixerStatus = MIXER_DRAIN_ALL;
5075 threadLoop_drain();
5076 }
Uday Gupta56604aa2014-05-13 11:19:17 -07005077 if (mUseAsyncWrite) {
5078 ALOG_ASSERT(mCallbackThread != 0);
5079 mCallbackThread->exit();
5080 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005081 PlaybackThread::threadLoop_exit();
5082}
5083
5084AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
5085 Vector< sp<Track> > *tracksToRemove
5086)
5087{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005088 size_t count = mActiveTracks.size();
5089
5090 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07005091 bool doHwPause = false;
5092 bool doHwResume = false;
5093
Eric Laurentede6c3b2013-09-19 14:37:46 -07005094 ALOGV("OffloadThread::prepareTracks_l active tracks %d", count);
5095
Eric Laurentbfb1b832013-01-07 09:53:42 -08005096 // find out which tracks need to be processed
5097 for (size_t i = 0; i < count; i++) {
5098 sp<Track> t = mActiveTracks[i].promote();
5099 // The track died recently
5100 if (t == 0) {
5101 continue;
5102 }
5103 Track* const track = t.get();
5104 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07005105 // Only consider last track started for volume and mixer state control.
5106 // In theory an older track could underrun and restart after the new one starts
5107 // but as we only care about the transition phase between two tracks on a
5108 // direct output, it is not a problem to ignore the underrun case.
5109 sp<Track> l = mLatestActiveTrack.promote();
5110 bool last = l.get() == track;
5111
Haynes Mathew George7844f672014-01-15 12:32:55 -08005112 if (track->isInvalid()) {
5113 ALOGW("An invalidated track shouldn't be in active list");
5114 tracksToRemove->add(track);
5115 continue;
5116 }
5117
5118 if (track->mState == TrackBase::IDLE) {
5119 ALOGW("An idle track shouldn't be in active list");
5120 continue;
5121 }
5122
Eric Laurentbfb1b832013-01-07 09:53:42 -08005123 if (track->isPausing()) {
5124 track->setPaused();
5125 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07005126 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07005127 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005128 mHwPaused = true;
5129 }
5130 // If we were part way through writing the mixbuffer to
5131 // the HAL we must save this until we resume
5132 // BUG - this will be wrong if a different track is made active,
5133 // in that case we want to discard the pending data in the
5134 // mixbuffer and tell the client to present it again when the
5135 // track is resumed
5136 mPausedWriteLength = mCurrentWriteLength;
5137 mPausedBytesRemaining = mBytesRemaining;
5138 mBytesRemaining = 0; // stop writing
5139 }
5140 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08005141 } else if (track->isFlushPending()) {
5142 track->flushAck();
5143 if (last) {
5144 mFlushPending = true;
5145 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005146 } else if (track->isResumePending()){
5147 track->resumeAck();
5148 if (last) {
5149 if (mPausedBytesRemaining) {
5150 // Need to continue write that was interrupted
5151 mCurrentWriteLength = mPausedWriteLength;
5152 mBytesRemaining = mPausedBytesRemaining;
5153 mPausedBytesRemaining = 0;
5154 }
5155 if (mHwPaused) {
5156 doHwResume = true;
5157 mHwPaused = false;
5158 // threadLoop_mix() will handle the case that we need to
5159 // resume an interrupted write
5160 }
5161 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005162 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005163
5164 // Do not handle new data in this iteration even if track->framesReady()
5165 mixerStatus = MIXER_TRACKS_ENABLED;
5166 }
5167 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07005168 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005169 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005170 if (track->mFillingUpStatus == Track::FS_FILLED) {
5171 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07005172 // make sure processVolume_l() will apply new volume even if 0
5173 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005174 }
5175
5176 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08005177 sp<Track> previousTrack = mPreviousTrack.promote();
5178 if (previousTrack != 0) {
5179 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08005180 // Flush any data still being written from last track
5181 mBytesRemaining = 0;
5182 if (mPausedBytesRemaining) {
5183 // Last track was paused so we also need to flush saved
5184 // mixbuffer state and invalidate track so that it will
5185 // re-submit that unwritten data when it is next resumed
5186 mPausedBytesRemaining = 0;
5187 // Invalidate is a bit drastic - would be more efficient
5188 // to have a flag to tell client that some of the
5189 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08005190 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005191 }
5192 // flush data already sent to the DSP if changing audio session as audio
5193 // comes from a different source. Also invalidate previous track to force a
5194 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08005195 if (previousTrack->sessionId() != track->sessionId()) {
5196 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005197 }
5198 }
5199 }
5200 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005201 // reset retry count
5202 track->mRetryCount = kMaxTrackRetriesOffload;
5203 mActiveTrack = t;
5204 mixerStatus = MIXER_TRACKS_READY;
5205 }
5206 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005207 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005208 if (track->isStopping_1()) {
5209 // Hardware buffer can hold a large amount of audio so we must
5210 // wait for all current track's data to drain before we say
5211 // that the track is stopped.
5212 if (mBytesRemaining == 0) {
5213 // Only start draining when all data in mixbuffer
5214 // has been written
5215 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
5216 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005217 // do not drain if no data was ever sent to HAL (mStandby == true)
5218 if (last && !mStandby) {
Eric Laurent1b9f9b12013-11-12 19:10:17 -08005219 // do not modify drain sequence if we are already draining. This happens
5220 // when resuming from pause after drain.
5221 if ((mDrainSequence & 1) == 0) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005222 mSleepTimeUs = 0;
5223 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent1b9f9b12013-11-12 19:10:17 -08005224 mixerStatus = MIXER_DRAIN_TRACK;
5225 mDrainSequence += 2;
5226 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005227 if (mHwPaused) {
5228 // It is possible to move from PAUSED to STOPPING_1 without
5229 // a resume so we must ensure hardware is running
Eric Laurent1b9f9b12013-11-12 19:10:17 -08005230 doHwResume = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005231 mHwPaused = false;
5232 }
5233 }
5234 }
5235 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005236 // Drain has completed or we are in standby, signal presentation complete
5237 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005238 track->mState = TrackBase::STOPPED;
5239 size_t audioHALFrames =
5240 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
5241 size_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08005242 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005243 track->presentationComplete(framesWritten, audioHALFrames);
5244 track->reset();
5245 tracksToRemove->add(track);
5246 }
5247 } else {
5248 // No buffers for this track. Give it a few chances to
5249 // fill a buffer, then remove it from active list.
5250 if (--(track->mRetryCount) <= 0) {
5251 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
5252 track->name());
5253 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08005254 // indicate to client process that the track was disabled because of underrun;
5255 // it will then automatically call start() when data is available
5256 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005257 } else if (last){
5258 mixerStatus = MIXER_TRACKS_ENABLED;
5259 }
5260 }
5261 }
5262 // compute volume for this track
5263 processVolume_l(track, last);
5264 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005265
Eric Laurentea0fade2013-10-04 16:23:48 -07005266 // make sure the pause/flush/resume sequence is executed in the right order.
5267 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5268 // before flush and then resume HW. This can happen in case of pause/flush/resume
5269 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07005270 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurent972a1732013-09-04 09:42:59 -07005271 mOutput->stream->pause(mOutput->stream);
5272 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005273 if (mFlushPending) {
5274 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005275 }
Eric Laurentfd477972013-10-25 18:10:40 -07005276 if (!mStandby && doHwResume) {
Eric Laurent972a1732013-09-04 09:42:59 -07005277 mOutput->stream->resume(mOutput->stream);
5278 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005279
Eric Laurentbfb1b832013-01-07 09:53:42 -08005280 // remove all the tracks that need to be...
5281 removeTracks_l(*tracksToRemove);
5282
5283 return mixerStatus;
5284}
5285
Eric Laurentbfb1b832013-01-07 09:53:42 -08005286// must be called with thread mutex locked
5287bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
5288{
Eric Laurent3b4529e2013-09-05 18:09:19 -07005289 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
5290 mWriteAckSequence, mDrainSequence);
5291 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005292 return true;
5293 }
5294 return false;
5295}
5296
Eric Laurentbfb1b832013-01-07 09:53:42 -08005297bool AudioFlinger::OffloadThread::waitingAsyncCallback()
5298{
5299 Mutex::Autolock _l(mLock);
5300 return waitingAsyncCallback_l();
5301}
5302
5303void AudioFlinger::OffloadThread::flushHw_l()
5304{
Eric Laurente659ef42014-09-29 13:06:46 -07005305 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005306 // Flush anything still waiting in the mixbuffer
5307 mCurrentWriteLength = 0;
5308 mBytesRemaining = 0;
5309 mPausedWriteLength = 0;
5310 mPausedBytesRemaining = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08005311
Eric Laurentbfb1b832013-01-07 09:53:42 -08005312 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005313 // discard any pending drain or write ack by incrementing sequence
5314 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5315 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005316 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005317 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5318 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005319 }
5320}
5321
5322// ----------------------------------------------------------------------------
5323
Eric Laurent81784c32012-11-19 14:55:58 -08005324AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07005325 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08005326 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
Eric Laurent72e3f392015-05-20 14:43:50 -07005327 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08005328 mWaitTimeMs(UINT_MAX)
5329{
5330 addOutputTrack(mainThread);
5331}
5332
5333AudioFlinger::DuplicatingThread::~DuplicatingThread()
5334{
5335 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5336 mOutputTracks[i]->destroy();
5337 }
5338}
5339
5340void AudioFlinger::DuplicatingThread::threadLoop_mix()
5341{
5342 // mix buffers...
5343 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08005344 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08005345 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08005346 if (mMixerBufferValid) {
5347 memset(mMixerBuffer, 0, mMixerBufferSize);
5348 } else {
5349 memset(mSinkBuffer, 0, mSinkBufferSize);
5350 }
Eric Laurent81784c32012-11-19 14:55:58 -08005351 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005352 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005353 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005354 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005355 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005356}
5357
5358void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
5359{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005360 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005361 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005362 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005363 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005364 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005365 }
5366 } else if (mBytesWritten != 0) {
5367 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5368 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005369 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005370 } else {
5371 // flush remaining overflow buffers in output tracks
5372 writeFrames = 0;
5373 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005374 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005375 }
5376}
5377
Eric Laurentbfb1b832013-01-07 09:53:42 -08005378ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005379{
5380 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08005381 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005382 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07005383 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08005384 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005385}
5386
5387void AudioFlinger::DuplicatingThread::threadLoop_standby()
5388{
5389 // DuplicatingThread implements standby by stopping all tracks
5390 for (size_t i = 0; i < outputTracks.size(); i++) {
5391 outputTracks[i]->stop();
5392 }
5393}
5394
5395void AudioFlinger::DuplicatingThread::saveOutputTracks()
5396{
5397 outputTracks = mOutputTracks;
5398}
5399
5400void AudioFlinger::DuplicatingThread::clearOutputTracks()
5401{
5402 outputTracks.clear();
5403}
5404
5405void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
5406{
5407 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08005408 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
5409 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
5410 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
5411 const size_t frameCount =
5412 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
5413 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
5414 // from different OutputTracks and their associated MixerThreads (e.g. one may
5415 // nearly empty and the other may be dropping data).
5416
5417 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08005418 this,
5419 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08005420 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08005421 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005422 frameCount,
5423 IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08005424 if (outputTrack->cblk() != NULL) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005425 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
Eric Laurent81784c32012-11-19 14:55:58 -08005426 mOutputTracks.add(outputTrack);
Andy Hungc25b84a2015-01-14 19:04:10 -08005427 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005428 updateWaitTime_l();
5429 }
5430}
5431
5432void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
5433{
5434 Mutex::Autolock _l(mLock);
5435 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5436 if (mOutputTracks[i]->thread() == thread) {
5437 mOutputTracks[i]->destroy();
5438 mOutputTracks.removeAt(i);
5439 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07005440 if (thread->getOutput() == mOutput) {
5441 mOutput = NULL;
5442 }
Eric Laurent81784c32012-11-19 14:55:58 -08005443 return;
5444 }
5445 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07005446 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005447}
5448
5449// caller must hold mLock
5450void AudioFlinger::DuplicatingThread::updateWaitTime_l()
5451{
5452 mWaitTimeMs = UINT_MAX;
5453 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5454 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
5455 if (strong != 0) {
5456 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
5457 if (waitTimeMs < mWaitTimeMs) {
5458 mWaitTimeMs = waitTimeMs;
5459 }
5460 }
5461 }
5462}
5463
5464
5465bool AudioFlinger::DuplicatingThread::outputsReady(
5466 const SortedVector< sp<OutputTrack> > &outputTracks)
5467{
5468 for (size_t i = 0; i < outputTracks.size(); i++) {
5469 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
5470 if (thread == 0) {
5471 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
5472 outputTracks[i].get());
5473 return false;
5474 }
5475 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5476 // see note at standby() declaration
5477 if (playbackThread->standby() && !playbackThread->isSuspended()) {
5478 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
5479 thread.get());
5480 return false;
5481 }
5482 }
5483 return true;
5484}
5485
5486uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
5487{
5488 return (mWaitTimeMs * 1000) / 2;
5489}
5490
5491void AudioFlinger::DuplicatingThread::cacheParameters_l()
5492{
5493 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
5494 updateWaitTime_l();
5495
5496 MixerThread::cacheParameters_l();
5497}
5498
5499// ----------------------------------------------------------------------------
5500// Record
5501// ----------------------------------------------------------------------------
5502
5503AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5504 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08005505 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08005506 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07005507 audio_devices_t inDevice,
5508 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08005509#ifdef TEE_SINK
5510 , const sp<NBAIO_Sink>& teeSink
5511#endif
5512 ) :
Eric Laurent72e3f392015-05-20 14:43:50 -07005513 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005514 mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005515 // mRsmpInFrames and mRsmpInFramesP2 are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005516 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08005517#ifdef TEE_SINK
5518 , mTeeSink(teeSink)
5519#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07005520 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
5521 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005522 // mFastCapture below
5523 , mFastCaptureFutex(0)
5524 // mInputSource
5525 // mPipeSink
5526 // mPipeSource
5527 , mPipeFramesP2(0)
5528 // mPipeMemory
5529 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005530 , mFastTrackAvail(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005531{
Glenn Kastend7dca052015-03-05 16:05:54 -08005532 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
5533 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08005534
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005535 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005536
5537 // create an NBAIO source for the HAL input stream, and negotiate
5538 mInputSource = new AudioStreamInSource(input->stream);
5539 size_t numCounterOffers = 0;
5540 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
5541 ssize_t index = mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
5542 ALOG_ASSERT(index == 0);
5543
5544 // initialize fast capture depending on configuration
5545 bool initFastCapture;
5546 switch (kUseFastCapture) {
5547 case FastCapture_Never:
5548 initFastCapture = false;
5549 break;
5550 case FastCapture_Always:
5551 initFastCapture = true;
5552 break;
5553 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07005554 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005555 break;
5556 // case FastCapture_Dynamic:
5557 }
5558
5559 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07005560 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005561 NBAIO_Format format = mInputSource->format();
Glenn Kasten49d00ad2014-07-21 11:22:03 -07005562 size_t pipeFramesP2 = roundup(mSampleRate / 25); // double-buffering of 20 ms each
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005563 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
5564 void *pipeBuffer;
5565 const sp<MemoryDealer> roHeap(readOnlyHeap());
5566 sp<IMemory> pipeMemory;
5567 if ((roHeap == 0) ||
5568 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
5569 (pipeBuffer = pipeMemory->pointer()) == NULL) {
5570 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
5571 goto failed;
5572 }
5573 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
5574 memset(pipeBuffer, 0, pipeSize);
5575 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
5576 const NBAIO_Format offers[1] = {format};
5577 size_t numCounterOffers = 0;
5578 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
5579 ALOG_ASSERT(index == 0);
5580 mPipeSink = pipe;
5581 PipeReader *pipeReader = new PipeReader(*pipe);
5582 numCounterOffers = 0;
5583 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
5584 ALOG_ASSERT(index == 0);
5585 mPipeSource = pipeReader;
5586 mPipeFramesP2 = pipeFramesP2;
5587 mPipeMemory = pipeMemory;
5588
5589 // create fast capture
5590 mFastCapture = new FastCapture();
5591 FastCaptureStateQueue *sq = mFastCapture->sq();
5592#ifdef STATE_QUEUE_DUMP
5593 // FIXME
5594#endif
5595 FastCaptureState *state = sq->begin();
5596 state->mCblk = NULL;
5597 state->mInputSource = mInputSource.get();
5598 state->mInputSourceGen++;
5599 state->mPipeSink = pipe;
5600 state->mPipeSinkGen++;
5601 state->mFrameCount = mFrameCount;
5602 state->mCommand = FastCaptureState::COLD_IDLE;
5603 // already done in constructor initialization list
5604 //mFastCaptureFutex = 0;
5605 state->mColdFutexAddr = &mFastCaptureFutex;
5606 state->mColdGen++;
5607 state->mDumpState = &mFastCaptureDumpState;
5608#ifdef TEE_SINK
5609 // FIXME
5610#endif
5611 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
5612 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
5613 sq->end();
5614 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5615
5616 // start the fast capture
5617 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
5618 pid_t tid = mFastCapture->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07005619 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005620#ifdef AUDIO_WATCHDOG
5621 // FIXME
5622#endif
5623
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005624 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005625 }
5626failed: ;
5627
5628 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08005629}
5630
Eric Laurent81784c32012-11-19 14:55:58 -08005631AudioFlinger::RecordThread::~RecordThread()
5632{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005633 if (mFastCapture != 0) {
5634 FastCaptureStateQueue *sq = mFastCapture->sq();
5635 FastCaptureState *state = sq->begin();
5636 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5637 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5638 if (old == -1) {
5639 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5640 }
5641 }
5642 state->mCommand = FastCaptureState::EXIT;
5643 sq->end();
5644 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5645 mFastCapture->join();
5646 mFastCapture.clear();
5647 }
5648 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07005649 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07005650 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08005651}
5652
5653void AudioFlinger::RecordThread::onFirstRef()
5654{
Glenn Kastend7dca052015-03-05 16:05:54 -08005655 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08005656}
5657
Eric Laurent81784c32012-11-19 14:55:58 -08005658bool AudioFlinger::RecordThread::threadLoop()
5659{
Eric Laurent81784c32012-11-19 14:55:58 -08005660 nsecs_t lastWarning = 0;
5661
5662 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08005663
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005664reacquire_wakelock:
5665 sp<RecordTrack> activeTrack;
Glenn Kasten2b806402013-11-20 16:37:38 -08005666 int activeTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005667 {
5668 Mutex::Autolock _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005669 size_t size = mActiveTracks.size();
5670 activeTracksGen = mActiveTracksGen;
5671 if (size > 0) {
5672 // FIXME an arbitrary choice
5673 activeTrack = mActiveTracks[0];
5674 acquireWakeLock_l(activeTrack->uid());
5675 if (size > 1) {
5676 SortedVector<int> tmp;
5677 for (size_t i = 0; i < size; i++) {
5678 tmp.add(mActiveTracks[i]->uid());
5679 }
5680 updateWakeLockUids_l(tmp);
5681 }
5682 } else {
5683 acquireWakeLock_l(-1);
5684 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005685 }
5686
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005687 // used to request a deferred sleep, to be executed later while mutex is unlocked
5688 uint32_t sleepUs = 0;
5689
5690 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005691 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005692 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07005693
Glenn Kasten5edadd42013-08-14 16:30:49 -07005694 // sleep with mutex unlocked
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005695 if (sleepUs > 0) {
Glenn Kastene7754022014-10-31 12:11:26 -07005696 ATRACE_BEGIN("sleep");
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005697 usleep(sleepUs);
Glenn Kastene7754022014-10-31 12:11:26 -07005698 ATRACE_END();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005699 sleepUs = 0;
Glenn Kasten5edadd42013-08-14 16:30:49 -07005700 }
5701
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005702 // activeTracks accumulates a copy of a subset of mActiveTracks
5703 Vector< sp<RecordTrack> > activeTracks;
5704
Glenn Kasten735f45f2014-08-18 15:51:59 -07005705 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005706 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07005707
Glenn Kasten735f45f2014-08-18 15:51:59 -07005708 // reference to a fast track which is about to be removed
5709 sp<RecordTrack> fastTrackToRemove;
5710
Eric Laurent81784c32012-11-19 14:55:58 -08005711 { // scope for mLock
5712 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08005713
Eric Laurent021cf962014-05-13 10:18:14 -07005714 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005715
Eric Laurent000a4192014-01-29 15:17:32 -08005716 // check exitPending here because checkForNewParameters_l() and
5717 // checkForNewParameters_l() can temporarily release mLock
5718 if (exitPending()) {
5719 break;
5720 }
5721
Glenn Kasten2b806402013-11-20 16:37:38 -08005722 // if no active track(s), then standby and release wakelock
5723 size_t size = mActiveTracks.size();
5724 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07005725 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005726 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08005727 releaseWakeLock_l();
5728 ALOGV("RecordThread: loop stopping");
5729 // go to sleep
5730 mWaitWorkCV.wait(mLock);
5731 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005732 goto reacquire_wakelock;
5733 }
5734
Glenn Kasten2b806402013-11-20 16:37:38 -08005735 if (mActiveTracksGen != activeTracksGen) {
5736 activeTracksGen = mActiveTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005737 SortedVector<int> tmp;
Glenn Kasten2b806402013-11-20 16:37:38 -08005738 for (size_t i = 0; i < size; i++) {
5739 tmp.add(mActiveTracks[i]->uid());
5740 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005741 updateWakeLockUids_l(tmp);
Eric Laurent81784c32012-11-19 14:55:58 -08005742 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005743
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005744 bool doBroadcast = false;
5745 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07005746
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005747 activeTrack = mActiveTracks[i];
5748 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07005749 if (activeTrack->isFastTrack()) {
5750 ALOG_ASSERT(fastTrackToRemove == 0);
5751 fastTrackToRemove = activeTrack;
5752 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005753 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08005754 mActiveTracks.remove(activeTrack);
5755 mActiveTracksGen++;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005756 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07005757 continue;
5758 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005759
5760 TrackBase::track_state activeTrackState = activeTrack->mState;
5761 switch (activeTrackState) {
5762
5763 case TrackBase::PAUSING:
5764 mActiveTracks.remove(activeTrack);
5765 mActiveTracksGen++;
5766 doBroadcast = true;
5767 size--;
5768 continue;
5769
5770 case TrackBase::STARTING_1:
5771 sleepUs = 10000;
5772 i++;
5773 continue;
5774
5775 case TrackBase::STARTING_2:
5776 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005777 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07005778 activeTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005779 break;
5780
5781 case TrackBase::ACTIVE:
5782 break;
5783
5784 case TrackBase::IDLE:
5785 i++;
5786 continue;
5787
5788 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08005789 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07005790 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005791
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005792 activeTracks.add(activeTrack);
5793 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07005794
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005795 if (activeTrack->isFastTrack()) {
5796 ALOG_ASSERT(!mFastTrackAvail);
5797 ALOG_ASSERT(fastTrack == 0);
5798 fastTrack = activeTrack;
5799 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005800 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005801 if (doBroadcast) {
5802 mStartStopCond.broadcast();
5803 }
5804
5805 // sleep if there are no active tracks to process
5806 if (activeTracks.size() == 0) {
5807 if (sleepUs == 0) {
5808 sleepUs = kRecordThreadSleepUs;
5809 }
5810 continue;
5811 }
5812 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07005813
Eric Laurent81784c32012-11-19 14:55:58 -08005814 lockEffectChains_l(effectChains);
5815 }
5816
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005817 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07005818
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005819 size_t size = effectChains.size();
5820 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005821 // thread mutex is not locked, but effect chain is locked
5822 effectChains[i]->process_l();
5823 }
5824
Glenn Kasten735f45f2014-08-18 15:51:59 -07005825 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005826 if (mFastCapture != 0) {
5827 FastCaptureStateQueue *sq = mFastCapture->sq();
5828 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07005829 bool didModify = false;
5830 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005831 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
5832 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
5833 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5834 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5835 if (old == -1) {
5836 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5837 }
5838 }
5839 state->mCommand = FastCaptureState::READ_WRITE;
5840#if 0 // FIXME
5841 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08005842 FastThreadDumpState::kSamplingNforLowRamDevice :
5843 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005844#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07005845 didModify = true;
5846 }
5847 audio_track_cblk_t *cblkOld = state->mCblk;
5848 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
5849 if (cblkNew != cblkOld) {
5850 state->mCblk = cblkNew;
5851 // block until acked if removing a fast track
5852 if (cblkOld != NULL) {
5853 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
5854 }
5855 didModify = true;
5856 }
5857 sq->end(didModify);
5858 if (didModify) {
5859 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005860#if 0
5861 if (kUseFastCapture == FastCapture_Dynamic) {
5862 mNormalSource = mPipeSource;
5863 }
5864#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005865 }
5866 }
5867
Glenn Kasten735f45f2014-08-18 15:51:59 -07005868 // now run the fast track destructor with thread mutex unlocked
5869 fastTrackToRemove.clear();
5870
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005871 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
5872 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
5873 // slow, then this RecordThread will overrun by not calling HAL read often enough.
5874 // If destination is non-contiguous, first read past the nominal end of buffer, then
5875 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005876
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005877 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005878 ssize_t framesRead;
5879
5880 // If an NBAIO source is present, use it to read the normal capture's data
5881 if (mPipeSource != 0) {
5882 size_t framesToRead = mBufferSize / mFrameSize;
Andy Hung57446612015-04-19 23:56:46 -07005883 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
Glenn Kastend79072e2016-01-06 08:41:20 -08005884 framesToRead);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005885 if (framesRead == 0) {
5886 // since pipe is non-blocking, simulate blocking input
5887 sleepUs = (framesToRead * 1000000LL) / mSampleRate;
5888 }
5889 // otherwise use the HAL / AudioStreamIn directly
5890 } else {
5891 ssize_t bytesRead = mInput->stream->read(mInput->stream,
Andy Hung57446612015-04-19 23:56:46 -07005892 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005893 if (bytesRead < 0) {
5894 framesRead = bytesRead;
5895 } else {
5896 framesRead = bytesRead / mFrameSize;
5897 }
5898 }
5899
5900 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
5901 ALOGE("read failed: framesRead=%d", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005902 // Force input into standby so that it tries to recover at next read attempt
5903 inputStandBy();
5904 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005905 }
5906 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005907 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005908 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005909 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005910
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005911 if (mTeeSink != 0) {
Andy Hung57446612015-04-19 23:56:46 -07005912 (void) mTeeSink->write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005913 }
5914 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005915 {
5916 size_t part1 = mRsmpInFramesP2 - rear;
5917 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07005918 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005919 (framesRead - part1) * mFrameSize);
5920 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005921 }
5922 rear = mRsmpInRear += framesRead;
5923
5924 size = activeTracks.size();
5925 // loop over each active track
5926 for (size_t i = 0; i < size; i++) {
5927 activeTrack = activeTracks[i];
5928
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005929 // skip fast tracks, as those are handled directly by FastCapture
5930 if (activeTrack->isFastTrack()) {
5931 continue;
5932 }
5933
Andy Hung73c02e42015-03-29 01:13:58 -07005934 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07005935 // TODO: Update the activeTrack buffer converter in case of reconfigure.
5936
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005937 enum {
5938 OVERRUN_UNKNOWN,
5939 OVERRUN_TRUE,
5940 OVERRUN_FALSE
5941 } overrun = OVERRUN_UNKNOWN;
5942
5943 // loop over getNextBuffer to handle circular sink
5944 for (;;) {
5945
5946 activeTrack->mSink.frameCount = ~0;
5947 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
5948 size_t framesOut = activeTrack->mSink.frameCount;
5949 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
5950
Andy Hung73c02e42015-03-29 01:13:58 -07005951 // check available frames and handle overrun conditions
5952 // if the record track isn't draining fast enough.
5953 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005954 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07005955 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
5956 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005957 overrun = OVERRUN_TRUE;
5958 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005959 if (framesOut == 0 || framesIn == 0) {
5960 break;
5961 }
5962
Andy Hung6770c6f2015-04-07 13:43:36 -07005963 // Don't allow framesOut to be larger than what is possible with resampling
5964 // from framesIn.
5965 // This isn't strictly necessary but helps limit buffer resizing in
5966 // RecordBufferConverter. TODO: remove when no longer needed.
5967 framesOut = min(framesOut,
5968 destinationFramesPossible(
5969 framesIn, mSampleRate, activeTrack->mSampleRate));
Andy Hung97a893e2015-03-29 01:03:07 -07005970 // process frames from the RecordThread buffer provider to the RecordTrack buffer
5971 framesOut = activeTrack->mRecordBufferConverter->convert(
5972 activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005973
5974 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
5975 overrun = OVERRUN_FALSE;
5976 }
5977
5978 if (activeTrack->mFramesToDrop == 0) {
5979 if (framesOut > 0) {
5980 activeTrack->mSink.frameCount = framesOut;
5981 activeTrack->releaseBuffer(&activeTrack->mSink);
5982 }
5983 } else {
5984 // FIXME could do a partial drop of framesOut
5985 if (activeTrack->mFramesToDrop > 0) {
5986 activeTrack->mFramesToDrop -= framesOut;
5987 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005988 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005989 }
5990 } else {
5991 activeTrack->mFramesToDrop += framesOut;
5992 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
5993 activeTrack->mSyncStartEvent->isCancelled()) {
5994 ALOGW("Synced record %s, session %d, trigger session %d",
5995 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
5996 activeTrack->sessionId(),
5997 (activeTrack->mSyncStartEvent != 0) ?
5998 activeTrack->mSyncStartEvent->triggerSession() : 0);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005999 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006000 }
6001 }
6002 }
6003
6004 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006005 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006006 }
6007 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006008
6009 switch (overrun) {
6010 case OVERRUN_TRUE:
6011 // client isn't retrieving buffers fast enough
6012 if (!activeTrack->setOverflow()) {
6013 nsecs_t now = systemTime();
6014 // FIXME should lastWarning per track?
6015 if ((now - lastWarning) > kWarningThrottleNs) {
6016 ALOGW("RecordThread: buffer overflow");
6017 lastWarning = now;
6018 }
6019 }
6020 break;
6021 case OVERRUN_FALSE:
6022 activeTrack->clearOverflow();
6023 break;
6024 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006025 break;
6026 }
6027
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006028 }
6029
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006030unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08006031 // enable changes in effect chain
6032 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006033 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08006034 }
6035
Glenn Kasten93e471f2013-08-19 08:40:07 -07006036 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08006037
6038 {
6039 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07006040 for (size_t i = 0; i < mTracks.size(); i++) {
6041 sp<RecordTrack> track = mTracks[i];
6042 track->invalidate();
6043 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006044 mActiveTracks.clear();
6045 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08006046 mStartStopCond.broadcast();
6047 }
6048
6049 releaseWakeLock();
6050
6051 ALOGV("RecordThread %p exiting", this);
6052 return false;
6053}
6054
Glenn Kasten93e471f2013-08-19 08:40:07 -07006055void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08006056{
6057 if (!mStandby) {
6058 inputStandBy();
6059 mStandby = true;
6060 }
6061}
6062
6063void AudioFlinger::RecordThread::inputStandBy()
6064{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006065 // Idle the fast capture if it's currently running
6066 if (mFastCapture != 0) {
6067 FastCaptureStateQueue *sq = mFastCapture->sq();
6068 FastCaptureState *state = sq->begin();
6069 if (!(state->mCommand & FastCaptureState::IDLE)) {
6070 state->mCommand = FastCaptureState::COLD_IDLE;
6071 state->mColdFutexAddr = &mFastCaptureFutex;
6072 state->mColdGen++;
6073 mFastCaptureFutex = 0;
6074 sq->end();
6075 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
6076 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
6077#if 0
6078 if (kUseFastCapture == FastCapture_Dynamic) {
6079 // FIXME
6080 }
6081#endif
6082#ifdef AUDIO_WATCHDOG
6083 // FIXME
6084#endif
6085 } else {
6086 sq->end(false /*didModify*/);
6087 }
6088 }
Eric Laurent81784c32012-11-19 14:55:58 -08006089 mInput->stream->common.standby(&mInput->stream->common);
6090}
6091
Glenn Kasten05997e22014-03-13 15:08:33 -07006092// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07006093sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08006094 const sp<AudioFlinger::Client>& client,
6095 uint32_t sampleRate,
6096 audio_format_t format,
6097 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08006098 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08006099 int sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07006100 size_t *notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08006101 int uid,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07006102 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08006103 pid_t tid,
6104 status_t *status)
6105{
Glenn Kasten74935e42013-12-19 08:56:45 -08006106 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08006107 sp<RecordTrack> track;
6108 status_t lStatus;
6109
Glenn Kasten90e58b12013-07-31 16:16:02 -07006110 // client expresses a preference for FAST, but we get the final say
6111 if (*flags & IAudioFlinger::TRACK_FAST) {
6112 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07006113 // we formerly checked for a callback handler (non-0 tid),
6114 // but that is no longer required for TRANSFER_OBTAIN mode
6115 //
Glenn Kasten74105912014-07-03 12:28:53 -07006116 // frame count is not specified, or is exactly the pipe depth
6117 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006118 // PCM data
6119 audio_is_linear_pcm(format) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006120 // native format
6121 (format == mFormat) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006122 // native channel mask
6123 (channelMask == mChannelMask) &&
6124 // native hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07006125 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006126 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006127 hasFastCapture() &&
6128 // there are sufficient fast track slots available
6129 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07006130 ) {
Glenn Kasten74105912014-07-03 12:28:53 -07006131 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%u mFrameCount=%u",
Glenn Kasten90e58b12013-07-31 16:16:02 -07006132 frameCount, mFrameCount);
6133 } else {
Glenn Kasten74105912014-07-03 12:28:53 -07006134 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%u mFrameCount=%u mPipeFramesP2=%u "
6135 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006136 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Glenn Kasten74105912014-07-03 12:28:53 -07006137 frameCount, mFrameCount, mPipeFramesP2,
6138 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
6139 hasFastCapture(), tid, mFastTrackAvail);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006140 *flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kasten74105912014-07-03 12:28:53 -07006141 }
6142 }
6143
6144 // compute track buffer size in frames, and suggest the notification frame count
6145 if (*flags & IAudioFlinger::TRACK_FAST) {
6146 // fast track: frame count is exactly the pipe depth
6147 frameCount = mPipeFramesP2;
6148 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
6149 *notificationFrames = mFrameCount;
6150 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006151 // not fast track: max notification period is resampled equivalent of one HAL buffer time
6152 // or 20 ms if there is a fast capture
6153 // TODO This could be a roundupRatio inline, and const
6154 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
6155 * sampleRate + mSampleRate - 1) / mSampleRate;
6156 // minimum number of notification periods is at least kMinNotifications,
6157 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
6158 static const size_t kMinNotifications = 3;
6159 static const uint32_t kMinMs = 30;
6160 // TODO This could be a roundupRatio inline
6161 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
6162 // TODO This could be a roundupRatio inline
6163 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
6164 maxNotificationFrames;
6165 const size_t minFrameCount = maxNotificationFrames *
6166 max(kMinNotifications, minNotificationsByMs);
6167 frameCount = max(frameCount, minFrameCount);
6168 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
6169 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07006170 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07006171 }
Glenn Kasten74935e42013-12-19 08:56:45 -08006172 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07006173
Glenn Kasten15e57982013-09-24 11:52:37 -07006174 lStatus = initCheck();
6175 if (lStatus != NO_ERROR) {
6176 ALOGE("createRecordTrack_l() audio driver not initialized");
6177 goto Exit;
6178 }
Eric Laurent81784c32012-11-19 14:55:58 -08006179
6180 { // scope for mLock
6181 Mutex::Autolock _l(mLock);
6182
6183 track = new RecordTrack(this, client, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07006184 format, channelMask, frameCount, NULL, sessionId, uid,
6185 *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08006186
Glenn Kasten03003332013-08-06 15:40:54 -07006187 lStatus = track->initCheck();
6188 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07006189 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08006190 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08006191 goto Exit;
6192 }
6193 mTracks.add(track);
6194
6195 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6196 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6197 mAudioFlinger->btNrecIsOff();
6198 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6199 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006200
6201 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
6202 pid_t callingPid = IPCThreadState::self()->getCallingPid();
6203 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
6204 // so ask activity manager to do this on our behalf
6205 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
6206 }
Eric Laurent81784c32012-11-19 14:55:58 -08006207 }
Glenn Kasten05997e22014-03-13 15:08:33 -07006208
Eric Laurent81784c32012-11-19 14:55:58 -08006209 lStatus = NO_ERROR;
6210
6211Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07006212 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08006213 return track;
6214}
6215
6216status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
6217 AudioSystem::sync_event_t event,
6218 int triggerSession)
6219{
6220 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
6221 sp<ThreadBase> strongMe = this;
6222 status_t status = NO_ERROR;
6223
6224 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006225 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006226 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006227 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08006228 triggerSession,
6229 recordTrack->sessionId(),
6230 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006231 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08006232 // Sync event can be cancelled by the trigger session if the track is not in a
6233 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006234 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006235 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006236 } else {
6237 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006238 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006239 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08006240 }
6241 }
6242
6243 {
Glenn Kasten47c20702013-08-13 15:37:35 -07006244 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08006245 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006246 if (mActiveTracks.indexOf(recordTrack) >= 0) {
6247 if (recordTrack->mState == TrackBase::PAUSING) {
6248 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006249 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006250 } else {
6251 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08006252 }
6253 return status;
6254 }
6255
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006256 // TODO consider other ways of handling this, such as changing the state to :STARTING and
6257 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
6258 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006259 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08006260 mActiveTracks.add(recordTrack);
6261 mActiveTracksGen++;
Eric Laurent83b88082014-06-20 18:31:16 -07006262 status_t status = NO_ERROR;
6263 if (recordTrack->isExternalTrack()) {
6264 mLock.unlock();
Eric Laurent4dc68062014-07-28 17:26:49 -07006265 status = AudioSystem::startInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006266 mLock.lock();
6267 // FIXME should verify that recordTrack is still in mActiveTracks
6268 if (status != NO_ERROR) {
6269 mActiveTracks.remove(recordTrack);
6270 mActiveTracksGen++;
6271 recordTrack->clearSyncStartEvent();
6272 ALOGV("RecordThread::start error %d", status);
6273 return status;
6274 }
Eric Laurent81784c32012-11-19 14:55:58 -08006275 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006276 // Catch up with current buffer indices if thread is already running.
6277 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
6278 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
6279 // see previously buffered data before it called start(), but with greater risk of overrun.
6280
Andy Hung73c02e42015-03-29 01:13:58 -07006281 recordTrack->mResamplerBufferProvider->reset();
Andy Hung97a893e2015-03-29 01:03:07 -07006282 // clear any converter state as new data will be discontinuous
6283 recordTrack->mRecordBufferConverter->reset();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006284 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08006285 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08006286 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08006287 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006288 ALOGV("Record failed to start");
6289 status = BAD_VALUE;
6290 goto startError;
6291 }
Eric Laurent81784c32012-11-19 14:55:58 -08006292 return status;
6293 }
Glenn Kasten7c027242012-12-26 14:43:16 -08006294
Eric Laurent81784c32012-11-19 14:55:58 -08006295startError:
Eric Laurent83b88082014-06-20 18:31:16 -07006296 if (recordTrack->isExternalTrack()) {
Eric Laurent4dc68062014-07-28 17:26:49 -07006297 AudioSystem::stopInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006298 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006299 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006300 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08006301 return status;
6302}
6303
Eric Laurent81784c32012-11-19 14:55:58 -08006304void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6305{
6306 sp<SyncEvent> strongEvent = event.promote();
6307
6308 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08006309 sp<RefBase> ptr = strongEvent->cookie().promote();
6310 if (ptr != 0) {
6311 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
6312 recordTrack->handleSyncStartEvent(strongEvent);
6313 }
Eric Laurent81784c32012-11-19 14:55:58 -08006314 }
6315}
6316
Glenn Kastena8356f62013-07-25 14:37:52 -07006317bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08006318 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07006319 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006320 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08006321 return false;
6322 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006323 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08006324 recordTrack->mState = TrackBase::PAUSING;
6325 // do not wait for mStartStopCond if exiting
6326 if (exitPending()) {
6327 return true;
6328 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006329 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08006330 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006331 // if we have been restarted, recordTrack is in mActiveTracks here
6332 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006333 ALOGV("Record stopped OK");
6334 return true;
6335 }
6336 return false;
6337}
6338
Glenn Kasten0f11b512014-01-31 16:18:54 -08006339bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08006340{
6341 return false;
6342}
6343
Glenn Kasten0f11b512014-01-31 16:18:54 -08006344status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006345{
6346#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
6347 if (!isValidSyncEvent(event)) {
6348 return BAD_VALUE;
6349 }
6350
6351 int eventSession = event->triggerSession();
6352 status_t ret = NAME_NOT_FOUND;
6353
6354 Mutex::Autolock _l(mLock);
6355
6356 for (size_t i = 0; i < mTracks.size(); i++) {
6357 sp<RecordTrack> track = mTracks[i];
6358 if (eventSession == track->sessionId()) {
6359 (void) track->setSyncEvent(event);
6360 ret = NO_ERROR;
6361 }
6362 }
6363 return ret;
6364#else
6365 return BAD_VALUE;
6366#endif
6367}
6368
6369// destroyTrack_l() must be called with ThreadBase::mLock held
6370void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6371{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006372 track->terminate();
6373 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08006374 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08006375 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006376 removeTrack_l(track);
6377 }
6378}
6379
6380void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6381{
6382 mTracks.remove(track);
6383 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006384 if (track->isFastTrack()) {
6385 ALOG_ASSERT(!mFastTrackAvail);
6386 mFastTrackAvail = true;
6387 }
Eric Laurent81784c32012-11-19 14:55:58 -08006388}
6389
6390void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6391{
6392 dumpInternals(fd, args);
6393 dumpTracks(fd, args);
6394 dumpEffectChains(fd, args);
6395}
6396
6397void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6398{
Elliott Hughes87cebad2014-05-22 10:14:43 -07006399 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08006400
Glenn Kasten44182c22015-03-05 17:12:23 -08006401 dumpBase(fd, args);
6402
6403 if (mActiveTracks.size() == 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006404 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006405 }
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006406 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006407 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08006408
Glenn Kasten2f90c512015-12-02 11:40:09 -08006409 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
6410 // while we are dumping it. It may be inconsistent, but it won't mutate!
6411 // This is a large object so we place it on the heap.
6412 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
6413 const FastCaptureDumpState *copy = new FastCaptureDumpState(mFastCaptureDumpState);
6414 copy->dump(fd);
6415 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08006416}
6417
Glenn Kasten0f11b512014-01-31 16:18:54 -08006418void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006419{
6420 const size_t SIZE = 256;
6421 char buffer[SIZE];
6422 String8 result;
6423
Marco Nelissenb2208842014-02-07 14:00:50 -08006424 size_t numtracks = mTracks.size();
6425 size_t numactive = mActiveTracks.size();
6426 size_t numactiveseen = 0;
Elliott Hughes87cebad2014-05-22 10:14:43 -07006427 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08006428 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006429 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08006430 RecordTrack::appendDumpHeader(result);
6431 for (size_t i = 0; i < numtracks ; ++i) {
6432 sp<RecordTrack> track = mTracks[i];
6433 if (track != 0) {
6434 bool active = mActiveTracks.indexOf(track) >= 0;
6435 if (active) {
6436 numactiveseen++;
6437 }
6438 track->dump(buffer, SIZE, active);
6439 result.append(buffer);
6440 }
Eric Laurent81784c32012-11-19 14:55:58 -08006441 }
Marco Nelissenb2208842014-02-07 14:00:50 -08006442 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006443 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006444 }
6445
Marco Nelissenb2208842014-02-07 14:00:50 -08006446 if (numactiveseen != numactive) {
6447 snprintf(buffer, SIZE, " The following tracks are in the active list but"
6448 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006449 result.append(buffer);
6450 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08006451 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08006452 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08006453 if (mTracks.indexOf(track) < 0) {
6454 track->dump(buffer, SIZE, true);
6455 result.append(buffer);
6456 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006457 }
Eric Laurent81784c32012-11-19 14:55:58 -08006458
6459 }
6460 write(fd, result.string(), result.size());
6461}
6462
Andy Hung73c02e42015-03-29 01:13:58 -07006463
6464void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
6465{
6466 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6467 RecordThread *recordThread = (RecordThread *) threadBase.get();
6468 mRsmpInFront = recordThread->mRsmpInRear;
6469 mRsmpInUnrel = 0;
6470}
6471
6472void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
6473 size_t *framesAvailable, bool *hasOverrun)
6474{
6475 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6476 RecordThread *recordThread = (RecordThread *) threadBase.get();
6477 const int32_t rear = recordThread->mRsmpInRear;
6478 const int32_t front = mRsmpInFront;
6479 const ssize_t filled = rear - front;
6480
6481 size_t framesIn;
6482 bool overrun = false;
6483 if (filled < 0) {
6484 // should not happen, but treat like a massive overrun and re-sync
6485 framesIn = 0;
6486 mRsmpInFront = rear;
6487 overrun = true;
6488 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
6489 framesIn = (size_t) filled;
6490 } else {
6491 // client is not keeping up with server, but give it latest data
6492 framesIn = recordThread->mRsmpInFrames;
6493 mRsmpInFront = /* front = */ rear - framesIn;
6494 overrun = true;
6495 }
6496 if (framesAvailable != NULL) {
6497 *framesAvailable = framesIn;
6498 }
6499 if (hasOverrun != NULL) {
6500 *hasOverrun = overrun;
6501 }
6502}
6503
Eric Laurent81784c32012-11-19 14:55:58 -08006504// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006505status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08006506 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006507{
Andy Hung73c02e42015-03-29 01:13:58 -07006508 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006509 if (threadBase == 0) {
6510 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006511 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006512 return NOT_ENOUGH_DATA;
6513 }
6514 RecordThread *recordThread = (RecordThread *) threadBase.get();
6515 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07006516 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07006517 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006518 // FIXME should not be P2 (don't want to increase latency)
6519 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006520 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07006521 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006522 front &= recordThread->mRsmpInFramesP2 - 1;
6523 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07006524 if (part1 > (size_t) filled) {
6525 part1 = filled;
6526 }
6527 size_t ask = buffer->frameCount;
6528 ALOG_ASSERT(ask > 0);
6529 if (part1 > ask) {
6530 part1 = ask;
6531 }
6532 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07006533 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07006534 buffer->raw = NULL;
6535 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07006536 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07006537 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08006538 }
6539
Andy Hung57446612015-04-19 23:56:46 -07006540 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07006541 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07006542 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08006543 return NO_ERROR;
6544}
6545
6546// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006547void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
6548 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006549{
Glenn Kasten85948432013-08-19 12:09:05 -07006550 size_t stepCount = buffer->frameCount;
6551 if (stepCount == 0) {
6552 return;
6553 }
Andy Hung73c02e42015-03-29 01:13:58 -07006554 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
6555 mRsmpInUnrel -= stepCount;
6556 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07006557 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006558 buffer->frameCount = 0;
6559}
6560
Andy Hung97a893e2015-03-29 01:03:07 -07006561AudioFlinger::RecordThread::RecordBufferConverter::RecordBufferConverter(
6562 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6563 uint32_t srcSampleRate,
6564 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6565 uint32_t dstSampleRate) :
6566 mSrcChannelMask(AUDIO_CHANNEL_INVALID), // updateParameters will set following vars
6567 // mSrcFormat
6568 // mSrcSampleRate
6569 // mDstChannelMask
6570 // mDstFormat
6571 // mDstSampleRate
6572 // mSrcChannelCount
6573 // mDstChannelCount
6574 // mDstFrameSize
6575 mBuf(NULL), mBufFrames(0), mBufFrameSize(0),
Andy Hungd330ee42015-04-20 13:23:41 -07006576 mResampler(NULL),
6577 mIsLegacyDownmix(false),
6578 mIsLegacyUpmix(false),
6579 mRequiresFloat(false),
6580 mInputConverterProvider(NULL)
Andy Hung97a893e2015-03-29 01:03:07 -07006581{
6582 (void)updateParameters(srcChannelMask, srcFormat, srcSampleRate,
6583 dstChannelMask, dstFormat, dstSampleRate);
6584}
6585
6586AudioFlinger::RecordThread::RecordBufferConverter::~RecordBufferConverter() {
6587 free(mBuf);
6588 delete mResampler;
Andy Hungd330ee42015-04-20 13:23:41 -07006589 delete mInputConverterProvider;
Andy Hung97a893e2015-03-29 01:03:07 -07006590}
6591
6592size_t AudioFlinger::RecordThread::RecordBufferConverter::convert(void *dst,
6593 AudioBufferProvider *provider, size_t frames)
6594{
Andy Hungd330ee42015-04-20 13:23:41 -07006595 if (mInputConverterProvider != NULL) {
6596 mInputConverterProvider->setBufferProvider(provider);
6597 provider = mInputConverterProvider;
6598 }
6599
6600 if (mResampler == NULL) {
Andy Hung97a893e2015-03-29 01:03:07 -07006601 ALOGVV("NO RESAMPLING sampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6602 mSrcSampleRate, mSrcFormat, mDstFormat);
6603
6604 AudioBufferProvider::Buffer buffer;
6605 for (size_t i = frames; i > 0; ) {
6606 buffer.frameCount = i;
Glenn Kastend79072e2016-01-06 08:41:20 -08006607 status_t status = provider->getNextBuffer(&buffer);
Andy Hung97a893e2015-03-29 01:03:07 -07006608 if (status != OK || buffer.frameCount == 0) {
6609 frames -= i; // cannot fill request.
6610 break;
6611 }
Andy Hungd330ee42015-04-20 13:23:41 -07006612 // format convert to destination buffer
6613 convertNoResampler(dst, buffer.raw, buffer.frameCount);
Andy Hung97a893e2015-03-29 01:03:07 -07006614
6615 dst = (int8_t*)dst + buffer.frameCount * mDstFrameSize;
6616 i -= buffer.frameCount;
6617 provider->releaseBuffer(&buffer);
6618 }
6619 } else {
6620 ALOGVV("RESAMPLING mSrcSampleRate:%u mDstSampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6621 mSrcSampleRate, mDstSampleRate, mSrcFormat, mDstFormat);
6622
Andy Hungd330ee42015-04-20 13:23:41 -07006623 // reallocate buffer if needed
6624 if (mBufFrameSize != 0 && mBufFrames < frames) {
6625 free(mBuf);
6626 mBufFrames = frames;
6627 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
6628 }
Andy Hung97a893e2015-03-29 01:03:07 -07006629 // resampler accumulates, but we only have one source track
Andy Hungd330ee42015-04-20 13:23:41 -07006630 memset(mBuf, 0, frames * mBufFrameSize);
6631 frames = mResampler->resample((int32_t*)mBuf, frames, provider);
6632 // format convert to destination buffer
6633 convertResampler(dst, mBuf, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006634 }
6635 return frames;
6636}
6637
6638status_t AudioFlinger::RecordThread::RecordBufferConverter::updateParameters(
6639 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6640 uint32_t srcSampleRate,
6641 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6642 uint32_t dstSampleRate)
6643{
6644 // quick evaluation if there is any change.
6645 if (mSrcFormat == srcFormat
6646 && mSrcChannelMask == srcChannelMask
6647 && mSrcSampleRate == srcSampleRate
6648 && mDstFormat == dstFormat
6649 && mDstChannelMask == dstChannelMask
6650 && mDstSampleRate == dstSampleRate) {
6651 return NO_ERROR;
6652 }
6653
Andy Hungdb4c0312015-05-06 08:46:52 -07006654 ALOGV("RecordBufferConverter updateParameters srcMask:%#x dstMask:%#x"
6655 " srcFormat:%#x dstFormat:%#x srcRate:%u dstRate:%u",
6656 srcChannelMask, dstChannelMask, srcFormat, dstFormat, srcSampleRate, dstSampleRate);
Andy Hung97a893e2015-03-29 01:03:07 -07006657 const bool valid =
6658 audio_is_input_channel(srcChannelMask)
6659 && audio_is_input_channel(dstChannelMask)
6660 && audio_is_valid_format(srcFormat) && audio_is_linear_pcm(srcFormat)
6661 && audio_is_valid_format(dstFormat) && audio_is_linear_pcm(dstFormat)
6662 && (srcSampleRate <= dstSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX)
6663 ; // no upsampling checks for now
6664 if (!valid) {
6665 return BAD_VALUE;
6666 }
6667
6668 mSrcFormat = srcFormat;
6669 mSrcChannelMask = srcChannelMask;
6670 mSrcSampleRate = srcSampleRate;
6671 mDstFormat = dstFormat;
6672 mDstChannelMask = dstChannelMask;
6673 mDstSampleRate = dstSampleRate;
6674
6675 // compute derived parameters
6676 mSrcChannelCount = audio_channel_count_from_in_mask(srcChannelMask);
6677 mDstChannelCount = audio_channel_count_from_in_mask(dstChannelMask);
6678 mDstFrameSize = mDstChannelCount * audio_bytes_per_sample(mDstFormat);
6679
Andy Hungd330ee42015-04-20 13:23:41 -07006680 // do we need to resample?
6681 delete mResampler;
6682 mResampler = NULL;
6683 if (mSrcSampleRate != mDstSampleRate) {
6684 mResampler = AudioResampler::create(AUDIO_FORMAT_PCM_FLOAT,
6685 mSrcChannelCount, mDstSampleRate);
6686 mResampler->setSampleRate(mSrcSampleRate);
6687 mResampler->setVolume(AudioMixer::UNITY_GAIN_FLOAT, AudioMixer::UNITY_GAIN_FLOAT);
6688 }
6689
6690 // are we running legacy channel conversion modes?
6691 mIsLegacyDownmix = (mSrcChannelMask == AUDIO_CHANNEL_IN_STEREO
6692 || mSrcChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK)
6693 && mDstChannelMask == AUDIO_CHANNEL_IN_MONO;
6694 mIsLegacyUpmix = mSrcChannelMask == AUDIO_CHANNEL_IN_MONO
6695 && (mDstChannelMask == AUDIO_CHANNEL_IN_STEREO
6696 || mDstChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK);
6697
6698 // do we need to process in float?
6699 mRequiresFloat = mResampler != NULL || mIsLegacyDownmix || mIsLegacyUpmix;
6700
6701 // do we need a staging buffer to convert for destination (we can still optimize this)?
6702 // we use mBufFrameSize > 0 to indicate both frame size as well as buffer necessity
6703 if (mResampler != NULL) {
6704 mBufFrameSize = max(mSrcChannelCount, FCC_2)
6705 * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
Andy Hunga97630b2015-07-22 23:27:24 -07006706 } else if (mIsLegacyUpmix || mIsLegacyDownmix) { // legacy modes always float
Andy Hungd330ee42015-04-20 13:23:41 -07006707 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
6708 } else if (mSrcChannelMask != mDstChannelMask && mDstFormat != mSrcFormat) {
Andy Hung97a893e2015-03-29 01:03:07 -07006709 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(mSrcFormat);
6710 } else {
6711 mBufFrameSize = 0;
6712 }
6713 mBufFrames = 0; // force the buffer to be resized.
6714
Andy Hungd330ee42015-04-20 13:23:41 -07006715 // do we need an input converter buffer provider to give us float?
6716 delete mInputConverterProvider;
6717 mInputConverterProvider = NULL;
6718 if (mRequiresFloat && mSrcFormat != AUDIO_FORMAT_PCM_FLOAT) {
6719 mInputConverterProvider = new ReformatBufferProvider(
6720 audio_channel_count_from_in_mask(mSrcChannelMask),
6721 mSrcFormat,
6722 AUDIO_FORMAT_PCM_FLOAT,
6723 256 /* provider buffer frame count */);
6724 }
6725
6726 // do we need a remixer to do channel mask conversion
6727 if (!mIsLegacyDownmix && !mIsLegacyUpmix && mSrcChannelMask != mDstChannelMask) {
6728 (void) memcpy_by_index_array_initialization_from_channel_mask(
6729 mIdxAry, ARRAY_SIZE(mIdxAry), mDstChannelMask, mSrcChannelMask);
Andy Hung97a893e2015-03-29 01:03:07 -07006730 }
6731 return NO_ERROR;
6732}
6733
Andy Hungd330ee42015-04-20 13:23:41 -07006734void AudioFlinger::RecordThread::RecordBufferConverter::convertNoResampler(
6735 void *dst, const void *src, size_t frames)
Andy Hung97a893e2015-03-29 01:03:07 -07006736{
Andy Hungd330ee42015-04-20 13:23:41 -07006737 // src is native type unless there is legacy upmix or downmix, whereupon it is float.
Andy Hung97a893e2015-03-29 01:03:07 -07006738 if (mBufFrameSize != 0 && mBufFrames < frames) {
6739 free(mBuf);
6740 mBufFrames = frames;
6741 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
6742 }
Andy Hungd330ee42015-04-20 13:23:41 -07006743 // do we need to do legacy upmix and downmix?
6744 if (mIsLegacyUpmix || mIsLegacyDownmix) {
Andy Hung97a893e2015-03-29 01:03:07 -07006745 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07006746 if (mIsLegacyUpmix) {
6747 upmix_to_stereo_float_from_mono_float((float *)dstBuf,
6748 (const float *)src, frames);
6749 } else /*mIsLegacyDownmix */ {
6750 downmix_to_mono_float_from_stereo_float((float *)dstBuf,
6751 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006752 }
Andy Hungd330ee42015-04-20 13:23:41 -07006753 if (mBuf != NULL) {
6754 memcpy_by_audio_format(dst, mDstFormat, mBuf, AUDIO_FORMAT_PCM_FLOAT,
6755 frames * mDstChannelCount);
6756 }
6757 return;
6758 }
6759 // do we need to do channel mask conversion?
6760 if (mSrcChannelMask != mDstChannelMask) {
Andy Hung97a893e2015-03-29 01:03:07 -07006761 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07006762 memcpy_by_index_array(dstBuf, mDstChannelCount,
6763 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mSrcFormat), frames);
6764 if (dstBuf == dst) {
6765 return; // format is the same
6766 }
6767 }
6768 // convert to destination buffer
6769 const void *convertBuf = mBuf != NULL ? mBuf : src;
6770 memcpy_by_audio_format(dst, mDstFormat, convertBuf, mSrcFormat,
6771 frames * mDstChannelCount);
6772}
6773
6774void AudioFlinger::RecordThread::RecordBufferConverter::convertResampler(
6775 void *dst, /*not-a-const*/ void *src, size_t frames)
6776{
6777 // src buffer format is ALWAYS float when entering this routine
6778 if (mIsLegacyUpmix) {
6779 ; // mono to stereo already handled by resampler
6780 } else if (mIsLegacyDownmix
6781 || (mSrcChannelMask == mDstChannelMask && mSrcChannelCount == 1)) {
6782 // the resampler outputs stereo for mono input channel (a feature?)
6783 // must convert to mono
6784 downmix_to_mono_float_from_stereo_float((float *)src,
6785 (const float *)src, frames);
6786 } else if (mSrcChannelMask != mDstChannelMask) {
6787 // convert to mono channel again for channel mask conversion (could be skipped
6788 // with further optimization).
Andy Hung97a893e2015-03-29 01:03:07 -07006789 if (mSrcChannelCount == 1) {
Andy Hungd330ee42015-04-20 13:23:41 -07006790 downmix_to_mono_float_from_stereo_float((float *)src,
6791 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006792 }
Andy Hungd330ee42015-04-20 13:23:41 -07006793 // convert to destination format (in place, OK as float is larger than other types)
6794 if (mDstFormat != AUDIO_FORMAT_PCM_FLOAT) {
6795 memcpy_by_audio_format(src, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
6796 frames * mSrcChannelCount);
6797 }
6798 // channel convert and save to dst
6799 memcpy_by_index_array(dst, mDstChannelCount,
6800 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mDstFormat), frames);
6801 return;
Andy Hung97a893e2015-03-29 01:03:07 -07006802 }
Andy Hungd330ee42015-04-20 13:23:41 -07006803 // convert to destination format and save to dst
6804 memcpy_by_audio_format(dst, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
6805 frames * mDstChannelCount);
Andy Hung97a893e2015-03-29 01:03:07 -07006806}
6807
Eric Laurent10351942014-05-08 18:49:52 -07006808bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
6809 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006810{
6811 bool reconfig = false;
6812
Eric Laurent10351942014-05-08 18:49:52 -07006813 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006814
Eric Laurent10351942014-05-08 18:49:52 -07006815 audio_format_t reqFormat = mFormat;
6816 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07006817 // 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 -07006818 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
6819
6820 AudioParameter param = AudioParameter(keyValuePair);
6821 int value;
6822 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
6823 // channel count change can be requested. Do we mandate the first client defines the
6824 // HAL sampling rate and channel count or do we allow changes on the fly?
6825 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6826 samplingRate = value;
6827 reconfig = true;
6828 }
6829 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07006830 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07006831 status = BAD_VALUE;
6832 } else {
6833 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08006834 reconfig = true;
6835 }
Eric Laurent10351942014-05-08 18:49:52 -07006836 }
6837 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
6838 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07006839 if (!audio_is_input_channel(mask) ||
6840 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07006841 status = BAD_VALUE;
6842 } else {
6843 channelMask = mask;
6844 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006845 }
Eric Laurent10351942014-05-08 18:49:52 -07006846 }
6847 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6848 // do not accept frame count changes if tracks are open as the track buffer
6849 // size depends on frame count and correct behavior would not be guaranteed
6850 // if frame count is changed after track creation
6851 if (mActiveTracks.size() > 0) {
6852 status = INVALID_OPERATION;
6853 } else {
6854 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006855 }
Eric Laurent10351942014-05-08 18:49:52 -07006856 }
6857 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6858 // forward device change to effects that have requested to be
6859 // aware of attached audio device.
6860 for (size_t i = 0; i < mEffectChains.size(); i++) {
6861 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08006862 }
Eric Laurent81784c32012-11-19 14:55:58 -08006863
Eric Laurent10351942014-05-08 18:49:52 -07006864 // store input device and output device but do not forward output device to audio HAL.
6865 // Note that status is ignored by the caller for output device
6866 // (see AudioFlinger::setParameters()
6867 if (audio_is_output_devices(value)) {
6868 mOutDevice = value;
6869 status = BAD_VALUE;
6870 } else {
6871 mInDevice = value;
Eric Laurente8726fe2015-06-26 09:39:24 -07006872 if (value != AUDIO_DEVICE_NONE) {
6873 mPrevInDevice = value;
6874 }
Eric Laurent10351942014-05-08 18:49:52 -07006875 // disable AEC and NS if the device is a BT SCO headset supporting those
6876 // pre processings
6877 if (mTracks.size() > 0) {
6878 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6879 mAudioFlinger->btNrecIsOff();
6880 for (size_t i = 0; i < mTracks.size(); i++) {
6881 sp<RecordTrack> track = mTracks[i];
6882 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
6883 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08006884 }
6885 }
6886 }
Eric Laurent10351942014-05-08 18:49:52 -07006887 }
6888 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
6889 mAudioSource != (audio_source_t)value) {
6890 // forward device change to effects that have requested to be
6891 // aware of attached audio device.
6892 for (size_t i = 0; i < mEffectChains.size(); i++) {
6893 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08006894 }
Eric Laurent10351942014-05-08 18:49:52 -07006895 mAudioSource = (audio_source_t)value;
6896 }
Glenn Kastene198c362013-08-13 09:13:36 -07006897
Eric Laurent10351942014-05-08 18:49:52 -07006898 if (status == NO_ERROR) {
6899 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6900 keyValuePair.string());
6901 if (status == INVALID_OPERATION) {
6902 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006903 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6904 keyValuePair.string());
Eric Laurent10351942014-05-08 18:49:52 -07006905 }
6906 if (reconfig) {
6907 if (status == BAD_VALUE &&
Andy Hung97a893e2015-03-29 01:03:07 -07006908 audio_is_linear_pcm(mInput->stream->common.get_format(&mInput->stream->common)) &&
6909 audio_is_linear_pcm(reqFormat) &&
Eric Laurent10351942014-05-08 18:49:52 -07006910 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
Andy Hung97a893e2015-03-29 01:03:07 -07006911 <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate)) &&
Andy Hunge5412692014-05-16 11:25:07 -07006912 audio_channel_count_from_in_mask(
Andy Hungd1abb8f2015-05-05 23:42:34 -07006913 mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07006914 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006915 }
Eric Laurent10351942014-05-08 18:49:52 -07006916 if (status == NO_ERROR) {
6917 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07006918 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08006919 }
6920 }
Eric Laurent81784c32012-11-19 14:55:58 -08006921 }
Eric Laurent10351942014-05-08 18:49:52 -07006922
Eric Laurent81784c32012-11-19 14:55:58 -08006923 return reconfig;
6924}
6925
6926String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6927{
Eric Laurent81784c32012-11-19 14:55:58 -08006928 Mutex::Autolock _l(mLock);
6929 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07006930 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08006931 }
6932
Glenn Kastend8ea6992013-07-16 14:17:15 -07006933 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
6934 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08006935 free(s);
6936 return out_s8;
6937}
6938
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07006939void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07006940 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
6941
6942 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08006943
6944 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07006945 case AUDIO_INPUT_OPENED:
6946 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07006947 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07006948 desc->mChannelMask = mChannelMask;
6949 desc->mSamplingRate = mSampleRate;
6950 desc->mFormat = mFormat;
6951 desc->mFrameCount = mFrameCount;
6952 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006953 break;
6954
Eric Laurent73e26b62015-04-27 16:55:58 -07006955 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08006956 default:
6957 break;
6958 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07006959 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08006960}
6961
Glenn Kastendeca2ae2014-02-07 10:25:56 -08006962void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006963{
Eric Laurent81784c32012-11-19 14:55:58 -08006964 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
6965 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Andy Hunge5412692014-05-16 11:25:07 -07006966 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Andy Hungd330ee42015-04-20 13:23:41 -07006967 if (mChannelCount > FCC_8) {
6968 ALOGE("HAL channel count %d > %d", mChannelCount, FCC_8);
6969 }
Andy Hung463be252014-07-10 16:56:07 -07006970 mHALFormat = mInput->stream->common.get_format(&mInput->stream->common);
6971 mFormat = mHALFormat;
Andy Hungd330ee42015-04-20 13:23:41 -07006972 if (!audio_is_linear_pcm(mFormat)) {
6973 ALOGE("HAL format %#x is not linear pcm", mFormat);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07006974 }
Eric Laurent665470b2014-07-03 16:37:08 -07006975 mFrameSize = audio_stream_in_frame_size(mInput->stream);
Glenn Kasten548efc92012-11-29 08:48:51 -08006976 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
6977 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006978 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08006979 // 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 -07006980 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08006981 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006982 // A larger value should allow more old data to be read after a track calls start(),
6983 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07006984 //
6985 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08006986 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07006987 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07006988 free(mRsmpInBuffer);
Andy Hung0a01c2f2015-09-21 12:44:54 -07006989 mRsmpInBuffer = NULL;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006990
6991 // TODO optimize audio capture buffer sizes ...
6992 // Here we calculate the size of the sliding buffer used as a source
6993 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
6994 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
6995 // be better to have it derived from the pipe depth in the long term.
6996 // The current value is higher than necessary. However it should not add to latency.
6997
Glenn Kasten85948432013-08-19 12:09:05 -07006998 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Andy Hung0a01c2f2015-09-21 12:44:54 -07006999 size_t bufferSize = (mRsmpInFramesP2 + mFrameCount - 1) * mFrameSize;
7000 (void)posix_memalign(&mRsmpInBuffer, 32, bufferSize);
7001 memset(mRsmpInBuffer, 0, bufferSize); // if posix_memalign fails, will segv here.
Eric Laurent81784c32012-11-19 14:55:58 -08007002
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007003 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
7004 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08007005}
7006
Glenn Kasten5f972c02014-01-13 09:59:31 -08007007uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08007008{
7009 Mutex::Autolock _l(mLock);
7010 if (initCheck() != NO_ERROR) {
7011 return 0;
7012 }
7013
7014 return mInput->stream->get_input_frames_lost(mInput->stream);
7015}
7016
7017uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
7018{
7019 Mutex::Autolock _l(mLock);
7020 uint32_t result = 0;
7021 if (getEffectChain_l(sessionId) != 0) {
7022 result = EFFECT_SESSION;
7023 }
7024
7025 for (size_t i = 0; i < mTracks.size(); ++i) {
7026 if (sessionId == mTracks[i]->sessionId()) {
7027 result |= TRACK_SESSION;
7028 break;
7029 }
7030 }
7031
7032 return result;
7033}
7034
7035KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
7036{
7037 KeyedVector<int, bool> ids;
7038 Mutex::Autolock _l(mLock);
7039 for (size_t j = 0; j < mTracks.size(); ++j) {
7040 sp<RecordThread::RecordTrack> track = mTracks[j];
7041 int sessionId = track->sessionId();
7042 if (ids.indexOfKey(sessionId) < 0) {
7043 ids.add(sessionId, true);
7044 }
7045 }
7046 return ids;
7047}
7048
7049AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
7050{
7051 Mutex::Autolock _l(mLock);
7052 AudioStreamIn *input = mInput;
7053 mInput = NULL;
7054 return input;
7055}
7056
7057// this method must always be called either with ThreadBase mLock held or inside the thread loop
7058audio_stream_t* AudioFlinger::RecordThread::stream() const
7059{
7060 if (mInput == NULL) {
7061 return NULL;
7062 }
7063 return &mInput->stream->common;
7064}
7065
7066status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7067{
7068 // only one chain per input thread
7069 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07007070 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08007071 return INVALID_OPERATION;
7072 }
7073 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07007074 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08007075 chain->setInBuffer(NULL);
7076 chain->setOutBuffer(NULL);
7077
7078 checkSuspendOnAddEffectChain_l(chain);
7079
Eric Laurent1b928682014-10-02 19:41:47 -07007080 // make sure enabled pre processing effects state is communicated to the HAL as we
7081 // just moved them to a new input stream.
7082 chain->syncHalEffectsState();
7083
Eric Laurent81784c32012-11-19 14:55:58 -08007084 mEffectChains.add(chain);
7085
7086 return NO_ERROR;
7087}
7088
7089size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7090{
7091 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
7092 ALOGW_IF(mEffectChains.size() != 1,
7093 "removeEffectChain_l() %p invalid chain size %d on thread %p",
7094 chain.get(), mEffectChains.size(), this);
7095 if (mEffectChains.size() == 1) {
7096 mEffectChains.removeAt(0);
7097 }
7098 return 0;
7099}
7100
Eric Laurent1c333e22014-05-20 10:48:17 -07007101status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
7102 audio_patch_handle_t *handle)
7103{
7104 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007105
7106 // store new device and send to effects
7107 mInDevice = patch->sources[0].ext.device.type;
Eric Laurent296fb132015-05-01 11:38:42 -07007108 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07007109 for (size_t i = 0; i < mEffectChains.size(); i++) {
7110 mEffectChains[i]->setDevice_l(mInDevice);
7111 }
7112
7113 // disable AEC and NS if the device is a BT SCO headset supporting those
7114 // pre processings
7115 if (mTracks.size() > 0) {
7116 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7117 mAudioFlinger->btNrecIsOff();
7118 for (size_t i = 0; i < mTracks.size(); i++) {
7119 sp<RecordTrack> track = mTracks[i];
7120 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7121 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
7122 }
7123 }
7124
7125 // store new source and send to effects
7126 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7127 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07007128 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07007129 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07007130 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007131 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007132
Eric Laurent054d9d32015-04-24 08:48:48 -07007133 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007134 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
7135 status = hwDevice->create_audio_patch(hwDevice,
7136 patch->num_sources,
7137 patch->sources,
7138 patch->num_sinks,
7139 patch->sinks,
7140 handle);
7141 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007142 char *address;
7143 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
7144 address = audio_device_address_to_parameter(
7145 patch->sources[0].ext.device.type,
7146 patch->sources[0].ext.device.address);
7147 } else {
7148 address = (char *)calloc(1, 1);
7149 }
7150 AudioParameter param = AudioParameter(String8(address));
7151 free(address);
7152 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING),
7153 (int)patch->sources[0].ext.device.type);
7154 param.addInt(String8(AUDIO_PARAMETER_STREAM_INPUT_SOURCE),
7155 (int)patch->sinks[0].ext.mix.usecase.source);
7156 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7157 param.toString().string());
7158 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07007159 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007160
Eric Laurente8726fe2015-06-26 09:39:24 -07007161 if (mInDevice != mPrevInDevice) {
7162 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
7163 mPrevInDevice = mInDevice;
7164 }
Eric Laurent296fb132015-05-01 11:38:42 -07007165
Eric Laurent1c333e22014-05-20 10:48:17 -07007166 return status;
7167}
7168
7169status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
7170{
7171 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007172
7173 mInDevice = AUDIO_DEVICE_NONE;
7174
Eric Laurent1c333e22014-05-20 10:48:17 -07007175 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
7176 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
7177 status = hwDevice->release_audio_patch(hwDevice, handle);
7178 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007179 AudioParameter param;
7180 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
7181 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7182 param.toString().string());
Eric Laurent1c333e22014-05-20 10:48:17 -07007183 }
7184 return status;
7185}
7186
Eric Laurent83b88082014-06-20 18:31:16 -07007187void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
7188{
7189 Mutex::Autolock _l(mLock);
7190 mTracks.add(record);
7191}
7192
7193void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
7194{
7195 Mutex::Autolock _l(mLock);
7196 destroyTrack_l(record);
7197}
7198
7199void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
7200{
7201 ThreadBase::getAudioPortConfig(config);
7202 config->role = AUDIO_PORT_ROLE_SINK;
7203 config->ext.mix.hw_module = mInput->audioHwDev->handle();
7204 config->ext.mix.usecase.source = mAudioSource;
7205}
Eric Laurent1c333e22014-05-20 10:48:17 -07007206
Glenn Kasten63238ef2015-03-02 15:50:29 -08007207} // namespace android