blob: 7a29ccead4e9a3eee672c26a0f58d4fc6b474807 [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) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08002920 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
2921 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08002922 }
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()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08002961 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
2962 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08002963 }
2964
Andy Hung98ef9782014-03-04 14:46:50 -08002965 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
2966 mNormalFrameCount * mChannelCount);
2967 }
2968
Eric Laurent81784c32012-11-19 14:55:58 -08002969 // enable changes in effect chain
2970 unlockEffectChains(effectChains);
2971
Eric Laurentbfb1b832013-01-07 09:53:42 -08002972 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002973 // mSleepTimeUs == 0 means we must write to audio hardware
2974 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07002975 ssize_t ret = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002976 if (mBytesRemaining) {
Andy Hung08fb1742015-05-31 23:22:10 -07002977 ret = threadLoop_write();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002978 if (ret < 0) {
2979 mBytesRemaining = 0;
2980 } else {
2981 mBytesWritten += ret;
2982 mBytesRemaining -= ret;
2983 }
2984 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
2985 (mMixerStatus == MIXER_DRAIN_ALL)) {
2986 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08002987 }
Andy Hung08fb1742015-05-31 23:22:10 -07002988 if (mType == MIXER && !mStandby) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07002989 // write blocked detection
2990 nsecs_t now = systemTime();
2991 nsecs_t delta = now - mLastWriteTime;
Andy Hung08fb1742015-05-31 23:22:10 -07002992 if (delta > maxPeriod) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07002993 mNumDelayedWrites++;
2994 if ((now - lastWarning) > kWarningThrottleNs) {
2995 ATRACE_NAME("underrun");
2996 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2997 ns2ms(delta), mNumDelayedWrites, this);
2998 lastWarning = now;
2999 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003000 }
Andy Hung08fb1742015-05-31 23:22:10 -07003001
3002 if (mThreadThrottle
3003 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
3004 && ret > 0) { // we wrote something
3005 // Limit MixerThread data processing to no more than twice the
3006 // expected processing rate.
3007 //
3008 // This helps prevent underruns with NuPlayer and other applications
3009 // which may set up buffers that are close to the minimum size, or use
3010 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3011 //
3012 // The throttle smooths out sudden large data drains from the device,
3013 // e.g. when it comes out of standby, which often causes problems with
3014 // (1) mixer threads without a fast mixer (which has its own warm-up)
3015 // (2) minimum buffer sized tracks (even if the track is full,
3016 // the app won't fill fast enough to handle the sudden draw).
3017
3018 const int32_t deltaMs = delta / 1000000;
3019 const int32_t throttleMs = mHalfBufferMs - deltaMs;
3020 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
3021 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003022 // notify of throttle start on verbose log
3023 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3024 "mixer(%p) throttle begin:"
3025 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003026 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07003027 mThreadThrottleTimeMs += throttleMs;
3028 } else {
3029 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3030 if (diff > 0) {
3031 // notify of throttle end on debug log
3032 ALOGD("mixer(%p) throttle end: throttle time(%u)", this, diff);
3033 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3034 }
Andy Hung08fb1742015-05-31 23:22:10 -07003035 }
3036 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003037 }
Eric Laurent81784c32012-11-19 14:55:58 -08003038
Eric Laurentbfb1b832013-01-07 09:53:42 -08003039 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003040 ATRACE_BEGIN("sleep");
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003041 usleep(mSleepTimeUs);
Glenn Kastene7754022014-10-31 12:11:26 -07003042 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003043 }
Eric Laurent81784c32012-11-19 14:55:58 -08003044 }
3045
3046 // Finally let go of removed track(s), without the lock held
3047 // since we can't guarantee the destructors won't acquire that
3048 // same lock. This will also mutate and push a new fast mixer state.
3049 threadLoop_removeTracks(tracksToRemove);
3050 tracksToRemove.clear();
3051
3052 // FIXME I don't understand the need for this here;
3053 // it was in the original code but maybe the
3054 // assignment in saveOutputTracks() makes this unnecessary?
3055 clearOutputTracks();
3056
3057 // Effect chains will be actually deleted here if they were removed from
3058 // mEffectChains list during mixing or effects processing
3059 effectChains.clear();
3060
3061 // FIXME Note that the above .clear() is no longer necessary since effectChains
3062 // is now local to this block, but will keep it for now (at least until merge done).
3063 }
3064
Eric Laurentbfb1b832013-01-07 09:53:42 -08003065 threadLoop_exit();
3066
Eric Laurentcf817a22014-08-04 20:36:31 -07003067 if (!mStandby) {
3068 threadLoop_standby();
3069 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003070 }
3071
3072 releaseWakeLock();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003073 mWakeLockUids.clear();
3074 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08003075
3076 ALOGV("Thread %p type %d exiting", this, mType);
3077 return false;
3078}
3079
Eric Laurentbfb1b832013-01-07 09:53:42 -08003080// removeTracks_l() must be called with ThreadBase::mLock held
3081void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3082{
3083 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07003084 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003085 for (size_t i=0 ; i<count ; i++) {
3086 const sp<Track>& track = tracksToRemove.itemAt(i);
3087 mActiveTracks.remove(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003088 mWakeLockUids.remove(track->uid());
3089 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003090 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
3091 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3092 if (chain != 0) {
3093 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
3094 track->sessionId());
3095 chain->decActiveTrackCnt();
3096 }
3097 if (track->isTerminated()) {
3098 removeTrack_l(track);
3099 }
3100 }
3101 }
3102
3103}
Eric Laurent81784c32012-11-19 14:55:58 -08003104
Eric Laurentaccc1472013-09-20 09:36:34 -07003105status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3106{
3107 if (mNormalSink != 0) {
3108 return mNormalSink->getTimestamp(timestamp);
3109 }
Andy Hung9a1c8892014-12-03 11:37:42 -08003110 if ((mType == OFFLOAD || mType == DIRECT)
3111 && mOutput != NULL && mOutput->stream->get_presentation_position) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003112 uint64_t position64;
Phil Burk062e67a2015-02-11 13:40:50 -08003113 int ret = mOutput->getPresentationPosition(&position64, &timestamp.mTime);
Eric Laurentaccc1472013-09-20 09:36:34 -07003114 if (ret == 0) {
3115 timestamp.mPosition = (uint32_t)position64;
3116 return NO_ERROR;
3117 }
3118 }
3119 return INVALID_OPERATION;
3120}
Eric Laurent1c333e22014-05-20 10:48:17 -07003121
Eric Laurent054d9d32015-04-24 08:48:48 -07003122status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
3123 audio_patch_handle_t *handle)
3124{
3125 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3126 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3127 if (mFastMixer != 0) {
3128 FastMixerStateQueue *sq = mFastMixer->sq();
3129 FastMixerState *state = sq->begin();
3130 if (!(state->mCommand & FastMixerState::IDLE)) {
3131 previousCommand = state->mCommand;
3132 state->mCommand = FastMixerState::HOT_IDLE;
3133 sq->end();
3134 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3135 } else {
3136 sq->end(false /*didModify*/);
3137 }
3138 }
3139 status_t status = PlaybackThread::createAudioPatch_l(patch, handle);
3140
3141 if (!(previousCommand & FastMixerState::IDLE)) {
3142 ALOG_ASSERT(mFastMixer != 0);
3143 FastMixerStateQueue *sq = mFastMixer->sq();
3144 FastMixerState *state = sq->begin();
3145 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3146 state->mCommand = previousCommand;
3147 sq->end();
3148 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3149 }
3150
3151 return status;
3152}
3153
Eric Laurent1c333e22014-05-20 10:48:17 -07003154status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3155 audio_patch_handle_t *handle)
3156{
3157 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003158
3159 // store new device and send to effects
3160 audio_devices_t type = AUDIO_DEVICE_NONE;
3161 for (unsigned int i = 0; i < patch->num_sinks; i++) {
3162 type |= patch->sinks[i].ext.device.type;
3163 }
3164
3165#ifdef ADD_BATTERY_DATA
3166 // when changing the audio output device, call addBatteryData to notify
3167 // the change
3168 if (mOutDevice != type) {
3169 uint32_t params = 0;
3170 // check whether speaker is on
3171 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3172 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003173 }
3174
Eric Laurent054d9d32015-04-24 08:48:48 -07003175 audio_devices_t deviceWithoutSpeaker
3176 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3177 // check if any other device (except speaker) is on
3178 if (type & deviceWithoutSpeaker) {
3179 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3180 }
3181
3182 if (params != 0) {
3183 addBatteryData(params);
3184 }
3185 }
3186#endif
3187
3188 for (size_t i = 0; i < mEffectChains.size(); i++) {
3189 mEffectChains[i]->setDevice_l(type);
3190 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003191
3192 // mPrevOutDevice is the latest device set by createAudioPatch_l(). It is not set when
3193 // the thread is created so that the first patch creation triggers an ioConfigChanged callback
3194 bool configChanged = mPrevOutDevice != type;
Eric Laurent054d9d32015-04-24 08:48:48 -07003195 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003196 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003197
3198 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003199 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
3200 status = hwDevice->create_audio_patch(hwDevice,
3201 patch->num_sources,
3202 patch->sources,
3203 patch->num_sinks,
3204 patch->sinks,
3205 handle);
3206 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003207 char *address;
3208 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3209 //FIXME: we only support address on first sink with HAL version < 3.0
3210 address = audio_device_address_to_parameter(
3211 patch->sinks[0].ext.device.type,
3212 patch->sinks[0].ext.device.address);
3213 } else {
3214 address = (char *)calloc(1, 1);
3215 }
3216 AudioParameter param = AudioParameter(String8(address));
3217 free(address);
3218 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), (int)type);
3219 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3220 param.toString().string());
3221 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003222 }
Eric Laurente8726fe2015-06-26 09:39:24 -07003223 if (configChanged) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003224 mPrevOutDevice = type;
Eric Laurente8726fe2015-06-26 09:39:24 -07003225 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
3226 }
Eric Laurent1c333e22014-05-20 10:48:17 -07003227 return status;
3228}
3229
Eric Laurent054d9d32015-04-24 08:48:48 -07003230status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3231{
3232 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3233 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3234 if (mFastMixer != 0) {
3235 FastMixerStateQueue *sq = mFastMixer->sq();
3236 FastMixerState *state = sq->begin();
3237 if (!(state->mCommand & FastMixerState::IDLE)) {
3238 previousCommand = state->mCommand;
3239 state->mCommand = FastMixerState::HOT_IDLE;
3240 sq->end();
3241 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3242 } else {
3243 sq->end(false /*didModify*/);
3244 }
3245 }
3246
3247 status_t status = PlaybackThread::releaseAudioPatch_l(handle);
3248
3249 if (!(previousCommand & FastMixerState::IDLE)) {
3250 ALOG_ASSERT(mFastMixer != 0);
3251 FastMixerStateQueue *sq = mFastMixer->sq();
3252 FastMixerState *state = sq->begin();
3253 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3254 state->mCommand = previousCommand;
3255 sq->end();
3256 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3257 }
3258
3259 return status;
3260}
3261
Eric Laurent1c333e22014-05-20 10:48:17 -07003262status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3263{
3264 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003265
3266 mOutDevice = AUDIO_DEVICE_NONE;
3267
Eric Laurent1c333e22014-05-20 10:48:17 -07003268 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
3269 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
3270 status = hwDevice->release_audio_patch(hwDevice, handle);
3271 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003272 AudioParameter param;
3273 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
3274 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3275 param.toString().string());
Eric Laurent1c333e22014-05-20 10:48:17 -07003276 }
3277 return status;
3278}
3279
Eric Laurent83b88082014-06-20 18:31:16 -07003280void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3281{
3282 Mutex::Autolock _l(mLock);
3283 mTracks.add(track);
3284}
3285
3286void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3287{
3288 Mutex::Autolock _l(mLock);
3289 destroyTrack_l(track);
3290}
3291
3292void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
3293{
3294 ThreadBase::getAudioPortConfig(config);
3295 config->role = AUDIO_PORT_ROLE_SOURCE;
3296 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3297 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
3298}
3299
Eric Laurent81784c32012-11-19 14:55:58 -08003300// ----------------------------------------------------------------------------
3301
3302AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurent72e3f392015-05-20 14:43:50 -07003303 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
3304 : PlaybackThread(audioFlinger, output, id, device, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08003305 // mAudioMixer below
3306 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08003307 mFastMixerFutex(0),
3308 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08003309 // mOutputSink below
3310 // mPipeSink below
3311 // mNormalSink below
3312{
3313 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07003314 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, "
Eric Laurent81784c32012-11-19 14:55:58 -08003315 "mFrameCount=%d, mNormalFrameCount=%d",
3316 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3317 mNormalFrameCount);
3318 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3319
Andy Hungfbfc3952015-01-15 13:33:51 -08003320 if (type == DUPLICATING) {
3321 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3322 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3323 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3324 return;
3325 }
Eric Laurent81784c32012-11-19 14:55:58 -08003326 // create an NBAIO sink for the HAL output stream, and negotiate
3327 mOutputSink = new AudioStreamOutSink(output->stream);
3328 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003329 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Eric Laurent81784c32012-11-19 14:55:58 -08003330 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
3331 ALOG_ASSERT(index == 0);
3332
3333 // initialize fast mixer depending on configuration
3334 bool initFastMixer;
3335 switch (kUseFastMixer) {
3336 case FastMixer_Never:
3337 initFastMixer = false;
3338 break;
3339 case FastMixer_Always:
3340 initFastMixer = true;
3341 break;
3342 case FastMixer_Static:
3343 case FastMixer_Dynamic:
3344 initFastMixer = mFrameCount < mNormalFrameCount;
3345 break;
3346 }
3347 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003348 audio_format_t fastMixerFormat;
3349 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3350 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3351 } else {
3352 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3353 }
3354 if (mFormat != fastMixerFormat) {
3355 // change our Sink format to accept our intermediate precision
3356 mFormat = fastMixerFormat;
3357 free(mSinkBuffer);
3358 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3359 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3360 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3361 }
Eric Laurent81784c32012-11-19 14:55:58 -08003362
3363 // create a MonoPipe to connect our submix to FastMixer
3364 NBAIO_Format format = mOutputSink->format();
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003365 NBAIO_Format origformat = format;
Andy Hung1258c1a2014-05-23 21:22:17 -07003366 // adjust format to match that of the Fast Mixer
Glenn Kasten97b7b752014-09-28 13:04:24 -07003367 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003368 format.mFormat = fastMixerFormat;
3369 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3370
Eric Laurent81784c32012-11-19 14:55:58 -08003371 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3372 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3373 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3374 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3375 const NBAIO_Format offers[1] = {format};
3376 size_t numCounterOffers = 0;
3377 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
3378 ALOG_ASSERT(index == 0);
3379 monoPipe->setAvgFrames((mScreenState & 1) ?
3380 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3381 mPipeSink = monoPipe;
3382
Glenn Kasten46909e72013-02-26 09:20:22 -08003383#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08003384 if (mTeeSinkOutputEnabled) {
3385 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003386 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
3387 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08003388 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003389 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003390 ALOG_ASSERT(index == 0);
3391 mTeeSink = teeSink;
3392 PipeReader *teeSource = new PipeReader(*teeSink);
3393 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003394 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003395 ALOG_ASSERT(index == 0);
3396 mTeeSource = teeSource;
3397 }
Glenn Kasten46909e72013-02-26 09:20:22 -08003398#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003399
3400 // create fast mixer and configure it initially with just one fast track for our submix
3401 mFastMixer = new FastMixer();
3402 FastMixerStateQueue *sq = mFastMixer->sq();
3403#ifdef STATE_QUEUE_DUMP
3404 sq->setObserverDump(&mStateQueueObserverDump);
3405 sq->setMutatorDump(&mStateQueueMutatorDump);
3406#endif
3407 FastMixerState *state = sq->begin();
3408 FastTrack *fastTrack = &state->mFastTracks[0];
3409 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3410 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3411 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003412 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3413 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003414 fastTrack->mGeneration++;
3415 state->mFastTracksGen++;
3416 state->mTrackMask = 1;
3417 // fast mixer will use the HAL output sink
3418 state->mOutputSink = mOutputSink.get();
3419 state->mOutputSinkGen++;
3420 state->mFrameCount = mFrameCount;
3421 state->mCommand = FastMixerState::COLD_IDLE;
3422 // already done in constructor initialization list
3423 //mFastMixerFutex = 0;
3424 state->mColdFutexAddr = &mFastMixerFutex;
3425 state->mColdGen++;
3426 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08003427#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003428 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08003429#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08003430 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3431 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003432 sq->end();
3433 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3434
3435 // start the fast mixer
3436 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3437 pid_t tid = mFastMixer->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003438 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003439
3440#ifdef AUDIO_WATCHDOG
3441 // create and start the watchdog
3442 mAudioWatchdog = new AudioWatchdog();
3443 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3444 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3445 tid = mAudioWatchdog->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003446 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003447#endif
3448
Eric Laurent81784c32012-11-19 14:55:58 -08003449 }
3450
3451 switch (kUseFastMixer) {
3452 case FastMixer_Never:
3453 case FastMixer_Dynamic:
3454 mNormalSink = mOutputSink;
3455 break;
3456 case FastMixer_Always:
3457 mNormalSink = mPipeSink;
3458 break;
3459 case FastMixer_Static:
3460 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3461 break;
3462 }
3463}
3464
3465AudioFlinger::MixerThread::~MixerThread()
3466{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003467 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003468 FastMixerStateQueue *sq = mFastMixer->sq();
3469 FastMixerState *state = sq->begin();
3470 if (state->mCommand == FastMixerState::COLD_IDLE) {
3471 int32_t old = android_atomic_inc(&mFastMixerFutex);
3472 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003473 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003474 }
3475 }
3476 state->mCommand = FastMixerState::EXIT;
3477 sq->end();
3478 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3479 mFastMixer->join();
3480 // Though the fast mixer thread has exited, it's state queue is still valid.
3481 // We'll use that extract the final state which contains one remaining fast track
3482 // corresponding to our sub-mix.
3483 state = sq->begin();
3484 ALOG_ASSERT(state->mTrackMask == 1);
3485 FastTrack *fastTrack = &state->mFastTracks[0];
3486 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3487 delete fastTrack->mBufferProvider;
3488 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003489 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003490#ifdef AUDIO_WATCHDOG
3491 if (mAudioWatchdog != 0) {
3492 mAudioWatchdog->requestExit();
3493 mAudioWatchdog->requestExitAndWait();
3494 mAudioWatchdog.clear();
3495 }
3496#endif
3497 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003498 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003499 delete mAudioMixer;
3500}
3501
3502
3503uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3504{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003505 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003506 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3507 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3508 }
3509 return latency;
3510}
3511
3512
3513void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3514{
3515 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3516}
3517
Eric Laurentbfb1b832013-01-07 09:53:42 -08003518ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003519{
3520 // FIXME we should only do one push per cycle; confirm this is true
3521 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003522 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003523 FastMixerStateQueue *sq = mFastMixer->sq();
3524 FastMixerState *state = sq->begin();
3525 if (state->mCommand != FastMixerState::MIX_WRITE &&
3526 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3527 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07003528
3529 // FIXME workaround for first HAL write being CPU bound on some devices
3530 ATRACE_BEGIN("write");
3531 mOutput->write((char *)mSinkBuffer, 0);
3532 ATRACE_END();
3533
Eric Laurent81784c32012-11-19 14:55:58 -08003534 int32_t old = android_atomic_inc(&mFastMixerFutex);
3535 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003536 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003537 }
3538#ifdef AUDIO_WATCHDOG
3539 if (mAudioWatchdog != 0) {
3540 mAudioWatchdog->resume();
3541 }
3542#endif
3543 }
3544 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08003545#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003546 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08003547 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08003548#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003549 sq->end();
3550 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3551 if (kUseFastMixer == FastMixer_Dynamic) {
3552 mNormalSink = mPipeSink;
3553 }
3554 } else {
3555 sq->end(false /*didModify*/);
3556 }
3557 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003558 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003559}
3560
3561void AudioFlinger::MixerThread::threadLoop_standby()
3562{
3563 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003564 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003565 FastMixerStateQueue *sq = mFastMixer->sq();
3566 FastMixerState *state = sq->begin();
3567 if (!(state->mCommand & FastMixerState::IDLE)) {
3568 state->mCommand = FastMixerState::COLD_IDLE;
3569 state->mColdFutexAddr = &mFastMixerFutex;
3570 state->mColdGen++;
3571 mFastMixerFutex = 0;
3572 sq->end();
3573 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3574 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3575 if (kUseFastMixer == FastMixer_Dynamic) {
3576 mNormalSink = mOutputSink;
3577 }
3578#ifdef AUDIO_WATCHDOG
3579 if (mAudioWatchdog != 0) {
3580 mAudioWatchdog->pause();
3581 }
3582#endif
3583 } else {
3584 sq->end(false /*didModify*/);
3585 }
3586 }
3587 PlaybackThread::threadLoop_standby();
3588}
3589
Eric Laurentbfb1b832013-01-07 09:53:42 -08003590bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3591{
3592 return false;
3593}
3594
3595bool AudioFlinger::PlaybackThread::shouldStandby_l()
3596{
3597 return !mStandby;
3598}
3599
3600bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3601{
3602 Mutex::Autolock _l(mLock);
3603 return waitingAsyncCallback_l();
3604}
3605
Eric Laurent81784c32012-11-19 14:55:58 -08003606// shared by MIXER and DIRECT, overridden by DUPLICATING
3607void AudioFlinger::PlaybackThread::threadLoop_standby()
3608{
3609 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08003610 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003611 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003612 // discard any pending drain or write ack by incrementing sequence
3613 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3614 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003615 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003616 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3617 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003618 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003619 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003620}
3621
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003622void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3623{
3624 ALOGV("signal playback thread");
3625 broadcast_l();
3626}
3627
Eric Laurent81784c32012-11-19 14:55:58 -08003628void AudioFlinger::MixerThread::threadLoop_mix()
3629{
Eric Laurent81784c32012-11-19 14:55:58 -08003630 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08003631 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08003632 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003633 // increase sleep time progressively when application underrun condition clears.
3634 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3635 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3636 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003637 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003638 sleepTimeShift--;
3639 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003640 mSleepTimeUs = 0;
3641 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08003642 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003643
Eric Laurent81784c32012-11-19 14:55:58 -08003644}
3645
3646void AudioFlinger::MixerThread::threadLoop_sleepTime()
3647{
3648 // If no tracks are ready, sleep once for the duration of an output
3649 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003650 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003651 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003652 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
3653 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
3654 mSleepTimeUs = kMinThreadSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003655 }
3656 // reduce sleep time in case of consecutive application underruns to avoid
3657 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3658 // duration we would end up writing less data than needed by the audio HAL if
3659 // the condition persists.
3660 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3661 sleepTimeShift++;
3662 }
3663 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003664 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003665 }
3666 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003667 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3668 // before effects processing or output.
3669 if (mMixerBufferValid) {
3670 memset(mMixerBuffer, 0, mMixerBufferSize);
3671 } else {
3672 memset(mSinkBuffer, 0, mSinkBufferSize);
3673 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003674 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003675 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3676 "anticipated start");
3677 }
3678 // TODO add standby time extension fct of effect tail
3679}
3680
3681// prepareTracks_l() must be called with ThreadBase::mLock held
3682AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3683 Vector< sp<Track> > *tracksToRemove)
3684{
3685
3686 mixer_state mixerStatus = MIXER_IDLE;
3687 // find out which tracks need to be processed
3688 size_t count = mActiveTracks.size();
3689 size_t mixedTracks = 0;
3690 size_t tracksWithEffect = 0;
3691 // counts only _active_ fast tracks
3692 size_t fastTracks = 0;
3693 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
3694
3695 float masterVolume = mMasterVolume;
3696 bool masterMute = mMasterMute;
3697
3698 if (masterMute) {
3699 masterVolume = 0;
3700 }
3701 // Delegate master volume control to effect in output mix effect chain if needed
3702 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3703 if (chain != 0) {
3704 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
3705 chain->setVolume_l(&v, &v);
3706 masterVolume = (float)((v + (1 << 23)) >> 24);
3707 chain.clear();
3708 }
3709
3710 // prepare a new state to push
3711 FastMixerStateQueue *sq = NULL;
3712 FastMixerState *state = NULL;
3713 bool didModify = false;
3714 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003715 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003716 sq = mFastMixer->sq();
3717 state = sq->begin();
3718 }
3719
Andy Hung69aed5f2014-02-25 17:24:40 -08003720 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08003721 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08003722
Eric Laurent81784c32012-11-19 14:55:58 -08003723 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003724 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003725 if (t == 0) {
3726 continue;
3727 }
3728
3729 // this const just means the local variable doesn't change
3730 Track* const track = t.get();
3731
3732 // process fast tracks
3733 if (track->isFastTrack()) {
3734
3735 // It's theoretically possible (though unlikely) for a fast track to be created
3736 // and then removed within the same normal mix cycle. This is not a problem, as
3737 // the track never becomes active so it's fast mixer slot is never touched.
3738 // The converse, of removing an (active) track and then creating a new track
3739 // at the identical fast mixer slot within the same normal mix cycle,
3740 // is impossible because the slot isn't marked available until the end of each cycle.
3741 int j = track->mFastIndex;
3742 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
3743 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
3744 FastTrack *fastTrack = &state->mFastTracks[j];
3745
3746 // Determine whether the track is currently in underrun condition,
3747 // and whether it had a recent underrun.
3748 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
3749 FastTrackUnderruns underruns = ftDump->mUnderruns;
3750 uint32_t recentFull = (underruns.mBitFields.mFull -
3751 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
3752 uint32_t recentPartial = (underruns.mBitFields.mPartial -
3753 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
3754 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
3755 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
3756 uint32_t recentUnderruns = recentPartial + recentEmpty;
3757 track->mObservedUnderruns = underruns;
3758 // don't count underruns that occur while stopping or pausing
3759 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07003760 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
3761 recentUnderruns > 0) {
3762 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
3763 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Phil Burk2812d9e2016-01-04 10:34:30 -08003764 } else {
3765 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Eric Laurent81784c32012-11-19 14:55:58 -08003766 }
3767
3768 // This is similar to the state machine for normal tracks,
3769 // with a few modifications for fast tracks.
3770 bool isActive = true;
3771 switch (track->mState) {
3772 case TrackBase::STOPPING_1:
3773 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08003774 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003775 track->mState = TrackBase::STOPPING_2;
3776 }
3777 break;
3778 case TrackBase::PAUSING:
3779 // ramp down is not yet implemented
3780 track->setPaused();
3781 break;
3782 case TrackBase::RESUMING:
3783 // ramp up is not yet implemented
3784 track->mState = TrackBase::ACTIVE;
3785 break;
3786 case TrackBase::ACTIVE:
3787 if (recentFull > 0 || recentPartial > 0) {
3788 // track has provided at least some frames recently: reset retry count
3789 track->mRetryCount = kMaxTrackRetries;
3790 }
3791 if (recentUnderruns == 0) {
3792 // no recent underruns: stay active
3793 break;
3794 }
3795 // there has recently been an underrun of some kind
3796 if (track->sharedBuffer() == 0) {
3797 // were any of the recent underruns "empty" (no frames available)?
3798 if (recentEmpty == 0) {
3799 // no, then ignore the partial underruns as they are allowed indefinitely
3800 break;
3801 }
3802 // there has recently been an "empty" underrun: decrement the retry counter
3803 if (--(track->mRetryCount) > 0) {
3804 break;
3805 }
3806 // indicate to client process that the track was disabled because of underrun;
3807 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003808 android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003809 // remove from active list, but state remains ACTIVE [confusing but true]
3810 isActive = false;
3811 break;
3812 }
3813 // fall through
3814 case TrackBase::STOPPING_2:
3815 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003816 case TrackBase::STOPPED:
3817 case TrackBase::FLUSHED: // flush() while active
3818 // Check for presentation complete if track is inactive
3819 // We have consumed all the buffers of this track.
3820 // This would be incomplete if we auto-paused on underrun
3821 {
3822 size_t audioHALFrames =
3823 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3824 size_t framesWritten = mBytesWritten / mFrameSize;
3825 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
3826 // track stays in active list until presentation is complete
3827 break;
3828 }
3829 }
3830 if (track->isStopping_2()) {
3831 track->mState = TrackBase::STOPPED;
3832 }
3833 if (track->isStopped()) {
3834 // Can't reset directly, as fast mixer is still polling this track
3835 // track->reset();
3836 // So instead mark this track as needing to be reset after push with ack
3837 resetMask |= 1 << i;
3838 }
3839 isActive = false;
3840 break;
3841 case TrackBase::IDLE:
3842 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08003843 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08003844 }
3845
3846 if (isActive) {
3847 // was it previously inactive?
3848 if (!(state->mTrackMask & (1 << j))) {
3849 ExtendedAudioBufferProvider *eabp = track;
3850 VolumeProvider *vp = track;
3851 fastTrack->mBufferProvider = eabp;
3852 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08003853 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003854 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08003855 fastTrack->mGeneration++;
3856 state->mTrackMask |= 1 << j;
3857 didModify = true;
3858 // no acknowledgement required for newly active tracks
3859 }
3860 // cache the combined master volume and stream type volume for fast mixer; this
3861 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08003862 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08003863 ++fastTracks;
3864 } else {
3865 // was it previously active?
3866 if (state->mTrackMask & (1 << j)) {
3867 fastTrack->mBufferProvider = NULL;
3868 fastTrack->mGeneration++;
3869 state->mTrackMask &= ~(1 << j);
3870 didModify = true;
3871 // If any fast tracks were removed, we must wait for acknowledgement
3872 // because we're about to decrement the last sp<> on those tracks.
3873 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3874 } else {
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08003875 LOG_ALWAYS_FATAL("fast track %d should have been active; "
3876 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
3877 j, track->mState, state->mTrackMask, recentUnderruns,
3878 track->sharedBuffer() != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08003879 }
3880 tracksToRemove->add(track);
3881 // Avoids a misleading display in dumpsys
3882 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
3883 }
3884 continue;
3885 }
3886
3887 { // local variable scope to avoid goto warning
3888
3889 audio_track_cblk_t* cblk = track->cblk();
3890
3891 // The first time a track is added we wait
3892 // for all its buffers to be filled before processing it
3893 int name = track->name();
3894 // make sure that we have enough frames to mix one full buffer.
3895 // enforce this condition only once to enable draining the buffer in case the client
3896 // app does not call stop() and relies on underrun to stop:
3897 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
3898 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003899 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07003900 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07003901 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07003902
3903 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07003904 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07003905 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
3906 // add frames already consumed but not yet released by the resampler
3907 // because mAudioTrackServerProxy->framesReady() will include these frames
3908 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
3909
Eric Laurent81784c32012-11-19 14:55:58 -08003910 uint32_t minFrames = 1;
3911 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
3912 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003913 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08003914 }
Eric Laurent13e4c962013-12-20 17:36:01 -08003915
3916 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07003917 if (ATRACE_ENABLED()) {
3918 // I wish we had formatted trace names
3919 char traceName[16];
3920 strcpy(traceName, "nRdy");
3921 int name = track->name();
3922 if (AudioMixer::TRACK0 <= name &&
3923 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
3924 name -= AudioMixer::TRACK0;
3925 traceName[4] = (name / 10) + '0';
3926 traceName[5] = (name % 10) + '0';
3927 } else {
3928 traceName[4] = '?';
3929 traceName[5] = '?';
3930 }
3931 traceName[6] = '\0';
3932 ATRACE_INT(traceName, framesReady);
3933 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003934 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08003935 !track->isPaused() && !track->isTerminated())
3936 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003937 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003938
3939 mixedTracks++;
3940
Andy Hung69aed5f2014-02-25 17:24:40 -08003941 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
3942 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08003943 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08003944 if (track->mainBuffer() != mSinkBuffer &&
3945 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08003946 if (mEffectBufferEnabled) {
3947 mEffectBufferValid = true; // Later can set directly.
3948 }
Eric Laurent81784c32012-11-19 14:55:58 -08003949 chain = getEffectChain_l(track->sessionId());
3950 // Delegate volume control to effect in track effect chain if needed
3951 if (chain != 0) {
3952 tracksWithEffect++;
3953 } else {
3954 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
3955 "session %d",
3956 name, track->sessionId());
3957 }
3958 }
3959
3960
3961 int param = AudioMixer::VOLUME;
3962 if (track->mFillingUpStatus == Track::FS_FILLED) {
3963 // no ramp for the first volume setting
3964 track->mFillingUpStatus = Track::FS_ACTIVE;
3965 if (track->mState == TrackBase::RESUMING) {
3966 track->mState = TrackBase::ACTIVE;
3967 param = AudioMixer::RAMP_VOLUME;
3968 }
3969 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003970 // FIXME should not make a decision based on mServer
3971 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003972 // If the track is stopped before the first frame was mixed,
3973 // do not apply ramp
3974 param = AudioMixer::RAMP_VOLUME;
3975 }
3976
3977 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07003978 uint32_t vl, vr; // in U8.24 integer format
3979 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08003980 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07003981 vl = vr = 0;
3982 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08003983 if (track->isPausing()) {
3984 track->setPaused();
3985 }
3986 } else {
3987
3988 // read original volumes with volume control
3989 float typeVolume = mStreamTypes[track->streamType()].volume;
3990 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003991 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07003992 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07003993 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
3994 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08003995 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07003996 if (vlf > GAIN_FLOAT_UNITY) {
3997 ALOGV("Track left volume out of range: %.3g", vlf);
3998 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003999 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07004000 if (vrf > GAIN_FLOAT_UNITY) {
4001 ALOGV("Track right volume out of range: %.3g", vrf);
4002 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004003 }
4004 // now apply the master volume and stream type volume
Andy Hung6be49402014-05-30 10:42:03 -07004005 vlf *= v;
4006 vrf *= v;
Eric Laurent81784c32012-11-19 14:55:58 -08004007 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07004008 // then derive vl and vr as U8.24 versions for the effect chain
4009 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
4010 vl = (uint32_t) (scaleto8_24 * vlf);
4011 vr = (uint32_t) (scaleto8_24 * vrf);
4012 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08004013 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08004014 // send level comes from shared memory and so may be corrupt
4015 if (sendLevel > MAX_GAIN_INT) {
4016 ALOGV("Track send level out of range: %04X", sendLevel);
4017 sendLevel = MAX_GAIN_INT;
4018 }
Andy Hung6be49402014-05-30 10:42:03 -07004019 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
4020 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08004021 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004022
Eric Laurent81784c32012-11-19 14:55:58 -08004023 // Delegate volume control to effect in track effect chain if needed
4024 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
4025 // Do not ramp volume if volume is controlled by effect
4026 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08004027 // Update remaining floating point volume levels
4028 vlf = (float)vl / (1 << 24);
4029 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08004030 track->mHasVolumeController = true;
4031 } else {
4032 // force no volume ramp when volume controller was just disabled or removed
4033 // from effect chain to avoid volume spike
4034 if (track->mHasVolumeController) {
4035 param = AudioMixer::VOLUME;
4036 }
4037 track->mHasVolumeController = false;
4038 }
4039
Eric Laurent81784c32012-11-19 14:55:58 -08004040 // XXX: these things DON'T need to be done each time
4041 mAudioMixer->setBufferProvider(name, track);
4042 mAudioMixer->enable(name);
4043
Andy Hung6be49402014-05-30 10:42:03 -07004044 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
4045 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
4046 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08004047 mAudioMixer->setParameter(
4048 name,
4049 AudioMixer::TRACK,
4050 AudioMixer::FORMAT, (void *)track->format());
4051 mAudioMixer->setParameter(
4052 name,
4053 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004054 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07004055 mAudioMixer->setParameter(
4056 name,
4057 AudioMixer::TRACK,
4058 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08004059 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07004060 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004061 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08004062 if (reqSampleRate == 0) {
4063 reqSampleRate = mSampleRate;
4064 } else if (reqSampleRate > maxSampleRate) {
4065 reqSampleRate = maxSampleRate;
4066 }
Eric Laurent81784c32012-11-19 14:55:58 -08004067 mAudioMixer->setParameter(
4068 name,
4069 AudioMixer::RESAMPLE,
4070 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004071 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004072
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004073 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004074 mAudioMixer->setParameter(
4075 name,
4076 AudioMixer::TIMESTRETCH,
4077 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004078 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004079
Andy Hung69aed5f2014-02-25 17:24:40 -08004080 /*
4081 * Select the appropriate output buffer for the track.
4082 *
Andy Hung98ef9782014-03-04 14:46:50 -08004083 * Tracks with effects go into their own effects chain buffer
4084 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08004085 *
4086 * Other tracks can use mMixerBuffer for higher precision
4087 * channel accumulation. If this buffer is enabled
4088 * (mMixerBufferEnabled true), then selected tracks will accumulate
4089 * into it.
4090 *
4091 */
4092 if (mMixerBufferEnabled
4093 && (track->mainBuffer() == mSinkBuffer
4094 || track->mainBuffer() == mMixerBuffer)) {
4095 mAudioMixer->setParameter(
4096 name,
4097 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004098 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08004099 mAudioMixer->setParameter(
4100 name,
4101 AudioMixer::TRACK,
4102 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
4103 // TODO: override track->mainBuffer()?
4104 mMixerBufferValid = true;
4105 } else {
4106 mAudioMixer->setParameter(
4107 name,
4108 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004109 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08004110 mAudioMixer->setParameter(
4111 name,
4112 AudioMixer::TRACK,
4113 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
4114 }
Eric Laurent81784c32012-11-19 14:55:58 -08004115 mAudioMixer->setParameter(
4116 name,
4117 AudioMixer::TRACK,
4118 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
4119
4120 // reset retry count
4121 track->mRetryCount = kMaxTrackRetries;
4122
4123 // If one track is ready, set the mixer ready if:
4124 // - the mixer was not ready during previous round OR
4125 // - no other track is not ready
4126 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
4127 mixerStatus != MIXER_TRACKS_ENABLED) {
4128 mixerStatus = MIXER_TRACKS_READY;
4129 }
4130 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004131 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hung08fb1742015-05-31 23:22:10 -07004132 ALOGV("track(%p) underrun, framesReady(%zu) < framesDesired(%zd)",
4133 track, framesReady, desiredFrames);
Glenn Kasten82aaf942013-07-17 16:05:07 -07004134 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08004135 } else {
4136 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004137 }
Phil Burk2812d9e2016-01-04 10:34:30 -08004138
Eric Laurent81784c32012-11-19 14:55:58 -08004139 // clear effect chain input buffer if an active track underruns to avoid sending
4140 // previous audio buffer again to effects
4141 chain = getEffectChain_l(track->sessionId());
4142 if (chain != 0) {
4143 chain->clearInputBuffer();
4144 }
4145
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004146 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004147 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
4148 track->isStopped() || track->isPaused()) {
4149 // We have consumed all the buffers of this track.
4150 // Remove it from the list of active tracks.
4151 // TODO: use actual buffer filling status instead of latency when available from
4152 // audio HAL
4153 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
4154 size_t framesWritten = mBytesWritten / mFrameSize;
4155 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
4156 if (track->isStopped()) {
4157 track->reset();
4158 }
4159 tracksToRemove->add(track);
4160 }
4161 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08004162 // No buffers for this track. Give it a few chances to
4163 // fill a buffer, then remove it from active list.
4164 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004165 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004166 tracksToRemove->add(track);
4167 // indicate to client process that the track was disabled because of underrun;
4168 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07004169 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08004170 // If one track is not ready, mark the mixer also not ready if:
4171 // - the mixer was ready during previous round OR
4172 // - no other track is ready
4173 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
4174 mixerStatus != MIXER_TRACKS_READY) {
4175 mixerStatus = MIXER_TRACKS_ENABLED;
4176 }
4177 }
4178 mAudioMixer->disable(name);
4179 }
4180
4181 } // local variable scope to avoid goto warning
4182track_is_ready: ;
4183
4184 }
4185
4186 // Push the new FastMixer state if necessary
4187 bool pauseAudioWatchdog = false;
4188 if (didModify) {
4189 state->mFastTracksGen++;
4190 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4191 if (kUseFastMixer == FastMixer_Dynamic &&
4192 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4193 state->mCommand = FastMixerState::COLD_IDLE;
4194 state->mColdFutexAddr = &mFastMixerFutex;
4195 state->mColdGen++;
4196 mFastMixerFutex = 0;
4197 if (kUseFastMixer == FastMixer_Dynamic) {
4198 mNormalSink = mOutputSink;
4199 }
4200 // If we go into cold idle, need to wait for acknowledgement
4201 // so that fast mixer stops doing I/O.
4202 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4203 pauseAudioWatchdog = true;
4204 }
Eric Laurent81784c32012-11-19 14:55:58 -08004205 }
4206 if (sq != NULL) {
4207 sq->end(didModify);
4208 sq->push(block);
4209 }
4210#ifdef AUDIO_WATCHDOG
4211 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4212 mAudioWatchdog->pause();
4213 }
4214#endif
4215
4216 // Now perform the deferred reset on fast tracks that have stopped
4217 while (resetMask != 0) {
4218 size_t i = __builtin_ctz(resetMask);
4219 ALOG_ASSERT(i < count);
4220 resetMask &= ~(1 << i);
4221 sp<Track> t = mActiveTracks[i].promote();
4222 if (t == 0) {
4223 continue;
4224 }
4225 Track* track = t.get();
4226 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
4227 track->reset();
4228 }
4229
4230 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004231 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004232
Eric Laurent97d547d2014-09-02 14:45:53 -07004233 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
4234 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07004235 }
4236
4237 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07004238 // as long as there are effects we should clear the effects buffer, to avoid
4239 // passing a non-clean buffer to the effect chain
4240 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07004241 }
Andy Hung69aed5f2014-02-25 17:24:40 -08004242 // sink or mix buffer must be cleared if all tracks are connected to an
4243 // effect chain as in this case the mixer will not write to the sink or mix buffer
4244 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08004245 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4246 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08004247 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08004248 if (mMixerBufferValid) {
4249 memset(mMixerBuffer, 0, mMixerBufferSize);
4250 // TODO: In testing, mSinkBuffer below need not be cleared because
4251 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
4252 // after mixing.
4253 //
4254 // To enforce this guarantee:
4255 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4256 // (mixedTracks == 0 && fastTracks > 0))
4257 // must imply MIXER_TRACKS_READY.
4258 // Later, we may clear buffers regardless, and skip much of this logic.
4259 }
Andy Hung98ef9782014-03-04 14:46:50 -08004260 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07004261 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004262 }
4263
4264 // if any fast tracks, then status is ready
4265 mMixerStatusIgnoringFastTracks = mixerStatus;
4266 if (fastTracks > 0) {
4267 mixerStatus = MIXER_TRACKS_READY;
4268 }
4269 return mixerStatus;
4270}
4271
4272// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07004273int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
4274 audio_format_t format, int sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08004275{
Andy Hunge8a1ced2014-05-09 15:02:21 -07004276 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08004277}
4278
4279// deleteTrackName_l() must be called with ThreadBase::mLock held
4280void AudioFlinger::MixerThread::deleteTrackName_l(int name)
4281{
4282 ALOGV("remove track (%d) and delete from mixer", name);
4283 mAudioMixer->deleteTrackName(name);
4284}
4285
Eric Laurent10351942014-05-08 18:49:52 -07004286// checkForNewParameter_l() must be called with ThreadBase::mLock held
4287bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
4288 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004289{
Eric Laurent81784c32012-11-19 14:55:58 -08004290 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08004291 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004292
Eric Laurent10351942014-05-08 18:49:52 -07004293 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004294
Eric Laurent10351942014-05-08 18:49:52 -07004295 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
4296 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004297 if (mFastMixer != 0) {
Eric Laurent10351942014-05-08 18:49:52 -07004298 FastMixerStateQueue *sq = mFastMixer->sq();
4299 FastMixerState *state = sq->begin();
4300 if (!(state->mCommand & FastMixerState::IDLE)) {
4301 previousCommand = state->mCommand;
4302 state->mCommand = FastMixerState::HOT_IDLE;
4303 sq->end();
4304 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
4305 } else {
4306 sq->end(false /*didModify*/);
Eric Laurent81784c32012-11-19 14:55:58 -08004307 }
Eric Laurent10351942014-05-08 18:49:52 -07004308 }
Eric Laurent81784c32012-11-19 14:55:58 -08004309
Eric Laurent10351942014-05-08 18:49:52 -07004310 AudioParameter param = AudioParameter(keyValuePair);
4311 int value;
4312 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4313 reconfig = true;
4314 }
4315 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004316 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004317 status = BAD_VALUE;
4318 } else {
4319 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08004320 reconfig = true;
4321 }
Eric Laurent10351942014-05-08 18:49:52 -07004322 }
4323 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004324 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004325 status = BAD_VALUE;
4326 } else {
4327 // no need to save value, since it's constant
4328 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004329 }
Eric Laurent10351942014-05-08 18:49:52 -07004330 }
4331 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4332 // do not accept frame count changes if tracks are open as the track buffer
4333 // size depends on frame count and correct behavior would not be guaranteed
4334 // if frame count is changed after track creation
4335 if (!mTracks.isEmpty()) {
4336 status = INVALID_OPERATION;
4337 } else {
4338 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004339 }
Eric Laurent10351942014-05-08 18:49:52 -07004340 }
4341 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004342#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07004343 // when changing the audio output device, call addBatteryData to notify
4344 // the change
4345 if (mOutDevice != value) {
4346 uint32_t params = 0;
4347 // check whether speaker is on
4348 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
4349 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08004350 }
Eric Laurent10351942014-05-08 18:49:52 -07004351
4352 audio_devices_t deviceWithoutSpeaker
4353 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
4354 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07004355 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07004356 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4357 }
4358
4359 if (params != 0) {
4360 addBatteryData(params);
4361 }
4362 }
Eric Laurent81784c32012-11-19 14:55:58 -08004363#endif
4364
Eric Laurent10351942014-05-08 18:49:52 -07004365 // forward device change to effects that have requested to be
4366 // aware of attached audio device.
4367 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08004368 a2dpDeviceChanged =
4369 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07004370 mOutDevice = value;
4371 for (size_t i = 0; i < mEffectChains.size(); i++) {
4372 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08004373 }
4374 }
Eric Laurent10351942014-05-08 18:49:52 -07004375 }
Eric Laurent81784c32012-11-19 14:55:58 -08004376
Eric Laurent10351942014-05-08 18:49:52 -07004377 if (status == NO_ERROR) {
4378 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4379 keyValuePair.string());
4380 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004381 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004382 mStandby = true;
4383 mBytesWritten = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004384 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Eric Laurent10351942014-05-08 18:49:52 -07004385 keyValuePair.string());
Eric Laurent81784c32012-11-19 14:55:58 -08004386 }
Eric Laurent10351942014-05-08 18:49:52 -07004387 if (status == NO_ERROR && reconfig) {
4388 readOutputParameters_l();
4389 delete mAudioMixer;
4390 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4391 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07004392 int name = getTrackName_l(mTracks[i]->mChannelMask,
4393 mTracks[i]->mFormat, mTracks[i]->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07004394 if (name < 0) {
4395 break;
4396 }
4397 mTracks[i]->mName = name;
4398 }
Eric Laurent73e26b62015-04-27 16:55:58 -07004399 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004400 }
Eric Laurent81784c32012-11-19 14:55:58 -08004401 }
4402
4403 if (!(previousCommand & FastMixerState::IDLE)) {
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004404 ALOG_ASSERT(mFastMixer != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08004405 FastMixerStateQueue *sq = mFastMixer->sq();
4406 FastMixerState *state = sq->begin();
4407 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
4408 state->mCommand = previousCommand;
4409 sq->end();
4410 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4411 }
4412
Eric Laurent42537be2016-01-08 17:16:42 -08004413 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08004414}
4415
4416
4417void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
4418{
4419 const size_t SIZE = 256;
4420 char buffer[SIZE];
4421 String8 result;
4422
4423 PlaybackThread::dumpInternals(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07004424 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Elliott Hughes87cebad2014-05-22 10:14:43 -07004425 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Andy Hung2ddee192015-12-18 17:34:44 -08004426 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Eric Laurent81784c32012-11-19 14:55:58 -08004427
4428 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten2f90c512015-12-02 11:40:09 -08004429 // while we are dumping it. It may be inconsistent, but it won't mutate!
4430 // This is a large object so we place it on the heap.
4431 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
4432 const FastMixerDumpState *copy = new FastMixerDumpState(mFastMixerDumpState);
4433 copy->dump(fd);
4434 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08004435
4436#ifdef STATE_QUEUE_DUMP
4437 // Similar for state queue
4438 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4439 observerCopy.dump(fd);
4440 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4441 mutatorCopy.dump(fd);
4442#endif
4443
Glenn Kasten46909e72013-02-26 09:20:22 -08004444#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08004445 // Write the tee output to a .wav file
4446 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08004447#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004448
4449#ifdef AUDIO_WATCHDOG
4450 if (mAudioWatchdog != 0) {
4451 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4452 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4453 wdCopy.dump(fd);
4454 }
4455#endif
4456}
4457
4458uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4459{
4460 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4461}
4462
4463uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4464{
4465 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4466}
4467
4468void AudioFlinger::MixerThread::cacheParameters_l()
4469{
4470 PlaybackThread::cacheParameters_l();
4471
4472 // FIXME: Relaxed timing because of a certain device that can't meet latency
4473 // Should be reduced to 2x after the vendor fixes the driver issue
4474 // increase threshold again due to low power audio mode. The way this warning
4475 // threshold is calculated and its usefulness should be reconsidered anyway.
4476 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4477}
4478
4479// ----------------------------------------------------------------------------
4480
4481AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07004482 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device, bool systemReady)
4483 : PlaybackThread(audioFlinger, output, id, device, DIRECT, systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08004484 // mLeftVolFloat, mRightVolFloat
4485{
4486}
4487
Eric Laurentbfb1b832013-01-07 09:53:42 -08004488AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4489 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07004490 ThreadBase::type_t type, bool systemReady)
4491 : PlaybackThread(audioFlinger, output, id, device, type, systemReady)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004492 // mLeftVolFloat, mRightVolFloat
4493{
4494}
4495
Eric Laurent81784c32012-11-19 14:55:58 -08004496AudioFlinger::DirectOutputThread::~DirectOutputThread()
4497{
4498}
4499
Eric Laurentbfb1b832013-01-07 09:53:42 -08004500void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
4501{
4502 audio_track_cblk_t* cblk = track->cblk();
4503 float left, right;
4504
4505 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4506 left = right = 0;
4507 } else {
4508 float typeVolume = mStreamTypes[track->streamType()].volume;
4509 float v = mMasterVolume * typeVolume;
4510 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004511 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4512 left = float_from_gain(gain_minifloat_unpack_left(vlr));
4513 if (left > GAIN_FLOAT_UNITY) {
4514 left = GAIN_FLOAT_UNITY;
4515 }
4516 left *= v;
4517 right = float_from_gain(gain_minifloat_unpack_right(vlr));
4518 if (right > GAIN_FLOAT_UNITY) {
4519 right = GAIN_FLOAT_UNITY;
4520 }
4521 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004522 }
4523
4524 if (lastTrack) {
4525 if (left != mLeftVolFloat || right != mRightVolFloat) {
4526 mLeftVolFloat = left;
4527 mRightVolFloat = right;
4528
4529 // Convert volumes from float to 8.24
4530 uint32_t vl = (uint32_t)(left * (1 << 24));
4531 uint32_t vr = (uint32_t)(right * (1 << 24));
4532
4533 // Delegate volume control to effect in track effect chain if needed
4534 // only one effect chain can be present on DirectOutputThread, so if
4535 // there is one, the track is connected to it
4536 if (!mEffectChains.isEmpty()) {
4537 mEffectChains[0]->setVolume_l(&vl, &vr);
4538 left = (float)vl / (1 << 24);
4539 right = (float)vr / (1 << 24);
4540 }
4541 if (mOutput->stream->set_volume) {
4542 mOutput->stream->set_volume(mOutput->stream, left, right);
4543 }
4544 }
4545 }
4546}
4547
Phil Burk43b4dcc2015-06-09 16:53:44 -07004548void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
4549{
4550 sp<Track> previousTrack = mPreviousTrack.promote();
4551 sp<Track> latestTrack = mLatestActiveTrack.promote();
4552
Eric Laurent0f0631e2015-07-06 18:01:25 -07004553 if (previousTrack != 0 && latestTrack != 0) {
4554 if (mType == DIRECT) {
4555 if (previousTrack.get() != latestTrack.get()) {
4556 mFlushPending = true;
4557 }
4558 } else /* mType == OFFLOAD */ {
4559 if (previousTrack->sessionId() != latestTrack->sessionId()) {
4560 mFlushPending = true;
4561 }
4562 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004563 }
4564 PlaybackThread::onAddNewTrack_l();
4565}
Eric Laurentbfb1b832013-01-07 09:53:42 -08004566
Eric Laurent81784c32012-11-19 14:55:58 -08004567AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4568 Vector< sp<Track> > *tracksToRemove
4569)
4570{
Eric Laurentd595b7c2013-04-03 17:27:56 -07004571 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08004572 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004573 bool doHwPause = false;
4574 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004575
4576 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07004577 for (size_t i = 0; i < count; i++) {
4578 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08004579 // The track died recently
4580 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004581 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08004582 }
4583
Phil Burk43b4dcc2015-06-09 16:53:44 -07004584 if (t->isInvalid()) {
4585 ALOGW("An invalidated track shouldn't be in active list");
4586 tracksToRemove->add(t);
4587 continue;
4588 }
4589
Eric Laurent81784c32012-11-19 14:55:58 -08004590 Track* const track = t.get();
4591 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07004592 // Only consider last track started for volume and mixer state control.
4593 // In theory an older track could underrun and restart after the new one starts
4594 // but as we only care about the transition phase between two tracks on a
4595 // direct output, it is not a problem to ignore the underrun case.
4596 sp<Track> l = mLatestActiveTrack.promote();
4597 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08004598
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004599 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004600 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004601 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004602 doHwPause = true;
4603 mHwPaused = true;
4604 }
4605 tracksToRemove->add(track);
4606 } else if (track->isFlushPending()) {
4607 track->flushAck();
4608 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004609 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004610 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004611 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004612 track->resumeAck();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004613 if (last && mHwPaused) {
4614 doHwResume = true;
4615 mHwPaused = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004616 }
4617 }
4618
Eric Laurent81784c32012-11-19 14:55:58 -08004619 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08004620 // for all its buffers to be filled before processing it.
4621 // Allow draining the buffer in case the client
4622 // app does not call stop() and relies on underrun to stop:
4623 // hence the test on (track->mRetryCount > 1).
4624 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07004625 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08004626 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08004627 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkca5e6142015-07-14 09:42:29 -07004628 && (track->mRetryCount > 1) && audio_is_linear_pcm(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004629 minFrames = mNormalFrameCount;
4630 } else {
4631 minFrames = 1;
4632 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004633
Eric Laurentab5cdba2014-06-09 17:22:27 -07004634 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4635 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08004636 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004637 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08004638
4639 if (track->mFillingUpStatus == Track::FS_FILLED) {
4640 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004641 // make sure processVolume_l() will apply new volume even if 0
4642 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004643 if (!mHwSupportsPause) {
4644 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08004645 }
4646 }
4647
4648 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004649 processVolume_l(track, last);
4650 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004651 sp<Track> previousTrack = mPreviousTrack.promote();
4652 if (previousTrack != 0) {
4653 if (track != previousTrack.get()) {
4654 // Flush any data still being written from last track
4655 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07004656 // Invalidate previous track to force a seek when resuming.
4657 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004658 }
4659 }
4660 mPreviousTrack = track;
4661
Eric Laurentd595b7c2013-04-03 17:27:56 -07004662 // reset retry count
4663 track->mRetryCount = kMaxTrackRetriesDirect;
4664 mActiveTrack = t;
4665 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07004666 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004667 doHwResume = true;
4668 mHwPaused = false;
4669 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004670 }
Eric Laurent81784c32012-11-19 14:55:58 -08004671 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004672 // clear effect chain input buffer if the last active track started underruns
4673 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07004674 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004675 mEffectChains[0]->clearInputBuffer();
4676 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004677 if (track->isStopping_1()) {
4678 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07004679 if (last && mHwPaused) {
4680 doHwResume = true;
4681 mHwPaused = false;
4682 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004683 }
4684 if ((track->sharedBuffer() != 0) || track->isStopped() ||
4685 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004686 // We have consumed all the buffers of this track.
4687 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07004688 size_t audioHALFrames;
4689 if (audio_is_linear_pcm(mFormat)) {
4690 audioHALFrames = (latency_l() * mSampleRate) / 1000;
4691 } else {
4692 audioHALFrames = 0;
4693 }
4694
Eric Laurent81784c32012-11-19 14:55:58 -08004695 size_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07004696 if (mStandby || !last ||
4697 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004698 if (track->isStopping_2()) {
4699 track->mState = TrackBase::STOPPED;
4700 }
Eric Laurent81784c32012-11-19 14:55:58 -08004701 if (track->isStopped()) {
4702 track->reset();
4703 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004704 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08004705 }
4706 } else {
4707 // No buffers for this track. Give it a few chances to
4708 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07004709 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08004710 if (--(track->mRetryCount) <= 0) {
4711 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07004712 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004713 // indicate to client process that the track was disabled because of underrun;
4714 // it will then automatically call start() when data is available
4715 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004716 } else if (last) {
Phil Burkca5e6142015-07-14 09:42:29 -07004717 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
4718 "minFrames = %u, mFormat = %#x",
4719 track->framesReady(), minFrames, mFormat);
Eric Laurent81784c32012-11-19 14:55:58 -08004720 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07004721 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004722 doHwPause = true;
4723 mHwPaused = true;
4724 }
Eric Laurent81784c32012-11-19 14:55:58 -08004725 }
4726 }
4727 }
4728 }
4729
Eric Laurentd1f69b02014-12-15 14:33:13 -08004730 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07004731 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004732 for (size_t i = 0; i < mTracks.size(); i++) {
4733 if (mTracks[i]->isFlushPending()) {
4734 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004735 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004736 }
4737 }
4738 }
4739
4740 // make sure the pause/flush/resume sequence is executed in the right order.
4741 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4742 // before flush and then resume HW. This can happen in case of pause/flush/resume
4743 // if resume is received before pause is executed.
4744 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07004745 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004746 mOutput->stream->pause(mOutput->stream);
4747 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004748 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004749 flushHw_l();
4750 }
4751 if (mHwSupportsPause && !mStandby && doHwResume) {
4752 mOutput->stream->resume(mOutput->stream);
4753 }
Eric Laurent81784c32012-11-19 14:55:58 -08004754 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004755 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004756
4757 return mixerStatus;
4758}
4759
4760void AudioFlinger::DirectOutputThread::threadLoop_mix()
4761{
Eric Laurent81784c32012-11-19 14:55:58 -08004762 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08004763 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004764 // output audio to hardware
4765 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07004766 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004767 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08004768 status_t status = mActiveTrack->getNextBuffer(&buffer);
4769 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08004770 memset(curBuf, 0, frameCount * mFrameSize);
4771 break;
4772 }
4773 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
4774 frameCount -= buffer.frameCount;
4775 curBuf += buffer.frameCount * mFrameSize;
4776 mActiveTrack->releaseBuffer(&buffer);
4777 }
Andy Hung2098f272014-02-27 14:00:06 -08004778 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004779 mSleepTimeUs = 0;
4780 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08004781 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004782}
4783
4784void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
4785{
Eric Laurentd1f69b02014-12-15 14:33:13 -08004786 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004787 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004788 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004789 return;
4790 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004791 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004792 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004793 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004794 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004795 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004796 }
4797 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08004798 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004799 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004800 }
4801}
4802
Eric Laurentd1f69b02014-12-15 14:33:13 -08004803void AudioFlinger::DirectOutputThread::threadLoop_exit()
4804{
4805 {
4806 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08004807 for (size_t i = 0; i < mTracks.size(); i++) {
4808 if (mTracks[i]->isFlushPending()) {
4809 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004810 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004811 }
4812 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004813 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004814 flushHw_l();
4815 }
4816 }
4817 PlaybackThread::threadLoop_exit();
4818}
4819
4820// must be called with thread mutex locked
4821bool AudioFlinger::DirectOutputThread::shouldStandby_l()
4822{
4823 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07004824 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004825
4826 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4827 // after a timeout and we will enter standby then.
4828 if (mTracks.size() > 0) {
4829 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07004830 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
4831 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004832 }
4833
Eric Laurent5cff4032015-05-26 13:49:58 -07004834 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08004835}
4836
Eric Laurent81784c32012-11-19 14:55:58 -08004837// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004838int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Andy Hunge8a1ced2014-05-09 15:02:21 -07004839 audio_format_t format __unused, int sessionId __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004840{
4841 return 0;
4842}
4843
4844// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004845void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004846{
4847}
4848
Eric Laurent10351942014-05-08 18:49:52 -07004849// checkForNewParameter_l() must be called with ThreadBase::mLock held
4850bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
4851 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004852{
4853 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08004854 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004855
Eric Laurent10351942014-05-08 18:49:52 -07004856 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004857
Eric Laurent10351942014-05-08 18:49:52 -07004858 AudioParameter param = AudioParameter(keyValuePair);
4859 int value;
4860 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4861 // forward device change to effects that have requested to be
4862 // aware of attached audio device.
4863 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08004864 a2dpDeviceChanged =
4865 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07004866 mOutDevice = value;
4867 for (size_t i = 0; i < mEffectChains.size(); i++) {
4868 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07004869 }
4870 }
Eric Laurent81784c32012-11-19 14:55:58 -08004871 }
Eric Laurent10351942014-05-08 18:49:52 -07004872 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4873 // do not accept frame count changes if tracks are open as the track buffer
4874 // size depends on frame count and correct behavior would not be garantied
4875 // if frame count is changed after track creation
4876 if (!mTracks.isEmpty()) {
4877 status = INVALID_OPERATION;
4878 } else {
4879 reconfig = true;
4880 }
4881 }
4882 if (status == NO_ERROR) {
4883 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4884 keyValuePair.string());
4885 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004886 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004887 mStandby = true;
4888 mBytesWritten = 0;
4889 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4890 keyValuePair.string());
4891 }
4892 if (status == NO_ERROR && reconfig) {
4893 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07004894 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004895 }
4896 }
4897
Eric Laurent42537be2016-01-08 17:16:42 -08004898 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08004899}
4900
4901uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
4902{
4903 uint32_t time;
4904 if (audio_is_linear_pcm(mFormat)) {
4905 time = PlaybackThread::activeSleepTimeUs();
4906 } else {
4907 time = 10000;
4908 }
4909 return time;
4910}
4911
4912uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
4913{
4914 uint32_t time;
4915 if (audio_is_linear_pcm(mFormat)) {
4916 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
4917 } else {
4918 time = 10000;
4919 }
4920 return time;
4921}
4922
4923uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
4924{
4925 uint32_t time;
4926 if (audio_is_linear_pcm(mFormat)) {
4927 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
4928 } else {
4929 time = 10000;
4930 }
4931 return time;
4932}
4933
4934void AudioFlinger::DirectOutputThread::cacheParameters_l()
4935{
4936 PlaybackThread::cacheParameters_l();
4937
4938 // use shorter standby delay as on normal output to release
4939 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07004940 // no delay on outputs with HW A/V sync
4941 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004942 mStandbyDelayNs = 0;
Eric Laurent5cff4032015-05-26 13:49:58 -07004943 } else if ((mType == OFFLOAD) && !audio_is_linear_pcm(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004944 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07004945 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004946 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07004947 }
Eric Laurent81784c32012-11-19 14:55:58 -08004948}
4949
Eric Laurente659ef42014-09-29 13:06:46 -07004950void AudioFlinger::DirectOutputThread::flushHw_l()
4951{
Phil Burk062e67a2015-02-11 13:40:50 -08004952 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08004953 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07004954 mFlushPending = false;
Eric Laurente659ef42014-09-29 13:06:46 -07004955}
4956
Eric Laurent81784c32012-11-19 14:55:58 -08004957// ----------------------------------------------------------------------------
4958
Eric Laurentbfb1b832013-01-07 09:53:42 -08004959AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07004960 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004961 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07004962 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07004963 mWriteAckSequence(0),
4964 mDrainSequence(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004965{
4966}
4967
4968AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
4969{
4970}
4971
4972void AudioFlinger::AsyncCallbackThread::onFirstRef()
4973{
4974 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
4975}
4976
4977bool AudioFlinger::AsyncCallbackThread::threadLoop()
4978{
4979 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004980 uint32_t writeAckSequence;
4981 uint32_t drainSequence;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004982
4983 {
4984 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08004985 while (!((mWriteAckSequence & 1) ||
4986 (mDrainSequence & 1) ||
4987 exitPending())) {
4988 mWaitWorkCV.wait(mLock);
4989 }
4990
Eric Laurentbfb1b832013-01-07 09:53:42 -08004991 if (exitPending()) {
4992 break;
4993 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004994 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
4995 mWriteAckSequence, mDrainSequence);
4996 writeAckSequence = mWriteAckSequence;
4997 mWriteAckSequence &= ~1;
4998 drainSequence = mDrainSequence;
4999 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005000 }
5001 {
Eric Laurent4de95592013-09-26 15:28:21 -07005002 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
5003 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005004 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005005 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005006 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005007 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005008 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005009 }
5010 }
5011 }
5012 }
5013 return false;
5014}
5015
5016void AudioFlinger::AsyncCallbackThread::exit()
5017{
5018 ALOGV("AsyncCallbackThread::exit");
5019 Mutex::Autolock _l(mLock);
5020 requestExit();
5021 mWaitWorkCV.broadcast();
5022}
5023
Eric Laurent3b4529e2013-09-05 18:09:19 -07005024void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005025{
5026 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005027 // bit 0 is cleared
5028 mWriteAckSequence = sequence << 1;
5029}
5030
5031void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
5032{
5033 Mutex::Autolock _l(mLock);
5034 // ignore unexpected callbacks
5035 if (mWriteAckSequence & 2) {
5036 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005037 mWaitWorkCV.signal();
5038 }
5039}
5040
Eric Laurent3b4529e2013-09-05 18:09:19 -07005041void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005042{
5043 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005044 // bit 0 is cleared
5045 mDrainSequence = sequence << 1;
5046}
5047
5048void AudioFlinger::AsyncCallbackThread::resetDraining()
5049{
5050 Mutex::Autolock _l(mLock);
5051 // ignore unexpected callbacks
5052 if (mDrainSequence & 2) {
5053 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005054 mWaitWorkCV.signal();
5055 }
5056}
5057
5058
5059// ----------------------------------------------------------------------------
5060AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07005061 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady)
5062 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady),
Eric Laurentd7e59222013-11-15 12:02:28 -08005063 mPausedBytesRemaining(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005064{
Eric Laurentfd477972013-10-25 18:10:40 -07005065 //FIXME: mStandby should be set to true by ThreadBase constructor
5066 mStandby = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005067}
5068
Eric Laurentbfb1b832013-01-07 09:53:42 -08005069void AudioFlinger::OffloadThread::threadLoop_exit()
5070{
5071 if (mFlushPending || mHwPaused) {
5072 // If a flush is pending or track was paused, just discard buffered data
5073 flushHw_l();
5074 } else {
5075 mMixerStatus = MIXER_DRAIN_ALL;
5076 threadLoop_drain();
5077 }
Uday Gupta56604aa2014-05-13 11:19:17 -07005078 if (mUseAsyncWrite) {
5079 ALOG_ASSERT(mCallbackThread != 0);
5080 mCallbackThread->exit();
5081 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005082 PlaybackThread::threadLoop_exit();
5083}
5084
5085AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
5086 Vector< sp<Track> > *tracksToRemove
5087)
5088{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005089 size_t count = mActiveTracks.size();
5090
5091 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07005092 bool doHwPause = false;
5093 bool doHwResume = false;
5094
Eric Laurentede6c3b2013-09-19 14:37:46 -07005095 ALOGV("OffloadThread::prepareTracks_l active tracks %d", count);
5096
Eric Laurentbfb1b832013-01-07 09:53:42 -08005097 // find out which tracks need to be processed
5098 for (size_t i = 0; i < count; i++) {
5099 sp<Track> t = mActiveTracks[i].promote();
5100 // The track died recently
5101 if (t == 0) {
5102 continue;
5103 }
5104 Track* const track = t.get();
5105 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07005106 // Only consider last track started for volume and mixer state control.
5107 // In theory an older track could underrun and restart after the new one starts
5108 // but as we only care about the transition phase between two tracks on a
5109 // direct output, it is not a problem to ignore the underrun case.
5110 sp<Track> l = mLatestActiveTrack.promote();
5111 bool last = l.get() == track;
5112
Haynes Mathew George7844f672014-01-15 12:32:55 -08005113 if (track->isInvalid()) {
5114 ALOGW("An invalidated track shouldn't be in active list");
5115 tracksToRemove->add(track);
5116 continue;
5117 }
5118
5119 if (track->mState == TrackBase::IDLE) {
5120 ALOGW("An idle track shouldn't be in active list");
5121 continue;
5122 }
5123
Eric Laurentbfb1b832013-01-07 09:53:42 -08005124 if (track->isPausing()) {
5125 track->setPaused();
5126 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07005127 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07005128 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005129 mHwPaused = true;
5130 }
5131 // If we were part way through writing the mixbuffer to
5132 // the HAL we must save this until we resume
5133 // BUG - this will be wrong if a different track is made active,
5134 // in that case we want to discard the pending data in the
5135 // mixbuffer and tell the client to present it again when the
5136 // track is resumed
5137 mPausedWriteLength = mCurrentWriteLength;
5138 mPausedBytesRemaining = mBytesRemaining;
5139 mBytesRemaining = 0; // stop writing
5140 }
5141 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08005142 } else if (track->isFlushPending()) {
5143 track->flushAck();
5144 if (last) {
5145 mFlushPending = true;
5146 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005147 } else if (track->isResumePending()){
5148 track->resumeAck();
5149 if (last) {
5150 if (mPausedBytesRemaining) {
5151 // Need to continue write that was interrupted
5152 mCurrentWriteLength = mPausedWriteLength;
5153 mBytesRemaining = mPausedBytesRemaining;
5154 mPausedBytesRemaining = 0;
5155 }
5156 if (mHwPaused) {
5157 doHwResume = true;
5158 mHwPaused = false;
5159 // threadLoop_mix() will handle the case that we need to
5160 // resume an interrupted write
5161 }
5162 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005163 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005164
5165 // Do not handle new data in this iteration even if track->framesReady()
5166 mixerStatus = MIXER_TRACKS_ENABLED;
5167 }
5168 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07005169 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005170 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005171 if (track->mFillingUpStatus == Track::FS_FILLED) {
5172 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07005173 // make sure processVolume_l() will apply new volume even if 0
5174 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005175 }
5176
5177 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08005178 sp<Track> previousTrack = mPreviousTrack.promote();
5179 if (previousTrack != 0) {
5180 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08005181 // Flush any data still being written from last track
5182 mBytesRemaining = 0;
5183 if (mPausedBytesRemaining) {
5184 // Last track was paused so we also need to flush saved
5185 // mixbuffer state and invalidate track so that it will
5186 // re-submit that unwritten data when it is next resumed
5187 mPausedBytesRemaining = 0;
5188 // Invalidate is a bit drastic - would be more efficient
5189 // to have a flag to tell client that some of the
5190 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08005191 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005192 }
5193 // flush data already sent to the DSP if changing audio session as audio
5194 // comes from a different source. Also invalidate previous track to force a
5195 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08005196 if (previousTrack->sessionId() != track->sessionId()) {
5197 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005198 }
5199 }
5200 }
5201 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005202 // reset retry count
5203 track->mRetryCount = kMaxTrackRetriesOffload;
5204 mActiveTrack = t;
5205 mixerStatus = MIXER_TRACKS_READY;
5206 }
5207 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005208 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005209 if (track->isStopping_1()) {
5210 // Hardware buffer can hold a large amount of audio so we must
5211 // wait for all current track's data to drain before we say
5212 // that the track is stopped.
5213 if (mBytesRemaining == 0) {
5214 // Only start draining when all data in mixbuffer
5215 // has been written
5216 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
5217 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005218 // do not drain if no data was ever sent to HAL (mStandby == true)
5219 if (last && !mStandby) {
Eric Laurent1b9f9b12013-11-12 19:10:17 -08005220 // do not modify drain sequence if we are already draining. This happens
5221 // when resuming from pause after drain.
5222 if ((mDrainSequence & 1) == 0) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005223 mSleepTimeUs = 0;
5224 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent1b9f9b12013-11-12 19:10:17 -08005225 mixerStatus = MIXER_DRAIN_TRACK;
5226 mDrainSequence += 2;
5227 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005228 if (mHwPaused) {
5229 // It is possible to move from PAUSED to STOPPING_1 without
5230 // a resume so we must ensure hardware is running
Eric Laurent1b9f9b12013-11-12 19:10:17 -08005231 doHwResume = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005232 mHwPaused = false;
5233 }
5234 }
5235 }
5236 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005237 // Drain has completed or we are in standby, signal presentation complete
5238 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005239 track->mState = TrackBase::STOPPED;
5240 size_t audioHALFrames =
5241 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
5242 size_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08005243 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005244 track->presentationComplete(framesWritten, audioHALFrames);
5245 track->reset();
5246 tracksToRemove->add(track);
5247 }
5248 } else {
5249 // No buffers for this track. Give it a few chances to
5250 // fill a buffer, then remove it from active list.
5251 if (--(track->mRetryCount) <= 0) {
5252 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
5253 track->name());
5254 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08005255 // indicate to client process that the track was disabled because of underrun;
5256 // it will then automatically call start() when data is available
5257 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005258 } else if (last){
5259 mixerStatus = MIXER_TRACKS_ENABLED;
5260 }
5261 }
5262 }
5263 // compute volume for this track
5264 processVolume_l(track, last);
5265 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005266
Eric Laurentea0fade2013-10-04 16:23:48 -07005267 // make sure the pause/flush/resume sequence is executed in the right order.
5268 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5269 // before flush and then resume HW. This can happen in case of pause/flush/resume
5270 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07005271 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurent972a1732013-09-04 09:42:59 -07005272 mOutput->stream->pause(mOutput->stream);
5273 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005274 if (mFlushPending) {
5275 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005276 }
Eric Laurentfd477972013-10-25 18:10:40 -07005277 if (!mStandby && doHwResume) {
Eric Laurent972a1732013-09-04 09:42:59 -07005278 mOutput->stream->resume(mOutput->stream);
5279 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005280
Eric Laurentbfb1b832013-01-07 09:53:42 -08005281 // remove all the tracks that need to be...
5282 removeTracks_l(*tracksToRemove);
5283
5284 return mixerStatus;
5285}
5286
Eric Laurentbfb1b832013-01-07 09:53:42 -08005287// must be called with thread mutex locked
5288bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
5289{
Eric Laurent3b4529e2013-09-05 18:09:19 -07005290 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
5291 mWriteAckSequence, mDrainSequence);
5292 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005293 return true;
5294 }
5295 return false;
5296}
5297
Eric Laurentbfb1b832013-01-07 09:53:42 -08005298bool AudioFlinger::OffloadThread::waitingAsyncCallback()
5299{
5300 Mutex::Autolock _l(mLock);
5301 return waitingAsyncCallback_l();
5302}
5303
5304void AudioFlinger::OffloadThread::flushHw_l()
5305{
Eric Laurente659ef42014-09-29 13:06:46 -07005306 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005307 // Flush anything still waiting in the mixbuffer
5308 mCurrentWriteLength = 0;
5309 mBytesRemaining = 0;
5310 mPausedWriteLength = 0;
5311 mPausedBytesRemaining = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08005312
Eric Laurentbfb1b832013-01-07 09:53:42 -08005313 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005314 // discard any pending drain or write ack by incrementing sequence
5315 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5316 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005317 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005318 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5319 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005320 }
5321}
5322
5323// ----------------------------------------------------------------------------
5324
Eric Laurent81784c32012-11-19 14:55:58 -08005325AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07005326 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08005327 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
Eric Laurent72e3f392015-05-20 14:43:50 -07005328 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08005329 mWaitTimeMs(UINT_MAX)
5330{
5331 addOutputTrack(mainThread);
5332}
5333
5334AudioFlinger::DuplicatingThread::~DuplicatingThread()
5335{
5336 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5337 mOutputTracks[i]->destroy();
5338 }
5339}
5340
5341void AudioFlinger::DuplicatingThread::threadLoop_mix()
5342{
5343 // mix buffers...
5344 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08005345 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08005346 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08005347 if (mMixerBufferValid) {
5348 memset(mMixerBuffer, 0, mMixerBufferSize);
5349 } else {
5350 memset(mSinkBuffer, 0, mSinkBufferSize);
5351 }
Eric Laurent81784c32012-11-19 14:55:58 -08005352 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005353 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005354 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005355 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005356 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005357}
5358
5359void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
5360{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005361 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005362 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005363 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005364 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005365 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005366 }
5367 } else if (mBytesWritten != 0) {
5368 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5369 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005370 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005371 } else {
5372 // flush remaining overflow buffers in output tracks
5373 writeFrames = 0;
5374 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005375 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005376 }
5377}
5378
Eric Laurentbfb1b832013-01-07 09:53:42 -08005379ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005380{
5381 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08005382 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005383 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07005384 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08005385 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005386}
5387
5388void AudioFlinger::DuplicatingThread::threadLoop_standby()
5389{
5390 // DuplicatingThread implements standby by stopping all tracks
5391 for (size_t i = 0; i < outputTracks.size(); i++) {
5392 outputTracks[i]->stop();
5393 }
5394}
5395
5396void AudioFlinger::DuplicatingThread::saveOutputTracks()
5397{
5398 outputTracks = mOutputTracks;
5399}
5400
5401void AudioFlinger::DuplicatingThread::clearOutputTracks()
5402{
5403 outputTracks.clear();
5404}
5405
5406void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
5407{
5408 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08005409 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
5410 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
5411 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
5412 const size_t frameCount =
5413 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
5414 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
5415 // from different OutputTracks and their associated MixerThreads (e.g. one may
5416 // nearly empty and the other may be dropping data).
5417
5418 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08005419 this,
5420 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08005421 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08005422 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005423 frameCount,
5424 IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08005425 if (outputTrack->cblk() != NULL) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005426 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
Eric Laurent81784c32012-11-19 14:55:58 -08005427 mOutputTracks.add(outputTrack);
Andy Hungc25b84a2015-01-14 19:04:10 -08005428 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005429 updateWaitTime_l();
5430 }
5431}
5432
5433void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
5434{
5435 Mutex::Autolock _l(mLock);
5436 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5437 if (mOutputTracks[i]->thread() == thread) {
5438 mOutputTracks[i]->destroy();
5439 mOutputTracks.removeAt(i);
5440 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07005441 if (thread->getOutput() == mOutput) {
5442 mOutput = NULL;
5443 }
Eric Laurent81784c32012-11-19 14:55:58 -08005444 return;
5445 }
5446 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07005447 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005448}
5449
5450// caller must hold mLock
5451void AudioFlinger::DuplicatingThread::updateWaitTime_l()
5452{
5453 mWaitTimeMs = UINT_MAX;
5454 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5455 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
5456 if (strong != 0) {
5457 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
5458 if (waitTimeMs < mWaitTimeMs) {
5459 mWaitTimeMs = waitTimeMs;
5460 }
5461 }
5462 }
5463}
5464
5465
5466bool AudioFlinger::DuplicatingThread::outputsReady(
5467 const SortedVector< sp<OutputTrack> > &outputTracks)
5468{
5469 for (size_t i = 0; i < outputTracks.size(); i++) {
5470 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
5471 if (thread == 0) {
5472 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
5473 outputTracks[i].get());
5474 return false;
5475 }
5476 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5477 // see note at standby() declaration
5478 if (playbackThread->standby() && !playbackThread->isSuspended()) {
5479 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
5480 thread.get());
5481 return false;
5482 }
5483 }
5484 return true;
5485}
5486
5487uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
5488{
5489 return (mWaitTimeMs * 1000) / 2;
5490}
5491
5492void AudioFlinger::DuplicatingThread::cacheParameters_l()
5493{
5494 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
5495 updateWaitTime_l();
5496
5497 MixerThread::cacheParameters_l();
5498}
5499
5500// ----------------------------------------------------------------------------
5501// Record
5502// ----------------------------------------------------------------------------
5503
5504AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5505 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08005506 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08005507 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07005508 audio_devices_t inDevice,
5509 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08005510#ifdef TEE_SINK
5511 , const sp<NBAIO_Sink>& teeSink
5512#endif
5513 ) :
Eric Laurent72e3f392015-05-20 14:43:50 -07005514 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005515 mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005516 // mRsmpInFrames and mRsmpInFramesP2 are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005517 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08005518#ifdef TEE_SINK
5519 , mTeeSink(teeSink)
5520#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07005521 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
5522 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005523 // mFastCapture below
5524 , mFastCaptureFutex(0)
5525 // mInputSource
5526 // mPipeSink
5527 // mPipeSource
5528 , mPipeFramesP2(0)
5529 // mPipeMemory
5530 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005531 , mFastTrackAvail(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005532{
Glenn Kastend7dca052015-03-05 16:05:54 -08005533 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
5534 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08005535
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005536 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005537
5538 // create an NBAIO source for the HAL input stream, and negotiate
5539 mInputSource = new AudioStreamInSource(input->stream);
5540 size_t numCounterOffers = 0;
5541 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
5542 ssize_t index = mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
5543 ALOG_ASSERT(index == 0);
5544
5545 // initialize fast capture depending on configuration
5546 bool initFastCapture;
5547 switch (kUseFastCapture) {
5548 case FastCapture_Never:
5549 initFastCapture = false;
5550 break;
5551 case FastCapture_Always:
5552 initFastCapture = true;
5553 break;
5554 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07005555 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005556 break;
5557 // case FastCapture_Dynamic:
5558 }
5559
5560 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07005561 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005562 NBAIO_Format format = mInputSource->format();
Glenn Kasten49d00ad2014-07-21 11:22:03 -07005563 size_t pipeFramesP2 = roundup(mSampleRate / 25); // double-buffering of 20 ms each
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005564 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
5565 void *pipeBuffer;
5566 const sp<MemoryDealer> roHeap(readOnlyHeap());
5567 sp<IMemory> pipeMemory;
5568 if ((roHeap == 0) ||
5569 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
5570 (pipeBuffer = pipeMemory->pointer()) == NULL) {
5571 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
5572 goto failed;
5573 }
5574 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
5575 memset(pipeBuffer, 0, pipeSize);
5576 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
5577 const NBAIO_Format offers[1] = {format};
5578 size_t numCounterOffers = 0;
5579 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
5580 ALOG_ASSERT(index == 0);
5581 mPipeSink = pipe;
5582 PipeReader *pipeReader = new PipeReader(*pipe);
5583 numCounterOffers = 0;
5584 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
5585 ALOG_ASSERT(index == 0);
5586 mPipeSource = pipeReader;
5587 mPipeFramesP2 = pipeFramesP2;
5588 mPipeMemory = pipeMemory;
5589
5590 // create fast capture
5591 mFastCapture = new FastCapture();
5592 FastCaptureStateQueue *sq = mFastCapture->sq();
5593#ifdef STATE_QUEUE_DUMP
5594 // FIXME
5595#endif
5596 FastCaptureState *state = sq->begin();
5597 state->mCblk = NULL;
5598 state->mInputSource = mInputSource.get();
5599 state->mInputSourceGen++;
5600 state->mPipeSink = pipe;
5601 state->mPipeSinkGen++;
5602 state->mFrameCount = mFrameCount;
5603 state->mCommand = FastCaptureState::COLD_IDLE;
5604 // already done in constructor initialization list
5605 //mFastCaptureFutex = 0;
5606 state->mColdFutexAddr = &mFastCaptureFutex;
5607 state->mColdGen++;
5608 state->mDumpState = &mFastCaptureDumpState;
5609#ifdef TEE_SINK
5610 // FIXME
5611#endif
5612 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
5613 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
5614 sq->end();
5615 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5616
5617 // start the fast capture
5618 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
5619 pid_t tid = mFastCapture->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07005620 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005621#ifdef AUDIO_WATCHDOG
5622 // FIXME
5623#endif
5624
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005625 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005626 }
5627failed: ;
5628
5629 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08005630}
5631
Eric Laurent81784c32012-11-19 14:55:58 -08005632AudioFlinger::RecordThread::~RecordThread()
5633{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005634 if (mFastCapture != 0) {
5635 FastCaptureStateQueue *sq = mFastCapture->sq();
5636 FastCaptureState *state = sq->begin();
5637 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5638 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5639 if (old == -1) {
5640 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5641 }
5642 }
5643 state->mCommand = FastCaptureState::EXIT;
5644 sq->end();
5645 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5646 mFastCapture->join();
5647 mFastCapture.clear();
5648 }
5649 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07005650 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07005651 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08005652}
5653
5654void AudioFlinger::RecordThread::onFirstRef()
5655{
Glenn Kastend7dca052015-03-05 16:05:54 -08005656 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08005657}
5658
Eric Laurent81784c32012-11-19 14:55:58 -08005659bool AudioFlinger::RecordThread::threadLoop()
5660{
Eric Laurent81784c32012-11-19 14:55:58 -08005661 nsecs_t lastWarning = 0;
5662
5663 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08005664
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005665reacquire_wakelock:
5666 sp<RecordTrack> activeTrack;
Glenn Kasten2b806402013-11-20 16:37:38 -08005667 int activeTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005668 {
5669 Mutex::Autolock _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005670 size_t size = mActiveTracks.size();
5671 activeTracksGen = mActiveTracksGen;
5672 if (size > 0) {
5673 // FIXME an arbitrary choice
5674 activeTrack = mActiveTracks[0];
5675 acquireWakeLock_l(activeTrack->uid());
5676 if (size > 1) {
5677 SortedVector<int> tmp;
5678 for (size_t i = 0; i < size; i++) {
5679 tmp.add(mActiveTracks[i]->uid());
5680 }
5681 updateWakeLockUids_l(tmp);
5682 }
5683 } else {
5684 acquireWakeLock_l(-1);
5685 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005686 }
5687
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005688 // used to request a deferred sleep, to be executed later while mutex is unlocked
5689 uint32_t sleepUs = 0;
5690
5691 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005692 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005693 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07005694
Glenn Kasten5edadd42013-08-14 16:30:49 -07005695 // sleep with mutex unlocked
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005696 if (sleepUs > 0) {
Glenn Kastene7754022014-10-31 12:11:26 -07005697 ATRACE_BEGIN("sleep");
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005698 usleep(sleepUs);
Glenn Kastene7754022014-10-31 12:11:26 -07005699 ATRACE_END();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005700 sleepUs = 0;
Glenn Kasten5edadd42013-08-14 16:30:49 -07005701 }
5702
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005703 // activeTracks accumulates a copy of a subset of mActiveTracks
5704 Vector< sp<RecordTrack> > activeTracks;
5705
Glenn Kasten735f45f2014-08-18 15:51:59 -07005706 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005707 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07005708
Glenn Kasten735f45f2014-08-18 15:51:59 -07005709 // reference to a fast track which is about to be removed
5710 sp<RecordTrack> fastTrackToRemove;
5711
Eric Laurent81784c32012-11-19 14:55:58 -08005712 { // scope for mLock
5713 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08005714
Eric Laurent021cf962014-05-13 10:18:14 -07005715 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005716
Eric Laurent000a4192014-01-29 15:17:32 -08005717 // check exitPending here because checkForNewParameters_l() and
5718 // checkForNewParameters_l() can temporarily release mLock
5719 if (exitPending()) {
5720 break;
5721 }
5722
Glenn Kasten2b806402013-11-20 16:37:38 -08005723 // if no active track(s), then standby and release wakelock
5724 size_t size = mActiveTracks.size();
5725 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07005726 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005727 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08005728 releaseWakeLock_l();
5729 ALOGV("RecordThread: loop stopping");
5730 // go to sleep
5731 mWaitWorkCV.wait(mLock);
5732 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005733 goto reacquire_wakelock;
5734 }
5735
Glenn Kasten2b806402013-11-20 16:37:38 -08005736 if (mActiveTracksGen != activeTracksGen) {
5737 activeTracksGen = mActiveTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005738 SortedVector<int> tmp;
Glenn Kasten2b806402013-11-20 16:37:38 -08005739 for (size_t i = 0; i < size; i++) {
5740 tmp.add(mActiveTracks[i]->uid());
5741 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005742 updateWakeLockUids_l(tmp);
Eric Laurent81784c32012-11-19 14:55:58 -08005743 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005744
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005745 bool doBroadcast = false;
5746 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07005747
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005748 activeTrack = mActiveTracks[i];
5749 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07005750 if (activeTrack->isFastTrack()) {
5751 ALOG_ASSERT(fastTrackToRemove == 0);
5752 fastTrackToRemove = activeTrack;
5753 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005754 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08005755 mActiveTracks.remove(activeTrack);
5756 mActiveTracksGen++;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005757 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07005758 continue;
5759 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005760
5761 TrackBase::track_state activeTrackState = activeTrack->mState;
5762 switch (activeTrackState) {
5763
5764 case TrackBase::PAUSING:
5765 mActiveTracks.remove(activeTrack);
5766 mActiveTracksGen++;
5767 doBroadcast = true;
5768 size--;
5769 continue;
5770
5771 case TrackBase::STARTING_1:
5772 sleepUs = 10000;
5773 i++;
5774 continue;
5775
5776 case TrackBase::STARTING_2:
5777 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005778 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07005779 activeTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005780 break;
5781
5782 case TrackBase::ACTIVE:
5783 break;
5784
5785 case TrackBase::IDLE:
5786 i++;
5787 continue;
5788
5789 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08005790 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07005791 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005792
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005793 activeTracks.add(activeTrack);
5794 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07005795
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005796 if (activeTrack->isFastTrack()) {
5797 ALOG_ASSERT(!mFastTrackAvail);
5798 ALOG_ASSERT(fastTrack == 0);
5799 fastTrack = activeTrack;
5800 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005801 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005802 if (doBroadcast) {
5803 mStartStopCond.broadcast();
5804 }
5805
5806 // sleep if there are no active tracks to process
5807 if (activeTracks.size() == 0) {
5808 if (sleepUs == 0) {
5809 sleepUs = kRecordThreadSleepUs;
5810 }
5811 continue;
5812 }
5813 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07005814
Eric Laurent81784c32012-11-19 14:55:58 -08005815 lockEffectChains_l(effectChains);
5816 }
5817
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005818 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07005819
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005820 size_t size = effectChains.size();
5821 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005822 // thread mutex is not locked, but effect chain is locked
5823 effectChains[i]->process_l();
5824 }
5825
Glenn Kasten735f45f2014-08-18 15:51:59 -07005826 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005827 if (mFastCapture != 0) {
5828 FastCaptureStateQueue *sq = mFastCapture->sq();
5829 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07005830 bool didModify = false;
5831 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005832 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
5833 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
5834 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5835 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5836 if (old == -1) {
5837 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5838 }
5839 }
5840 state->mCommand = FastCaptureState::READ_WRITE;
5841#if 0 // FIXME
5842 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08005843 FastThreadDumpState::kSamplingNforLowRamDevice :
5844 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005845#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07005846 didModify = true;
5847 }
5848 audio_track_cblk_t *cblkOld = state->mCblk;
5849 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
5850 if (cblkNew != cblkOld) {
5851 state->mCblk = cblkNew;
5852 // block until acked if removing a fast track
5853 if (cblkOld != NULL) {
5854 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
5855 }
5856 didModify = true;
5857 }
5858 sq->end(didModify);
5859 if (didModify) {
5860 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005861#if 0
5862 if (kUseFastCapture == FastCapture_Dynamic) {
5863 mNormalSource = mPipeSource;
5864 }
5865#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005866 }
5867 }
5868
Glenn Kasten735f45f2014-08-18 15:51:59 -07005869 // now run the fast track destructor with thread mutex unlocked
5870 fastTrackToRemove.clear();
5871
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005872 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
5873 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
5874 // slow, then this RecordThread will overrun by not calling HAL read often enough.
5875 // If destination is non-contiguous, first read past the nominal end of buffer, then
5876 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005877
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005878 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005879 ssize_t framesRead;
5880
5881 // If an NBAIO source is present, use it to read the normal capture's data
5882 if (mPipeSource != 0) {
5883 size_t framesToRead = mBufferSize / mFrameSize;
Andy Hung57446612015-04-19 23:56:46 -07005884 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
Glenn Kastend79072e2016-01-06 08:41:20 -08005885 framesToRead);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005886 if (framesRead == 0) {
5887 // since pipe is non-blocking, simulate blocking input
5888 sleepUs = (framesToRead * 1000000LL) / mSampleRate;
5889 }
5890 // otherwise use the HAL / AudioStreamIn directly
5891 } else {
5892 ssize_t bytesRead = mInput->stream->read(mInput->stream,
Andy Hung57446612015-04-19 23:56:46 -07005893 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005894 if (bytesRead < 0) {
5895 framesRead = bytesRead;
5896 } else {
5897 framesRead = bytesRead / mFrameSize;
5898 }
5899 }
5900
5901 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
5902 ALOGE("read failed: framesRead=%d", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005903 // Force input into standby so that it tries to recover at next read attempt
5904 inputStandBy();
5905 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005906 }
5907 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005908 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005909 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005910 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005911
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005912 if (mTeeSink != 0) {
Andy Hung57446612015-04-19 23:56:46 -07005913 (void) mTeeSink->write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005914 }
5915 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005916 {
5917 size_t part1 = mRsmpInFramesP2 - rear;
5918 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07005919 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005920 (framesRead - part1) * mFrameSize);
5921 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005922 }
5923 rear = mRsmpInRear += framesRead;
5924
5925 size = activeTracks.size();
5926 // loop over each active track
5927 for (size_t i = 0; i < size; i++) {
5928 activeTrack = activeTracks[i];
5929
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005930 // skip fast tracks, as those are handled directly by FastCapture
5931 if (activeTrack->isFastTrack()) {
5932 continue;
5933 }
5934
Andy Hung73c02e42015-03-29 01:13:58 -07005935 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07005936 // TODO: Update the activeTrack buffer converter in case of reconfigure.
5937
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005938 enum {
5939 OVERRUN_UNKNOWN,
5940 OVERRUN_TRUE,
5941 OVERRUN_FALSE
5942 } overrun = OVERRUN_UNKNOWN;
5943
5944 // loop over getNextBuffer to handle circular sink
5945 for (;;) {
5946
5947 activeTrack->mSink.frameCount = ~0;
5948 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
5949 size_t framesOut = activeTrack->mSink.frameCount;
5950 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
5951
Andy Hung73c02e42015-03-29 01:13:58 -07005952 // check available frames and handle overrun conditions
5953 // if the record track isn't draining fast enough.
5954 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005955 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07005956 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
5957 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005958 overrun = OVERRUN_TRUE;
5959 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005960 if (framesOut == 0 || framesIn == 0) {
5961 break;
5962 }
5963
Andy Hung6770c6f2015-04-07 13:43:36 -07005964 // Don't allow framesOut to be larger than what is possible with resampling
5965 // from framesIn.
5966 // This isn't strictly necessary but helps limit buffer resizing in
5967 // RecordBufferConverter. TODO: remove when no longer needed.
5968 framesOut = min(framesOut,
5969 destinationFramesPossible(
5970 framesIn, mSampleRate, activeTrack->mSampleRate));
Andy Hung97a893e2015-03-29 01:03:07 -07005971 // process frames from the RecordThread buffer provider to the RecordTrack buffer
5972 framesOut = activeTrack->mRecordBufferConverter->convert(
5973 activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005974
5975 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
5976 overrun = OVERRUN_FALSE;
5977 }
5978
5979 if (activeTrack->mFramesToDrop == 0) {
5980 if (framesOut > 0) {
5981 activeTrack->mSink.frameCount = framesOut;
5982 activeTrack->releaseBuffer(&activeTrack->mSink);
5983 }
5984 } else {
5985 // FIXME could do a partial drop of framesOut
5986 if (activeTrack->mFramesToDrop > 0) {
5987 activeTrack->mFramesToDrop -= framesOut;
5988 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005989 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005990 }
5991 } else {
5992 activeTrack->mFramesToDrop += framesOut;
5993 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
5994 activeTrack->mSyncStartEvent->isCancelled()) {
5995 ALOGW("Synced record %s, session %d, trigger session %d",
5996 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
5997 activeTrack->sessionId(),
5998 (activeTrack->mSyncStartEvent != 0) ?
5999 activeTrack->mSyncStartEvent->triggerSession() : 0);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006000 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006001 }
6002 }
6003 }
6004
6005 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006006 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006007 }
6008 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006009
6010 switch (overrun) {
6011 case OVERRUN_TRUE:
6012 // client isn't retrieving buffers fast enough
6013 if (!activeTrack->setOverflow()) {
6014 nsecs_t now = systemTime();
6015 // FIXME should lastWarning per track?
6016 if ((now - lastWarning) > kWarningThrottleNs) {
6017 ALOGW("RecordThread: buffer overflow");
6018 lastWarning = now;
6019 }
6020 }
6021 break;
6022 case OVERRUN_FALSE:
6023 activeTrack->clearOverflow();
6024 break;
6025 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006026 break;
6027 }
6028
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006029 }
6030
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006031unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08006032 // enable changes in effect chain
6033 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006034 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08006035 }
6036
Glenn Kasten93e471f2013-08-19 08:40:07 -07006037 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08006038
6039 {
6040 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07006041 for (size_t i = 0; i < mTracks.size(); i++) {
6042 sp<RecordTrack> track = mTracks[i];
6043 track->invalidate();
6044 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006045 mActiveTracks.clear();
6046 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08006047 mStartStopCond.broadcast();
6048 }
6049
6050 releaseWakeLock();
6051
6052 ALOGV("RecordThread %p exiting", this);
6053 return false;
6054}
6055
Glenn Kasten93e471f2013-08-19 08:40:07 -07006056void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08006057{
6058 if (!mStandby) {
6059 inputStandBy();
6060 mStandby = true;
6061 }
6062}
6063
6064void AudioFlinger::RecordThread::inputStandBy()
6065{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006066 // Idle the fast capture if it's currently running
6067 if (mFastCapture != 0) {
6068 FastCaptureStateQueue *sq = mFastCapture->sq();
6069 FastCaptureState *state = sq->begin();
6070 if (!(state->mCommand & FastCaptureState::IDLE)) {
6071 state->mCommand = FastCaptureState::COLD_IDLE;
6072 state->mColdFutexAddr = &mFastCaptureFutex;
6073 state->mColdGen++;
6074 mFastCaptureFutex = 0;
6075 sq->end();
6076 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
6077 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
6078#if 0
6079 if (kUseFastCapture == FastCapture_Dynamic) {
6080 // FIXME
6081 }
6082#endif
6083#ifdef AUDIO_WATCHDOG
6084 // FIXME
6085#endif
6086 } else {
6087 sq->end(false /*didModify*/);
6088 }
6089 }
Eric Laurent81784c32012-11-19 14:55:58 -08006090 mInput->stream->common.standby(&mInput->stream->common);
6091}
6092
Glenn Kasten05997e22014-03-13 15:08:33 -07006093// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07006094sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08006095 const sp<AudioFlinger::Client>& client,
6096 uint32_t sampleRate,
6097 audio_format_t format,
6098 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08006099 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08006100 int sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07006101 size_t *notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08006102 int uid,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07006103 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08006104 pid_t tid,
6105 status_t *status)
6106{
Glenn Kasten74935e42013-12-19 08:56:45 -08006107 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08006108 sp<RecordTrack> track;
6109 status_t lStatus;
6110
Glenn Kasten90e58b12013-07-31 16:16:02 -07006111 // client expresses a preference for FAST, but we get the final say
6112 if (*flags & IAudioFlinger::TRACK_FAST) {
6113 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07006114 // we formerly checked for a callback handler (non-0 tid),
6115 // but that is no longer required for TRANSFER_OBTAIN mode
6116 //
Glenn Kasten74105912014-07-03 12:28:53 -07006117 // frame count is not specified, or is exactly the pipe depth
6118 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006119 // PCM data
6120 audio_is_linear_pcm(format) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006121 // native format
6122 (format == mFormat) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006123 // native channel mask
6124 (channelMask == mChannelMask) &&
6125 // native hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07006126 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006127 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006128 hasFastCapture() &&
6129 // there are sufficient fast track slots available
6130 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07006131 ) {
Glenn Kasten74105912014-07-03 12:28:53 -07006132 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%u mFrameCount=%u",
Glenn Kasten90e58b12013-07-31 16:16:02 -07006133 frameCount, mFrameCount);
6134 } else {
Glenn Kasten74105912014-07-03 12:28:53 -07006135 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%u mFrameCount=%u mPipeFramesP2=%u "
6136 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006137 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Glenn Kasten74105912014-07-03 12:28:53 -07006138 frameCount, mFrameCount, mPipeFramesP2,
6139 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
6140 hasFastCapture(), tid, mFastTrackAvail);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006141 *flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kasten74105912014-07-03 12:28:53 -07006142 }
6143 }
6144
6145 // compute track buffer size in frames, and suggest the notification frame count
6146 if (*flags & IAudioFlinger::TRACK_FAST) {
6147 // fast track: frame count is exactly the pipe depth
6148 frameCount = mPipeFramesP2;
6149 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
6150 *notificationFrames = mFrameCount;
6151 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006152 // not fast track: max notification period is resampled equivalent of one HAL buffer time
6153 // or 20 ms if there is a fast capture
6154 // TODO This could be a roundupRatio inline, and const
6155 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
6156 * sampleRate + mSampleRate - 1) / mSampleRate;
6157 // minimum number of notification periods is at least kMinNotifications,
6158 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
6159 static const size_t kMinNotifications = 3;
6160 static const uint32_t kMinMs = 30;
6161 // TODO This could be a roundupRatio inline
6162 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
6163 // TODO This could be a roundupRatio inline
6164 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
6165 maxNotificationFrames;
6166 const size_t minFrameCount = maxNotificationFrames *
6167 max(kMinNotifications, minNotificationsByMs);
6168 frameCount = max(frameCount, minFrameCount);
6169 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
6170 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07006171 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07006172 }
Glenn Kasten74935e42013-12-19 08:56:45 -08006173 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07006174
Glenn Kasten15e57982013-09-24 11:52:37 -07006175 lStatus = initCheck();
6176 if (lStatus != NO_ERROR) {
6177 ALOGE("createRecordTrack_l() audio driver not initialized");
6178 goto Exit;
6179 }
Eric Laurent81784c32012-11-19 14:55:58 -08006180
6181 { // scope for mLock
6182 Mutex::Autolock _l(mLock);
6183
6184 track = new RecordTrack(this, client, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07006185 format, channelMask, frameCount, NULL, sessionId, uid,
6186 *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08006187
Glenn Kasten03003332013-08-06 15:40:54 -07006188 lStatus = track->initCheck();
6189 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07006190 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08006191 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08006192 goto Exit;
6193 }
6194 mTracks.add(track);
6195
6196 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6197 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6198 mAudioFlinger->btNrecIsOff();
6199 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6200 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006201
6202 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
6203 pid_t callingPid = IPCThreadState::self()->getCallingPid();
6204 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
6205 // so ask activity manager to do this on our behalf
6206 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
6207 }
Eric Laurent81784c32012-11-19 14:55:58 -08006208 }
Glenn Kasten05997e22014-03-13 15:08:33 -07006209
Eric Laurent81784c32012-11-19 14:55:58 -08006210 lStatus = NO_ERROR;
6211
6212Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07006213 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08006214 return track;
6215}
6216
6217status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
6218 AudioSystem::sync_event_t event,
6219 int triggerSession)
6220{
6221 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
6222 sp<ThreadBase> strongMe = this;
6223 status_t status = NO_ERROR;
6224
6225 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006226 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006227 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006228 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08006229 triggerSession,
6230 recordTrack->sessionId(),
6231 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006232 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08006233 // Sync event can be cancelled by the trigger session if the track is not in a
6234 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006235 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006236 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006237 } else {
6238 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006239 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006240 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08006241 }
6242 }
6243
6244 {
Glenn Kasten47c20702013-08-13 15:37:35 -07006245 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08006246 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006247 if (mActiveTracks.indexOf(recordTrack) >= 0) {
6248 if (recordTrack->mState == TrackBase::PAUSING) {
6249 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006250 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006251 } else {
6252 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08006253 }
6254 return status;
6255 }
6256
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006257 // TODO consider other ways of handling this, such as changing the state to :STARTING and
6258 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
6259 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006260 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08006261 mActiveTracks.add(recordTrack);
6262 mActiveTracksGen++;
Eric Laurent83b88082014-06-20 18:31:16 -07006263 status_t status = NO_ERROR;
6264 if (recordTrack->isExternalTrack()) {
6265 mLock.unlock();
Eric Laurent4dc68062014-07-28 17:26:49 -07006266 status = AudioSystem::startInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006267 mLock.lock();
6268 // FIXME should verify that recordTrack is still in mActiveTracks
6269 if (status != NO_ERROR) {
6270 mActiveTracks.remove(recordTrack);
6271 mActiveTracksGen++;
6272 recordTrack->clearSyncStartEvent();
6273 ALOGV("RecordThread::start error %d", status);
6274 return status;
6275 }
Eric Laurent81784c32012-11-19 14:55:58 -08006276 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006277 // Catch up with current buffer indices if thread is already running.
6278 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
6279 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
6280 // see previously buffered data before it called start(), but with greater risk of overrun.
6281
Andy Hung73c02e42015-03-29 01:13:58 -07006282 recordTrack->mResamplerBufferProvider->reset();
Andy Hung97a893e2015-03-29 01:03:07 -07006283 // clear any converter state as new data will be discontinuous
6284 recordTrack->mRecordBufferConverter->reset();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006285 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08006286 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08006287 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08006288 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006289 ALOGV("Record failed to start");
6290 status = BAD_VALUE;
6291 goto startError;
6292 }
Eric Laurent81784c32012-11-19 14:55:58 -08006293 return status;
6294 }
Glenn Kasten7c027242012-12-26 14:43:16 -08006295
Eric Laurent81784c32012-11-19 14:55:58 -08006296startError:
Eric Laurent83b88082014-06-20 18:31:16 -07006297 if (recordTrack->isExternalTrack()) {
Eric Laurent4dc68062014-07-28 17:26:49 -07006298 AudioSystem::stopInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006299 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006300 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006301 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08006302 return status;
6303}
6304
Eric Laurent81784c32012-11-19 14:55:58 -08006305void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6306{
6307 sp<SyncEvent> strongEvent = event.promote();
6308
6309 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08006310 sp<RefBase> ptr = strongEvent->cookie().promote();
6311 if (ptr != 0) {
6312 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
6313 recordTrack->handleSyncStartEvent(strongEvent);
6314 }
Eric Laurent81784c32012-11-19 14:55:58 -08006315 }
6316}
6317
Glenn Kastena8356f62013-07-25 14:37:52 -07006318bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08006319 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07006320 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006321 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08006322 return false;
6323 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006324 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08006325 recordTrack->mState = TrackBase::PAUSING;
6326 // do not wait for mStartStopCond if exiting
6327 if (exitPending()) {
6328 return true;
6329 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006330 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08006331 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006332 // if we have been restarted, recordTrack is in mActiveTracks here
6333 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006334 ALOGV("Record stopped OK");
6335 return true;
6336 }
6337 return false;
6338}
6339
Glenn Kasten0f11b512014-01-31 16:18:54 -08006340bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08006341{
6342 return false;
6343}
6344
Glenn Kasten0f11b512014-01-31 16:18:54 -08006345status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006346{
6347#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
6348 if (!isValidSyncEvent(event)) {
6349 return BAD_VALUE;
6350 }
6351
6352 int eventSession = event->triggerSession();
6353 status_t ret = NAME_NOT_FOUND;
6354
6355 Mutex::Autolock _l(mLock);
6356
6357 for (size_t i = 0; i < mTracks.size(); i++) {
6358 sp<RecordTrack> track = mTracks[i];
6359 if (eventSession == track->sessionId()) {
6360 (void) track->setSyncEvent(event);
6361 ret = NO_ERROR;
6362 }
6363 }
6364 return ret;
6365#else
6366 return BAD_VALUE;
6367#endif
6368}
6369
6370// destroyTrack_l() must be called with ThreadBase::mLock held
6371void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6372{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006373 track->terminate();
6374 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08006375 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08006376 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006377 removeTrack_l(track);
6378 }
6379}
6380
6381void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6382{
6383 mTracks.remove(track);
6384 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006385 if (track->isFastTrack()) {
6386 ALOG_ASSERT(!mFastTrackAvail);
6387 mFastTrackAvail = true;
6388 }
Eric Laurent81784c32012-11-19 14:55:58 -08006389}
6390
6391void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6392{
6393 dumpInternals(fd, args);
6394 dumpTracks(fd, args);
6395 dumpEffectChains(fd, args);
6396}
6397
6398void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6399{
Elliott Hughes87cebad2014-05-22 10:14:43 -07006400 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08006401
Glenn Kasten44182c22015-03-05 17:12:23 -08006402 dumpBase(fd, args);
6403
6404 if (mActiveTracks.size() == 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006405 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006406 }
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006407 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006408 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08006409
Glenn Kasten2f90c512015-12-02 11:40:09 -08006410 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
6411 // while we are dumping it. It may be inconsistent, but it won't mutate!
6412 // This is a large object so we place it on the heap.
6413 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
6414 const FastCaptureDumpState *copy = new FastCaptureDumpState(mFastCaptureDumpState);
6415 copy->dump(fd);
6416 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08006417}
6418
Glenn Kasten0f11b512014-01-31 16:18:54 -08006419void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006420{
6421 const size_t SIZE = 256;
6422 char buffer[SIZE];
6423 String8 result;
6424
Marco Nelissenb2208842014-02-07 14:00:50 -08006425 size_t numtracks = mTracks.size();
6426 size_t numactive = mActiveTracks.size();
6427 size_t numactiveseen = 0;
Elliott Hughes87cebad2014-05-22 10:14:43 -07006428 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08006429 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006430 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08006431 RecordTrack::appendDumpHeader(result);
6432 for (size_t i = 0; i < numtracks ; ++i) {
6433 sp<RecordTrack> track = mTracks[i];
6434 if (track != 0) {
6435 bool active = mActiveTracks.indexOf(track) >= 0;
6436 if (active) {
6437 numactiveseen++;
6438 }
6439 track->dump(buffer, SIZE, active);
6440 result.append(buffer);
6441 }
Eric Laurent81784c32012-11-19 14:55:58 -08006442 }
Marco Nelissenb2208842014-02-07 14:00:50 -08006443 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006444 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006445 }
6446
Marco Nelissenb2208842014-02-07 14:00:50 -08006447 if (numactiveseen != numactive) {
6448 snprintf(buffer, SIZE, " The following tracks are in the active list but"
6449 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006450 result.append(buffer);
6451 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08006452 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08006453 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08006454 if (mTracks.indexOf(track) < 0) {
6455 track->dump(buffer, SIZE, true);
6456 result.append(buffer);
6457 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006458 }
Eric Laurent81784c32012-11-19 14:55:58 -08006459
6460 }
6461 write(fd, result.string(), result.size());
6462}
6463
Andy Hung73c02e42015-03-29 01:13:58 -07006464
6465void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
6466{
6467 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6468 RecordThread *recordThread = (RecordThread *) threadBase.get();
6469 mRsmpInFront = recordThread->mRsmpInRear;
6470 mRsmpInUnrel = 0;
6471}
6472
6473void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
6474 size_t *framesAvailable, bool *hasOverrun)
6475{
6476 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6477 RecordThread *recordThread = (RecordThread *) threadBase.get();
6478 const int32_t rear = recordThread->mRsmpInRear;
6479 const int32_t front = mRsmpInFront;
6480 const ssize_t filled = rear - front;
6481
6482 size_t framesIn;
6483 bool overrun = false;
6484 if (filled < 0) {
6485 // should not happen, but treat like a massive overrun and re-sync
6486 framesIn = 0;
6487 mRsmpInFront = rear;
6488 overrun = true;
6489 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
6490 framesIn = (size_t) filled;
6491 } else {
6492 // client is not keeping up with server, but give it latest data
6493 framesIn = recordThread->mRsmpInFrames;
6494 mRsmpInFront = /* front = */ rear - framesIn;
6495 overrun = true;
6496 }
6497 if (framesAvailable != NULL) {
6498 *framesAvailable = framesIn;
6499 }
6500 if (hasOverrun != NULL) {
6501 *hasOverrun = overrun;
6502 }
6503}
6504
Eric Laurent81784c32012-11-19 14:55:58 -08006505// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006506status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08006507 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006508{
Andy Hung73c02e42015-03-29 01:13:58 -07006509 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006510 if (threadBase == 0) {
6511 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006512 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006513 return NOT_ENOUGH_DATA;
6514 }
6515 RecordThread *recordThread = (RecordThread *) threadBase.get();
6516 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07006517 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07006518 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006519 // FIXME should not be P2 (don't want to increase latency)
6520 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006521 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07006522 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006523 front &= recordThread->mRsmpInFramesP2 - 1;
6524 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07006525 if (part1 > (size_t) filled) {
6526 part1 = filled;
6527 }
6528 size_t ask = buffer->frameCount;
6529 ALOG_ASSERT(ask > 0);
6530 if (part1 > ask) {
6531 part1 = ask;
6532 }
6533 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07006534 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07006535 buffer->raw = NULL;
6536 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07006537 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07006538 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08006539 }
6540
Andy Hung57446612015-04-19 23:56:46 -07006541 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07006542 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07006543 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08006544 return NO_ERROR;
6545}
6546
6547// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006548void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
6549 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006550{
Glenn Kasten85948432013-08-19 12:09:05 -07006551 size_t stepCount = buffer->frameCount;
6552 if (stepCount == 0) {
6553 return;
6554 }
Andy Hung73c02e42015-03-29 01:13:58 -07006555 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
6556 mRsmpInUnrel -= stepCount;
6557 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07006558 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006559 buffer->frameCount = 0;
6560}
6561
Andy Hung97a893e2015-03-29 01:03:07 -07006562AudioFlinger::RecordThread::RecordBufferConverter::RecordBufferConverter(
6563 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6564 uint32_t srcSampleRate,
6565 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6566 uint32_t dstSampleRate) :
6567 mSrcChannelMask(AUDIO_CHANNEL_INVALID), // updateParameters will set following vars
6568 // mSrcFormat
6569 // mSrcSampleRate
6570 // mDstChannelMask
6571 // mDstFormat
6572 // mDstSampleRate
6573 // mSrcChannelCount
6574 // mDstChannelCount
6575 // mDstFrameSize
6576 mBuf(NULL), mBufFrames(0), mBufFrameSize(0),
Andy Hungd330ee42015-04-20 13:23:41 -07006577 mResampler(NULL),
6578 mIsLegacyDownmix(false),
6579 mIsLegacyUpmix(false),
6580 mRequiresFloat(false),
6581 mInputConverterProvider(NULL)
Andy Hung97a893e2015-03-29 01:03:07 -07006582{
6583 (void)updateParameters(srcChannelMask, srcFormat, srcSampleRate,
6584 dstChannelMask, dstFormat, dstSampleRate);
6585}
6586
6587AudioFlinger::RecordThread::RecordBufferConverter::~RecordBufferConverter() {
6588 free(mBuf);
6589 delete mResampler;
Andy Hungd330ee42015-04-20 13:23:41 -07006590 delete mInputConverterProvider;
Andy Hung97a893e2015-03-29 01:03:07 -07006591}
6592
6593size_t AudioFlinger::RecordThread::RecordBufferConverter::convert(void *dst,
6594 AudioBufferProvider *provider, size_t frames)
6595{
Andy Hungd330ee42015-04-20 13:23:41 -07006596 if (mInputConverterProvider != NULL) {
6597 mInputConverterProvider->setBufferProvider(provider);
6598 provider = mInputConverterProvider;
6599 }
6600
6601 if (mResampler == NULL) {
Andy Hung97a893e2015-03-29 01:03:07 -07006602 ALOGVV("NO RESAMPLING sampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6603 mSrcSampleRate, mSrcFormat, mDstFormat);
6604
6605 AudioBufferProvider::Buffer buffer;
6606 for (size_t i = frames; i > 0; ) {
6607 buffer.frameCount = i;
Glenn Kastend79072e2016-01-06 08:41:20 -08006608 status_t status = provider->getNextBuffer(&buffer);
Andy Hung97a893e2015-03-29 01:03:07 -07006609 if (status != OK || buffer.frameCount == 0) {
6610 frames -= i; // cannot fill request.
6611 break;
6612 }
Andy Hungd330ee42015-04-20 13:23:41 -07006613 // format convert to destination buffer
6614 convertNoResampler(dst, buffer.raw, buffer.frameCount);
Andy Hung97a893e2015-03-29 01:03:07 -07006615
6616 dst = (int8_t*)dst + buffer.frameCount * mDstFrameSize;
6617 i -= buffer.frameCount;
6618 provider->releaseBuffer(&buffer);
6619 }
6620 } else {
6621 ALOGVV("RESAMPLING mSrcSampleRate:%u mDstSampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6622 mSrcSampleRate, mDstSampleRate, mSrcFormat, mDstFormat);
6623
Andy Hungd330ee42015-04-20 13:23:41 -07006624 // reallocate buffer if needed
6625 if (mBufFrameSize != 0 && mBufFrames < frames) {
6626 free(mBuf);
6627 mBufFrames = frames;
6628 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
6629 }
Andy Hung97a893e2015-03-29 01:03:07 -07006630 // resampler accumulates, but we only have one source track
Andy Hungd330ee42015-04-20 13:23:41 -07006631 memset(mBuf, 0, frames * mBufFrameSize);
6632 frames = mResampler->resample((int32_t*)mBuf, frames, provider);
6633 // format convert to destination buffer
6634 convertResampler(dst, mBuf, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006635 }
6636 return frames;
6637}
6638
6639status_t AudioFlinger::RecordThread::RecordBufferConverter::updateParameters(
6640 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6641 uint32_t srcSampleRate,
6642 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6643 uint32_t dstSampleRate)
6644{
6645 // quick evaluation if there is any change.
6646 if (mSrcFormat == srcFormat
6647 && mSrcChannelMask == srcChannelMask
6648 && mSrcSampleRate == srcSampleRate
6649 && mDstFormat == dstFormat
6650 && mDstChannelMask == dstChannelMask
6651 && mDstSampleRate == dstSampleRate) {
6652 return NO_ERROR;
6653 }
6654
Andy Hungdb4c0312015-05-06 08:46:52 -07006655 ALOGV("RecordBufferConverter updateParameters srcMask:%#x dstMask:%#x"
6656 " srcFormat:%#x dstFormat:%#x srcRate:%u dstRate:%u",
6657 srcChannelMask, dstChannelMask, srcFormat, dstFormat, srcSampleRate, dstSampleRate);
Andy Hung97a893e2015-03-29 01:03:07 -07006658 const bool valid =
6659 audio_is_input_channel(srcChannelMask)
6660 && audio_is_input_channel(dstChannelMask)
6661 && audio_is_valid_format(srcFormat) && audio_is_linear_pcm(srcFormat)
6662 && audio_is_valid_format(dstFormat) && audio_is_linear_pcm(dstFormat)
6663 && (srcSampleRate <= dstSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX)
6664 ; // no upsampling checks for now
6665 if (!valid) {
6666 return BAD_VALUE;
6667 }
6668
6669 mSrcFormat = srcFormat;
6670 mSrcChannelMask = srcChannelMask;
6671 mSrcSampleRate = srcSampleRate;
6672 mDstFormat = dstFormat;
6673 mDstChannelMask = dstChannelMask;
6674 mDstSampleRate = dstSampleRate;
6675
6676 // compute derived parameters
6677 mSrcChannelCount = audio_channel_count_from_in_mask(srcChannelMask);
6678 mDstChannelCount = audio_channel_count_from_in_mask(dstChannelMask);
6679 mDstFrameSize = mDstChannelCount * audio_bytes_per_sample(mDstFormat);
6680
Andy Hungd330ee42015-04-20 13:23:41 -07006681 // do we need to resample?
6682 delete mResampler;
6683 mResampler = NULL;
6684 if (mSrcSampleRate != mDstSampleRate) {
6685 mResampler = AudioResampler::create(AUDIO_FORMAT_PCM_FLOAT,
6686 mSrcChannelCount, mDstSampleRate);
6687 mResampler->setSampleRate(mSrcSampleRate);
6688 mResampler->setVolume(AudioMixer::UNITY_GAIN_FLOAT, AudioMixer::UNITY_GAIN_FLOAT);
6689 }
6690
6691 // are we running legacy channel conversion modes?
6692 mIsLegacyDownmix = (mSrcChannelMask == AUDIO_CHANNEL_IN_STEREO
6693 || mSrcChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK)
6694 && mDstChannelMask == AUDIO_CHANNEL_IN_MONO;
6695 mIsLegacyUpmix = mSrcChannelMask == AUDIO_CHANNEL_IN_MONO
6696 && (mDstChannelMask == AUDIO_CHANNEL_IN_STEREO
6697 || mDstChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK);
6698
6699 // do we need to process in float?
6700 mRequiresFloat = mResampler != NULL || mIsLegacyDownmix || mIsLegacyUpmix;
6701
6702 // do we need a staging buffer to convert for destination (we can still optimize this)?
6703 // we use mBufFrameSize > 0 to indicate both frame size as well as buffer necessity
6704 if (mResampler != NULL) {
6705 mBufFrameSize = max(mSrcChannelCount, FCC_2)
6706 * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
Andy Hunga97630b2015-07-22 23:27:24 -07006707 } else if (mIsLegacyUpmix || mIsLegacyDownmix) { // legacy modes always float
Andy Hungd330ee42015-04-20 13:23:41 -07006708 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
6709 } else if (mSrcChannelMask != mDstChannelMask && mDstFormat != mSrcFormat) {
Andy Hung97a893e2015-03-29 01:03:07 -07006710 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(mSrcFormat);
6711 } else {
6712 mBufFrameSize = 0;
6713 }
6714 mBufFrames = 0; // force the buffer to be resized.
6715
Andy Hungd330ee42015-04-20 13:23:41 -07006716 // do we need an input converter buffer provider to give us float?
6717 delete mInputConverterProvider;
6718 mInputConverterProvider = NULL;
6719 if (mRequiresFloat && mSrcFormat != AUDIO_FORMAT_PCM_FLOAT) {
6720 mInputConverterProvider = new ReformatBufferProvider(
6721 audio_channel_count_from_in_mask(mSrcChannelMask),
6722 mSrcFormat,
6723 AUDIO_FORMAT_PCM_FLOAT,
6724 256 /* provider buffer frame count */);
6725 }
6726
6727 // do we need a remixer to do channel mask conversion
6728 if (!mIsLegacyDownmix && !mIsLegacyUpmix && mSrcChannelMask != mDstChannelMask) {
6729 (void) memcpy_by_index_array_initialization_from_channel_mask(
6730 mIdxAry, ARRAY_SIZE(mIdxAry), mDstChannelMask, mSrcChannelMask);
Andy Hung97a893e2015-03-29 01:03:07 -07006731 }
6732 return NO_ERROR;
6733}
6734
Andy Hungd330ee42015-04-20 13:23:41 -07006735void AudioFlinger::RecordThread::RecordBufferConverter::convertNoResampler(
6736 void *dst, const void *src, size_t frames)
Andy Hung97a893e2015-03-29 01:03:07 -07006737{
Andy Hungd330ee42015-04-20 13:23:41 -07006738 // src is native type unless there is legacy upmix or downmix, whereupon it is float.
Andy Hung97a893e2015-03-29 01:03:07 -07006739 if (mBufFrameSize != 0 && mBufFrames < frames) {
6740 free(mBuf);
6741 mBufFrames = frames;
6742 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
6743 }
Andy Hungd330ee42015-04-20 13:23:41 -07006744 // do we need to do legacy upmix and downmix?
6745 if (mIsLegacyUpmix || mIsLegacyDownmix) {
Andy Hung97a893e2015-03-29 01:03:07 -07006746 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07006747 if (mIsLegacyUpmix) {
6748 upmix_to_stereo_float_from_mono_float((float *)dstBuf,
6749 (const float *)src, frames);
6750 } else /*mIsLegacyDownmix */ {
6751 downmix_to_mono_float_from_stereo_float((float *)dstBuf,
6752 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006753 }
Andy Hungd330ee42015-04-20 13:23:41 -07006754 if (mBuf != NULL) {
6755 memcpy_by_audio_format(dst, mDstFormat, mBuf, AUDIO_FORMAT_PCM_FLOAT,
6756 frames * mDstChannelCount);
6757 }
6758 return;
6759 }
6760 // do we need to do channel mask conversion?
6761 if (mSrcChannelMask != mDstChannelMask) {
Andy Hung97a893e2015-03-29 01:03:07 -07006762 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07006763 memcpy_by_index_array(dstBuf, mDstChannelCount,
6764 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mSrcFormat), frames);
6765 if (dstBuf == dst) {
6766 return; // format is the same
6767 }
6768 }
6769 // convert to destination buffer
6770 const void *convertBuf = mBuf != NULL ? mBuf : src;
6771 memcpy_by_audio_format(dst, mDstFormat, convertBuf, mSrcFormat,
6772 frames * mDstChannelCount);
6773}
6774
6775void AudioFlinger::RecordThread::RecordBufferConverter::convertResampler(
6776 void *dst, /*not-a-const*/ void *src, size_t frames)
6777{
6778 // src buffer format is ALWAYS float when entering this routine
6779 if (mIsLegacyUpmix) {
6780 ; // mono to stereo already handled by resampler
6781 } else if (mIsLegacyDownmix
6782 || (mSrcChannelMask == mDstChannelMask && mSrcChannelCount == 1)) {
6783 // the resampler outputs stereo for mono input channel (a feature?)
6784 // must convert to mono
6785 downmix_to_mono_float_from_stereo_float((float *)src,
6786 (const float *)src, frames);
6787 } else if (mSrcChannelMask != mDstChannelMask) {
6788 // convert to mono channel again for channel mask conversion (could be skipped
6789 // with further optimization).
Andy Hung97a893e2015-03-29 01:03:07 -07006790 if (mSrcChannelCount == 1) {
Andy Hungd330ee42015-04-20 13:23:41 -07006791 downmix_to_mono_float_from_stereo_float((float *)src,
6792 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006793 }
Andy Hungd330ee42015-04-20 13:23:41 -07006794 // convert to destination format (in place, OK as float is larger than other types)
6795 if (mDstFormat != AUDIO_FORMAT_PCM_FLOAT) {
6796 memcpy_by_audio_format(src, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
6797 frames * mSrcChannelCount);
6798 }
6799 // channel convert and save to dst
6800 memcpy_by_index_array(dst, mDstChannelCount,
6801 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mDstFormat), frames);
6802 return;
Andy Hung97a893e2015-03-29 01:03:07 -07006803 }
Andy Hungd330ee42015-04-20 13:23:41 -07006804 // convert to destination format and save to dst
6805 memcpy_by_audio_format(dst, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
6806 frames * mDstChannelCount);
Andy Hung97a893e2015-03-29 01:03:07 -07006807}
6808
Eric Laurent10351942014-05-08 18:49:52 -07006809bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
6810 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006811{
6812 bool reconfig = false;
6813
Eric Laurent10351942014-05-08 18:49:52 -07006814 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006815
Eric Laurent10351942014-05-08 18:49:52 -07006816 audio_format_t reqFormat = mFormat;
6817 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07006818 // 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 -07006819 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
6820
6821 AudioParameter param = AudioParameter(keyValuePair);
6822 int value;
6823 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
6824 // channel count change can be requested. Do we mandate the first client defines the
6825 // HAL sampling rate and channel count or do we allow changes on the fly?
6826 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6827 samplingRate = value;
6828 reconfig = true;
6829 }
6830 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07006831 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07006832 status = BAD_VALUE;
6833 } else {
6834 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08006835 reconfig = true;
6836 }
Eric Laurent10351942014-05-08 18:49:52 -07006837 }
6838 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
6839 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07006840 if (!audio_is_input_channel(mask) ||
6841 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07006842 status = BAD_VALUE;
6843 } else {
6844 channelMask = mask;
6845 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006846 }
Eric Laurent10351942014-05-08 18:49:52 -07006847 }
6848 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6849 // do not accept frame count changes if tracks are open as the track buffer
6850 // size depends on frame count and correct behavior would not be guaranteed
6851 // if frame count is changed after track creation
6852 if (mActiveTracks.size() > 0) {
6853 status = INVALID_OPERATION;
6854 } else {
6855 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006856 }
Eric Laurent10351942014-05-08 18:49:52 -07006857 }
6858 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6859 // forward device change to effects that have requested to be
6860 // aware of attached audio device.
6861 for (size_t i = 0; i < mEffectChains.size(); i++) {
6862 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08006863 }
Eric Laurent81784c32012-11-19 14:55:58 -08006864
Eric Laurent10351942014-05-08 18:49:52 -07006865 // store input device and output device but do not forward output device to audio HAL.
6866 // Note that status is ignored by the caller for output device
6867 // (see AudioFlinger::setParameters()
6868 if (audio_is_output_devices(value)) {
6869 mOutDevice = value;
6870 status = BAD_VALUE;
6871 } else {
6872 mInDevice = value;
Eric Laurente8726fe2015-06-26 09:39:24 -07006873 if (value != AUDIO_DEVICE_NONE) {
6874 mPrevInDevice = value;
6875 }
Eric Laurent10351942014-05-08 18:49:52 -07006876 // disable AEC and NS if the device is a BT SCO headset supporting those
6877 // pre processings
6878 if (mTracks.size() > 0) {
6879 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6880 mAudioFlinger->btNrecIsOff();
6881 for (size_t i = 0; i < mTracks.size(); i++) {
6882 sp<RecordTrack> track = mTracks[i];
6883 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
6884 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08006885 }
6886 }
6887 }
Eric Laurent10351942014-05-08 18:49:52 -07006888 }
6889 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
6890 mAudioSource != (audio_source_t)value) {
6891 // forward device change to effects that have requested to be
6892 // aware of attached audio device.
6893 for (size_t i = 0; i < mEffectChains.size(); i++) {
6894 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08006895 }
Eric Laurent10351942014-05-08 18:49:52 -07006896 mAudioSource = (audio_source_t)value;
6897 }
Glenn Kastene198c362013-08-13 09:13:36 -07006898
Eric Laurent10351942014-05-08 18:49:52 -07006899 if (status == NO_ERROR) {
6900 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6901 keyValuePair.string());
6902 if (status == INVALID_OPERATION) {
6903 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006904 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6905 keyValuePair.string());
Eric Laurent10351942014-05-08 18:49:52 -07006906 }
6907 if (reconfig) {
6908 if (status == BAD_VALUE &&
Andy Hung97a893e2015-03-29 01:03:07 -07006909 audio_is_linear_pcm(mInput->stream->common.get_format(&mInput->stream->common)) &&
6910 audio_is_linear_pcm(reqFormat) &&
Eric Laurent10351942014-05-08 18:49:52 -07006911 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
Andy Hung97a893e2015-03-29 01:03:07 -07006912 <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate)) &&
Andy Hunge5412692014-05-16 11:25:07 -07006913 audio_channel_count_from_in_mask(
Andy Hungd1abb8f2015-05-05 23:42:34 -07006914 mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07006915 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006916 }
Eric Laurent10351942014-05-08 18:49:52 -07006917 if (status == NO_ERROR) {
6918 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07006919 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08006920 }
6921 }
Eric Laurent81784c32012-11-19 14:55:58 -08006922 }
Eric Laurent10351942014-05-08 18:49:52 -07006923
Eric Laurent81784c32012-11-19 14:55:58 -08006924 return reconfig;
6925}
6926
6927String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6928{
Eric Laurent81784c32012-11-19 14:55:58 -08006929 Mutex::Autolock _l(mLock);
6930 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07006931 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08006932 }
6933
Glenn Kastend8ea6992013-07-16 14:17:15 -07006934 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
6935 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08006936 free(s);
6937 return out_s8;
6938}
6939
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07006940void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07006941 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
6942
6943 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08006944
6945 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07006946 case AUDIO_INPUT_OPENED:
6947 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07006948 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07006949 desc->mChannelMask = mChannelMask;
6950 desc->mSamplingRate = mSampleRate;
6951 desc->mFormat = mFormat;
6952 desc->mFrameCount = mFrameCount;
6953 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006954 break;
6955
Eric Laurent73e26b62015-04-27 16:55:58 -07006956 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08006957 default:
6958 break;
6959 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07006960 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08006961}
6962
Glenn Kastendeca2ae2014-02-07 10:25:56 -08006963void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006964{
Eric Laurent81784c32012-11-19 14:55:58 -08006965 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
6966 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Andy Hunge5412692014-05-16 11:25:07 -07006967 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Andy Hungd330ee42015-04-20 13:23:41 -07006968 if (mChannelCount > FCC_8) {
6969 ALOGE("HAL channel count %d > %d", mChannelCount, FCC_8);
6970 }
Andy Hung463be252014-07-10 16:56:07 -07006971 mHALFormat = mInput->stream->common.get_format(&mInput->stream->common);
6972 mFormat = mHALFormat;
Andy Hungd330ee42015-04-20 13:23:41 -07006973 if (!audio_is_linear_pcm(mFormat)) {
6974 ALOGE("HAL format %#x is not linear pcm", mFormat);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07006975 }
Eric Laurent665470b2014-07-03 16:37:08 -07006976 mFrameSize = audio_stream_in_frame_size(mInput->stream);
Glenn Kasten548efc92012-11-29 08:48:51 -08006977 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
6978 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006979 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08006980 // 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 -07006981 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08006982 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006983 // A larger value should allow more old data to be read after a track calls start(),
6984 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07006985 //
6986 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08006987 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07006988 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07006989 free(mRsmpInBuffer);
Andy Hung0a01c2f2015-09-21 12:44:54 -07006990 mRsmpInBuffer = NULL;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006991
6992 // TODO optimize audio capture buffer sizes ...
6993 // Here we calculate the size of the sliding buffer used as a source
6994 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
6995 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
6996 // be better to have it derived from the pipe depth in the long term.
6997 // The current value is higher than necessary. However it should not add to latency.
6998
Glenn Kasten85948432013-08-19 12:09:05 -07006999 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Andy Hung0a01c2f2015-09-21 12:44:54 -07007000 size_t bufferSize = (mRsmpInFramesP2 + mFrameCount - 1) * mFrameSize;
7001 (void)posix_memalign(&mRsmpInBuffer, 32, bufferSize);
7002 memset(mRsmpInBuffer, 0, bufferSize); // if posix_memalign fails, will segv here.
Eric Laurent81784c32012-11-19 14:55:58 -08007003
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007004 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
7005 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08007006}
7007
Glenn Kasten5f972c02014-01-13 09:59:31 -08007008uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08007009{
7010 Mutex::Autolock _l(mLock);
7011 if (initCheck() != NO_ERROR) {
7012 return 0;
7013 }
7014
7015 return mInput->stream->get_input_frames_lost(mInput->stream);
7016}
7017
7018uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
7019{
7020 Mutex::Autolock _l(mLock);
7021 uint32_t result = 0;
7022 if (getEffectChain_l(sessionId) != 0) {
7023 result = EFFECT_SESSION;
7024 }
7025
7026 for (size_t i = 0; i < mTracks.size(); ++i) {
7027 if (sessionId == mTracks[i]->sessionId()) {
7028 result |= TRACK_SESSION;
7029 break;
7030 }
7031 }
7032
7033 return result;
7034}
7035
7036KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
7037{
7038 KeyedVector<int, bool> ids;
7039 Mutex::Autolock _l(mLock);
7040 for (size_t j = 0; j < mTracks.size(); ++j) {
7041 sp<RecordThread::RecordTrack> track = mTracks[j];
7042 int sessionId = track->sessionId();
7043 if (ids.indexOfKey(sessionId) < 0) {
7044 ids.add(sessionId, true);
7045 }
7046 }
7047 return ids;
7048}
7049
7050AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
7051{
7052 Mutex::Autolock _l(mLock);
7053 AudioStreamIn *input = mInput;
7054 mInput = NULL;
7055 return input;
7056}
7057
7058// this method must always be called either with ThreadBase mLock held or inside the thread loop
7059audio_stream_t* AudioFlinger::RecordThread::stream() const
7060{
7061 if (mInput == NULL) {
7062 return NULL;
7063 }
7064 return &mInput->stream->common;
7065}
7066
7067status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7068{
7069 // only one chain per input thread
7070 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07007071 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08007072 return INVALID_OPERATION;
7073 }
7074 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07007075 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08007076 chain->setInBuffer(NULL);
7077 chain->setOutBuffer(NULL);
7078
7079 checkSuspendOnAddEffectChain_l(chain);
7080
Eric Laurent1b928682014-10-02 19:41:47 -07007081 // make sure enabled pre processing effects state is communicated to the HAL as we
7082 // just moved them to a new input stream.
7083 chain->syncHalEffectsState();
7084
Eric Laurent81784c32012-11-19 14:55:58 -08007085 mEffectChains.add(chain);
7086
7087 return NO_ERROR;
7088}
7089
7090size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7091{
7092 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
7093 ALOGW_IF(mEffectChains.size() != 1,
7094 "removeEffectChain_l() %p invalid chain size %d on thread %p",
7095 chain.get(), mEffectChains.size(), this);
7096 if (mEffectChains.size() == 1) {
7097 mEffectChains.removeAt(0);
7098 }
7099 return 0;
7100}
7101
Eric Laurent1c333e22014-05-20 10:48:17 -07007102status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
7103 audio_patch_handle_t *handle)
7104{
7105 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007106
7107 // store new device and send to effects
7108 mInDevice = patch->sources[0].ext.device.type;
Eric Laurent296fb132015-05-01 11:38:42 -07007109 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07007110 for (size_t i = 0; i < mEffectChains.size(); i++) {
7111 mEffectChains[i]->setDevice_l(mInDevice);
7112 }
7113
7114 // disable AEC and NS if the device is a BT SCO headset supporting those
7115 // pre processings
7116 if (mTracks.size() > 0) {
7117 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7118 mAudioFlinger->btNrecIsOff();
7119 for (size_t i = 0; i < mTracks.size(); i++) {
7120 sp<RecordTrack> track = mTracks[i];
7121 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7122 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
7123 }
7124 }
7125
7126 // store new source and send to effects
7127 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7128 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07007129 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07007130 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07007131 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007132 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007133
Eric Laurent054d9d32015-04-24 08:48:48 -07007134 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007135 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
7136 status = hwDevice->create_audio_patch(hwDevice,
7137 patch->num_sources,
7138 patch->sources,
7139 patch->num_sinks,
7140 patch->sinks,
7141 handle);
7142 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007143 char *address;
7144 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
7145 address = audio_device_address_to_parameter(
7146 patch->sources[0].ext.device.type,
7147 patch->sources[0].ext.device.address);
7148 } else {
7149 address = (char *)calloc(1, 1);
7150 }
7151 AudioParameter param = AudioParameter(String8(address));
7152 free(address);
7153 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING),
7154 (int)patch->sources[0].ext.device.type);
7155 param.addInt(String8(AUDIO_PARAMETER_STREAM_INPUT_SOURCE),
7156 (int)patch->sinks[0].ext.mix.usecase.source);
7157 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7158 param.toString().string());
7159 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07007160 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007161
Eric Laurente8726fe2015-06-26 09:39:24 -07007162 if (mInDevice != mPrevInDevice) {
7163 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
7164 mPrevInDevice = mInDevice;
7165 }
Eric Laurent296fb132015-05-01 11:38:42 -07007166
Eric Laurent1c333e22014-05-20 10:48:17 -07007167 return status;
7168}
7169
7170status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
7171{
7172 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007173
7174 mInDevice = AUDIO_DEVICE_NONE;
7175
Eric Laurent1c333e22014-05-20 10:48:17 -07007176 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
7177 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
7178 status = hwDevice->release_audio_patch(hwDevice, handle);
7179 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007180 AudioParameter param;
7181 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
7182 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7183 param.toString().string());
Eric Laurent1c333e22014-05-20 10:48:17 -07007184 }
7185 return status;
7186}
7187
Eric Laurent83b88082014-06-20 18:31:16 -07007188void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
7189{
7190 Mutex::Autolock _l(mLock);
7191 mTracks.add(record);
7192}
7193
7194void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
7195{
7196 Mutex::Autolock _l(mLock);
7197 destroyTrack_l(record);
7198}
7199
7200void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
7201{
7202 ThreadBase::getAudioPortConfig(config);
7203 config->role = AUDIO_PORT_ROLE_SINK;
7204 config->ext.mix.hw_module = mInput->audioHwDev->handle();
7205 config->ext.mix.usecase.source = mAudioSource;
7206}
Eric Laurent1c333e22014-05-20 10:48:17 -07007207
Glenn Kasten63238ef2015-03-02 15:50:29 -08007208} // namespace android