blob: c3a82256c82c2b1cff31d53a4828f3c1a1d53bd1 [file] [log] [blame]
Eric Laurent81784c32012-11-19 14:55:58 -08001/*
2**
3** Copyright 2012, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
Alex Ray371eb972012-11-30 11:11:54 -080021#define ATRACE_TAG ATRACE_TAG_AUDIO
Eric Laurent81784c32012-11-19 14:55:58 -080022
Glenn Kasten153b9fe2013-07-15 11:23:36 -070023#include "Configuration.h"
Eric Laurent81784c32012-11-19 14:55:58 -080024#include <math.h>
25#include <fcntl.h>
Glenn Kastenad8510a2015-02-17 16:24:07 -080026#include <linux/futex.h>
Eric Laurent81784c32012-11-19 14:55:58 -080027#include <sys/stat.h>
Glenn Kastenad8510a2015-02-17 16:24:07 -080028#include <sys/syscall.h>
Eric Laurent81784c32012-11-19 14:55:58 -080029#include <cutils/properties.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070030#include <media/AudioParameter.h>
Andy Hungcd044842014-08-07 11:04:34 -070031#include <media/AudioResamplerPublic.h>
Eric Laurent81784c32012-11-19 14:55:58 -080032#include <utils/Log.h>
Alex Ray371eb972012-11-30 11:11:54 -080033#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080034
35#include <private/media/AudioTrackShared.h>
36#include <hardware/audio.h>
37#include <audio_effects/effect_ns.h>
38#include <audio_effects/effect_aec.h>
39#include <audio_utils/primitives.h>
Andy Hung98ef9782014-03-04 14:46:50 -080040#include <audio_utils/format.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070041#include <audio_utils/minifloat.h>
Eric Laurent81784c32012-11-19 14:55:58 -080042
43// NBAIO implementations
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070044#include <media/nbaio/AudioStreamInSource.h>
Eric Laurent81784c32012-11-19 14:55:58 -080045#include <media/nbaio/AudioStreamOutSink.h>
46#include <media/nbaio/MonoPipe.h>
47#include <media/nbaio/MonoPipeReader.h>
48#include <media/nbaio/Pipe.h>
49#include <media/nbaio/PipeReader.h>
50#include <media/nbaio/SourceAudioBufferProvider.h>
Wei Jia3f273d12015-11-24 09:06:49 -080051#include <mediautils/BatteryNotifier.h>
Eric Laurent81784c32012-11-19 14:55:58 -080052
53#include <powermanager/PowerManager.h>
54
55#include <common_time/cc_helper.h>
56#include <common_time/local_clock.h>
57
58#include "AudioFlinger.h"
59#include "AudioMixer.h"
Andy Hungd330ee42015-04-20 13:23:41 -070060#include "BufferProviders.h"
Eric Laurent81784c32012-11-19 14:55:58 -080061#include "FastMixer.h"
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070062#include "FastCapture.h"
Eric Laurent81784c32012-11-19 14:55:58 -080063#include "ServiceUtilities.h"
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -070064#include "mediautils/SchedulingPolicyService.h"
Eric Laurent81784c32012-11-19 14:55:58 -080065
Eric Laurent81784c32012-11-19 14:55:58 -080066#ifdef ADD_BATTERY_DATA
67#include <media/IMediaPlayerService.h>
68#include <media/IMediaDeathNotifier.h>
69#endif
70
Eric Laurent81784c32012-11-19 14:55:58 -080071#ifdef DEBUG_CPU_USAGE
72#include <cpustats/CentralTendencyStatistics.h>
73#include <cpustats/ThreadCpuUsage.h>
74#endif
75
76// ----------------------------------------------------------------------------
77
78// Note: the following macro is used for extremely verbose logging message. In
79// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
80// 0; but one side effect of this is to turn all LOGV's as well. Some messages
81// are so verbose that we want to suppress them even when we have ALOG_ASSERT
82// turned on. Do not uncomment the #def below unless you really know what you
83// are doing and want to see all of the extremely verbose messages.
84//#define VERY_VERY_VERBOSE_LOGGING
85#ifdef VERY_VERY_VERBOSE_LOGGING
86#define ALOGVV ALOGV
87#else
88#define ALOGVV(a...) do { } while(0)
89#endif
90
Andy Hung6770c6f2015-04-07 13:43:36 -070091// TODO: Move these macro/inlines to a header file.
Glenn Kasten49d00ad2014-07-21 11:22:03 -070092#define max(a, b) ((a) > (b) ? (a) : (b))
Andy Hung6770c6f2015-04-07 13:43:36 -070093template <typename T>
94static inline T min(const T& a, const T& b)
95{
96 return a < b ? a : b;
97}
Glenn Kasten49d00ad2014-07-21 11:22:03 -070098
Andy Hungd330ee42015-04-20 13:23:41 -070099#ifndef ARRAY_SIZE
100#define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
101#endif
102
Eric Laurent81784c32012-11-19 14:55:58 -0800103namespace android {
104
105// retry counts for buffer fill timeout
106// 50 * ~20msecs = 1 second
107static const int8_t kMaxTrackRetries = 50;
108static const int8_t kMaxTrackStartupRetries = 50;
109// allow less retry attempts on direct output thread.
110// direct outputs can be a scarce resource in audio hardware and should
111// be released as quickly as possible.
112static const int8_t kMaxTrackRetriesDirect = 2;
113
114// don't warn about blocked writes or record buffer overflows more often than this
115static const nsecs_t kWarningThrottleNs = seconds(5);
116
117// RecordThread loop sleep time upon application overrun or audio HAL read error
118static const int kRecordThreadSleepUs = 5000;
119
Eric Laurent10351942014-05-08 18:49:52 -0700120// maximum time to wait in sendConfigEvent_l() for a status to be received
121static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800122
123// minimum sleep time for the mixer thread loop when tracks are active but in underrun
124static const uint32_t kMinThreadSleepTimeUs = 5000;
125// maximum divider applied to the active sleep time in the mixer thread loop
126static const uint32_t kMaxThreadSleepTimeShift = 2;
127
Andy Hung09a50072014-02-27 14:30:47 -0800128// minimum normal sink buffer size, expressed in milliseconds rather than frames
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700129// FIXME This should be based on experimentally observed scheduling jitter
Andy Hung09a50072014-02-27 14:30:47 -0800130static const uint32_t kMinNormalSinkBufferSizeMs = 20;
131// maximum normal sink buffer size
132static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800133
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700134// minimum capture buffer size in milliseconds to _not_ need a fast capture thread
135// FIXME This should be based on experimentally observed scheduling jitter
136static const uint32_t kMinNormalCaptureBufferSizeMs = 12;
137
Eric Laurent972a1732013-09-04 09:42:59 -0700138// Offloaded output thread standby delay: allows track transition without going to standby
139static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
140
Eric Laurent81784c32012-11-19 14:55:58 -0800141// Whether to use fast mixer
142static const enum {
143 FastMixer_Never, // never initialize or use: for debugging only
144 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
145 // normal mixer multiplier is 1
146 FastMixer_Static, // initialize if needed, then use all the time if initialized,
147 // multiplier is calculated based on min & max normal mixer buffer size
148 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
149 // multiplier is calculated based on min & max normal mixer buffer size
150 // FIXME for FastMixer_Dynamic:
151 // Supporting this option will require fixing HALs that can't handle large writes.
152 // For example, one HAL implementation returns an error from a large write,
153 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
154 // We could either fix the HAL implementations, or provide a wrapper that breaks
155 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
156} kUseFastMixer = FastMixer_Static;
157
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700158// Whether to use fast capture
159static const enum {
160 FastCapture_Never, // never initialize or use: for debugging only
161 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
162 FastCapture_Static, // initialize if needed, then use all the time if initialized
163} kUseFastCapture = FastCapture_Static;
164
Eric Laurent81784c32012-11-19 14:55:58 -0800165// Priorities for requestPriority
166static const int kPriorityAudioApp = 2;
167static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700168static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800169
170// IAudioFlinger::createTrack() reports back to client the total size of shared memory area
171// for the track. The client then sub-divides this into smaller buffers for its use.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800172// Currently the client uses N-buffering by default, but doesn't tell us about the value of N.
173// So for now we just assume that client is double-buffered for fast tracks.
174// FIXME It would be better for client to tell AudioFlinger the value of N,
175// so AudioFlinger could allocate the right amount of memory.
Eric Laurent81784c32012-11-19 14:55:58 -0800176// See the client's minBufCount and mNotificationFramesAct calculations for details.
Glenn Kasten03490092014-05-27 12:30:54 -0700177
178// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800179static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800180
Glenn Kasten03490092014-05-27 12:30:54 -0700181// The minimum and maximum allowed values
182static const int kFastTrackMultiplierMin = 1;
183static const int kFastTrackMultiplierMax = 2;
184
185// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
186static int sFastTrackMultiplier = kFastTrackMultiplier;
187
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700188// See Thread::readOnlyHeap().
189// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
190// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
191// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Glenn Kasten9f81de32014-07-27 15:02:23 -0700192static const size_t kRecordThreadReadOnlyHeapSize = 0x2000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700193
Eric Laurent81784c32012-11-19 14:55:58 -0800194// ----------------------------------------------------------------------------
195
Glenn Kasten03490092014-05-27 12:30:54 -0700196static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
197
198static void sFastTrackMultiplierInit()
199{
200 char value[PROPERTY_VALUE_MAX];
201 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
202 char *endptr;
203 unsigned long ul = strtoul(value, &endptr, 0);
204 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
205 sFastTrackMultiplier = (int) ul;
206 }
207 }
208}
209
210// ----------------------------------------------------------------------------
211
Eric Laurent81784c32012-11-19 14:55:58 -0800212#ifdef ADD_BATTERY_DATA
213// To collect the amplifier usage
214static void addBatteryData(uint32_t params) {
215 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
216 if (service == NULL) {
217 // it already logged
218 return;
219 }
220
221 service->addBatteryData(params);
222}
223#endif
224
225
226// ----------------------------------------------------------------------------
227// CPU Stats
228// ----------------------------------------------------------------------------
229
230class CpuStats {
231public:
232 CpuStats();
233 void sample(const String8 &title);
234#ifdef DEBUG_CPU_USAGE
235private:
236 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
237 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
238
239 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
240
241 int mCpuNum; // thread's current CPU number
242 int mCpukHz; // frequency of thread's current CPU in kHz
243#endif
244};
245
246CpuStats::CpuStats()
247#ifdef DEBUG_CPU_USAGE
248 : mCpuNum(-1), mCpukHz(-1)
249#endif
250{
251}
252
Glenn Kasten0f11b512014-01-31 16:18:54 -0800253void CpuStats::sample(const String8 &title
254#ifndef DEBUG_CPU_USAGE
255 __unused
256#endif
257 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800258#ifdef DEBUG_CPU_USAGE
259 // get current thread's delta CPU time in wall clock ns
260 double wcNs;
261 bool valid = mCpuUsage.sampleAndEnable(wcNs);
262
263 // record sample for wall clock statistics
264 if (valid) {
265 mWcStats.sample(wcNs);
266 }
267
268 // get the current CPU number
269 int cpuNum = sched_getcpu();
270
271 // get the current CPU frequency in kHz
272 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
273
274 // check if either CPU number or frequency changed
275 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
276 mCpuNum = cpuNum;
277 mCpukHz = cpukHz;
278 // ignore sample for purposes of cycles
279 valid = false;
280 }
281
282 // if no change in CPU number or frequency, then record sample for cycle statistics
283 if (valid && mCpukHz > 0) {
284 double cycles = wcNs * cpukHz * 0.000001;
285 mHzStats.sample(cycles);
286 }
287
288 unsigned n = mWcStats.n();
289 // mCpuUsage.elapsed() is expensive, so don't call it every loop
290 if ((n & 127) == 1) {
291 long long elapsed = mCpuUsage.elapsed();
292 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
293 double perLoop = elapsed / (double) n;
294 double perLoop100 = perLoop * 0.01;
295 double perLoop1k = perLoop * 0.001;
296 double mean = mWcStats.mean();
297 double stddev = mWcStats.stddev();
298 double minimum = mWcStats.minimum();
299 double maximum = mWcStats.maximum();
300 double meanCycles = mHzStats.mean();
301 double stddevCycles = mHzStats.stddev();
302 double minCycles = mHzStats.minimum();
303 double maxCycles = mHzStats.maximum();
304 mCpuUsage.resetElapsed();
305 mWcStats.reset();
306 mHzStats.reset();
307 ALOGD("CPU usage for %s over past %.1f secs\n"
308 " (%u mixer loops at %.1f mean ms per loop):\n"
309 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
310 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
311 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
312 title.string(),
313 elapsed * .000000001, n, perLoop * .000001,
314 mean * .001,
315 stddev * .001,
316 minimum * .001,
317 maximum * .001,
318 mean / perLoop100,
319 stddev / perLoop100,
320 minimum / perLoop100,
321 maximum / perLoop100,
322 meanCycles / perLoop1k,
323 stddevCycles / perLoop1k,
324 minCycles / perLoop1k,
325 maxCycles / perLoop1k);
326
327 }
328 }
329#endif
330};
331
332// ----------------------------------------------------------------------------
333// ThreadBase
334// ----------------------------------------------------------------------------
335
Glenn Kasten97b7b752014-09-28 13:04:24 -0700336// static
337const char *AudioFlinger::ThreadBase::threadTypeToString(AudioFlinger::ThreadBase::type_t type)
338{
339 switch (type) {
340 case MIXER:
341 return "MIXER";
342 case DIRECT:
343 return "DIRECT";
344 case DUPLICATING:
345 return "DUPLICATING";
346 case RECORD:
347 return "RECORD";
348 case OFFLOAD:
349 return "OFFLOAD";
350 default:
351 return "unknown";
352 }
353}
354
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800355String8 devicesToString(audio_devices_t devices)
356{
357 static const struct mapping {
358 audio_devices_t mDevices;
359 const char * mString;
360 } mappingsOut[] = {
Glenn Kasten818da522015-12-02 13:53:26 -0800361 {AUDIO_DEVICE_OUT_EARPIECE, "EARPIECE"},
362 {AUDIO_DEVICE_OUT_SPEAKER, "SPEAKER"},
363 {AUDIO_DEVICE_OUT_WIRED_HEADSET, "WIRED_HEADSET"},
364 {AUDIO_DEVICE_OUT_WIRED_HEADPHONE, "WIRED_HEADPHONE"},
365 {AUDIO_DEVICE_OUT_BLUETOOTH_SCO, "BLUETOOTH_SCO"},
366 {AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET, "BLUETOOTH_SCO_HEADSET"},
367 {AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT, "BLUETOOTH_SCO_CARKIT"},
368 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, "BLUETOOTH_A2DP"},
369 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,"BLUETOOTH_A2DP_HEADPHONES"},
370 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER, "BLUETOOTH_A2DP_SPEAKER"},
371 {AUDIO_DEVICE_OUT_AUX_DIGITAL, "AUX_DIGITAL"},
372 {AUDIO_DEVICE_OUT_HDMI, "HDMI"},
373 {AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET,"ANLG_DOCK_HEADSET"},
374 {AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET,"DGTL_DOCK_HEADSET"},
375 {AUDIO_DEVICE_OUT_USB_ACCESSORY, "USB_ACCESSORY"},
376 {AUDIO_DEVICE_OUT_USB_DEVICE, "USB_DEVICE"},
377 {AUDIO_DEVICE_OUT_TELEPHONY_TX, "TELEPHONY_TX"},
378 {AUDIO_DEVICE_OUT_LINE, "LINE"},
379 {AUDIO_DEVICE_OUT_HDMI_ARC, "HDMI_ARC"},
380 {AUDIO_DEVICE_OUT_SPDIF, "SPDIF"},
381 {AUDIO_DEVICE_OUT_FM, "FM"},
382 {AUDIO_DEVICE_OUT_AUX_LINE, "AUX_LINE"},
383 {AUDIO_DEVICE_OUT_SPEAKER_SAFE, "SPEAKER_SAFE"},
384 {AUDIO_DEVICE_OUT_IP, "IP"},
385 {AUDIO_DEVICE_NONE, "NONE"}, // must be last
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800386 }, mappingsIn[] = {
Glenn Kasten818da522015-12-02 13:53:26 -0800387 {AUDIO_DEVICE_IN_COMMUNICATION, "COMMUNICATION"},
388 {AUDIO_DEVICE_IN_AMBIENT, "AMBIENT"},
389 {AUDIO_DEVICE_IN_BUILTIN_MIC, "BUILTIN_MIC"},
390 {AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET, "BLUETOOTH_SCO_HEADSET"},
391 {AUDIO_DEVICE_IN_WIRED_HEADSET, "WIRED_HEADSET"},
392 {AUDIO_DEVICE_IN_AUX_DIGITAL, "AUX_DIGITAL"},
393 {AUDIO_DEVICE_IN_VOICE_CALL, "VOICE_CALL"},
394 {AUDIO_DEVICE_IN_TELEPHONY_RX, "TELEPHONY_RX"},
395 {AUDIO_DEVICE_IN_BACK_MIC, "BACK_MIC"},
396 {AUDIO_DEVICE_IN_REMOTE_SUBMIX, "REMOTE_SUBMIX"},
397 {AUDIO_DEVICE_IN_ANLG_DOCK_HEADSET, "ANLG_DOCK_HEADSET"},
398 {AUDIO_DEVICE_IN_DGTL_DOCK_HEADSET, "DGTL_DOCK_HEADSET"},
399 {AUDIO_DEVICE_IN_USB_ACCESSORY, "USB_ACCESSORY"},
400 {AUDIO_DEVICE_IN_USB_DEVICE, "USB_DEVICE"},
401 {AUDIO_DEVICE_IN_FM_TUNER, "FM_TUNER"},
402 {AUDIO_DEVICE_IN_TV_TUNER, "TV_TUNER"},
403 {AUDIO_DEVICE_IN_LINE, "LINE"},
404 {AUDIO_DEVICE_IN_SPDIF, "SPDIF"},
405 {AUDIO_DEVICE_IN_BLUETOOTH_A2DP, "BLUETOOTH_A2DP"},
406 {AUDIO_DEVICE_IN_LOOPBACK, "LOOPBACK"},
407 {AUDIO_DEVICE_IN_IP, "IP"},
408 {AUDIO_DEVICE_NONE, "NONE"}, // must be last
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800409 };
410 String8 result;
411 audio_devices_t allDevices = AUDIO_DEVICE_NONE;
412 const mapping *entry;
413 if (devices & AUDIO_DEVICE_BIT_IN) {
414 devices &= ~AUDIO_DEVICE_BIT_IN;
415 entry = mappingsIn;
416 } else {
417 entry = mappingsOut;
418 }
419 for ( ; entry->mDevices != AUDIO_DEVICE_NONE; entry++) {
420 allDevices = (audio_devices_t) (allDevices | entry->mDevices);
421 if (devices & entry->mDevices) {
422 if (!result.isEmpty()) {
423 result.append("|");
424 }
425 result.append(entry->mString);
426 }
427 }
428 if (devices & ~allDevices) {
429 if (!result.isEmpty()) {
430 result.append("|");
431 }
432 result.appendFormat("0x%X", devices & ~allDevices);
433 }
434 if (result.isEmpty()) {
435 result.append(entry->mString);
436 }
437 return result;
438}
439
440String8 inputFlagsToString(audio_input_flags_t flags)
441{
442 static const struct mapping {
443 audio_input_flags_t mFlag;
444 const char * mString;
445 } mappings[] = {
Glenn Kasten818da522015-12-02 13:53:26 -0800446 {AUDIO_INPUT_FLAG_FAST, "FAST"},
447 {AUDIO_INPUT_FLAG_HW_HOTWORD, "HW_HOTWORD"},
448 {AUDIO_INPUT_FLAG_RAW, "RAW"},
449 {AUDIO_INPUT_FLAG_SYNC, "SYNC"},
450 {AUDIO_INPUT_FLAG_NONE, "NONE"}, // must be last
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800451 };
452 String8 result;
453 audio_input_flags_t allFlags = AUDIO_INPUT_FLAG_NONE;
454 const mapping *entry;
455 for (entry = mappings; entry->mFlag != AUDIO_INPUT_FLAG_NONE; entry++) {
456 allFlags = (audio_input_flags_t) (allFlags | entry->mFlag);
457 if (flags & entry->mFlag) {
458 if (!result.isEmpty()) {
459 result.append("|");
460 }
461 result.append(entry->mString);
462 }
463 }
464 if (flags & ~allFlags) {
465 if (!result.isEmpty()) {
466 result.append("|");
467 }
468 result.appendFormat("0x%X", flags & ~allFlags);
469 }
470 if (result.isEmpty()) {
471 result.append(entry->mString);
472 }
473 return result;
474}
475
476String8 outputFlagsToString(audio_output_flags_t flags)
Glenn Kasten97b7b752014-09-28 13:04:24 -0700477{
478 static const struct mapping {
479 audio_output_flags_t mFlag;
480 const char * mString;
481 } mappings[] = {
Glenn Kasten818da522015-12-02 13:53:26 -0800482 {AUDIO_OUTPUT_FLAG_DIRECT, "DIRECT"},
483 {AUDIO_OUTPUT_FLAG_PRIMARY, "PRIMARY"},
484 {AUDIO_OUTPUT_FLAG_FAST, "FAST"},
485 {AUDIO_OUTPUT_FLAG_DEEP_BUFFER, "DEEP_BUFFER"},
486 {AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,"COMPRESS_OFFLOAD"},
487 {AUDIO_OUTPUT_FLAG_NON_BLOCKING, "NON_BLOCKING"},
488 {AUDIO_OUTPUT_FLAG_HW_AV_SYNC, "HW_AV_SYNC"},
489 {AUDIO_OUTPUT_FLAG_RAW, "RAW"},
490 {AUDIO_OUTPUT_FLAG_SYNC, "SYNC"},
491 {AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO, "IEC958_NONAUDIO"},
492 {AUDIO_OUTPUT_FLAG_NONE, "NONE"}, // must be last
Glenn Kasten97b7b752014-09-28 13:04:24 -0700493 };
494 String8 result;
495 audio_output_flags_t allFlags = AUDIO_OUTPUT_FLAG_NONE;
496 const mapping *entry;
497 for (entry = mappings; entry->mFlag != AUDIO_OUTPUT_FLAG_NONE; entry++) {
498 allFlags = (audio_output_flags_t) (allFlags | entry->mFlag);
499 if (flags & entry->mFlag) {
500 if (!result.isEmpty()) {
501 result.append("|");
502 }
503 result.append(entry->mString);
504 }
505 }
506 if (flags & ~allFlags) {
507 if (!result.isEmpty()) {
508 result.append("|");
509 }
510 result.appendFormat("0x%X", flags & ~allFlags);
511 }
512 if (result.isEmpty()) {
513 result.append(entry->mString);
514 }
515 return result;
516}
517
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800518const char *sourceToString(audio_source_t source)
519{
520 switch (source) {
521 case AUDIO_SOURCE_DEFAULT: return "default";
522 case AUDIO_SOURCE_MIC: return "mic";
523 case AUDIO_SOURCE_VOICE_UPLINK: return "voice uplink";
524 case AUDIO_SOURCE_VOICE_DOWNLINK: return "voice downlink";
525 case AUDIO_SOURCE_VOICE_CALL: return "voice call";
526 case AUDIO_SOURCE_CAMCORDER: return "camcorder";
527 case AUDIO_SOURCE_VOICE_RECOGNITION: return "voice recognition";
528 case AUDIO_SOURCE_VOICE_COMMUNICATION: return "voice communication";
529 case AUDIO_SOURCE_REMOTE_SUBMIX: return "remote submix";
530 case AUDIO_SOURCE_FM_TUNER: return "FM tuner";
531 case AUDIO_SOURCE_HOTWORD: return "hotword";
532 default: return "unknown";
533 }
534}
535
Eric Laurent81784c32012-11-19 14:55:58 -0800536AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -0700537 audio_devices_t outDevice, audio_devices_t inDevice, type_t type, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -0800538 : Thread(false /*canCallJava*/),
539 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700540 mAudioFlinger(audioFlinger),
Glenn Kasten70949c42013-08-06 07:40:12 -0700541 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800542 // are set by PlaybackThread::readOutputParameters_l() or
543 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700544 //FIXME: mStandby should be true here. Is this some kind of hack?
Eric Laurent81784c32012-11-19 14:55:58 -0800545 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700546 mPrevOutDevice(AUDIO_DEVICE_NONE), mPrevInDevice(AUDIO_DEVICE_NONE),
547 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Eric Laurent81784c32012-11-19 14:55:58 -0800548 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700549 mDeathRecipient(new PMDeathRecipient(this)),
Wei Jia3f273d12015-11-24 09:06:49 -0800550 mSystemReady(systemReady),
551 mNotifiedBatteryStart(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800552{
Eric Laurent296fb132015-05-01 11:38:42 -0700553 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800554}
555
556AudioFlinger::ThreadBase::~ThreadBase()
557{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700558 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700559 mConfigEvents.clear();
560
Eric Laurent81784c32012-11-19 14:55:58 -0800561 // do not lock the mutex in destructor
562 releaseWakeLock_l();
563 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800564 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800565 binder->unlinkToDeath(mDeathRecipient);
566 }
567}
568
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700569status_t AudioFlinger::ThreadBase::readyToRun()
570{
571 status_t status = initCheck();
572 if (status == NO_ERROR) {
573 ALOGI("AudioFlinger's thread %p ready to run", this);
574 } else {
575 ALOGE("No working audio driver found.");
576 }
577 return status;
578}
579
Eric Laurent81784c32012-11-19 14:55:58 -0800580void AudioFlinger::ThreadBase::exit()
581{
582 ALOGV("ThreadBase::exit");
583 // do any cleanup required for exit to succeed
584 preExit();
585 {
586 // This lock prevents the following race in thread (uniprocessor for illustration):
587 // if (!exitPending()) {
588 // // context switch from here to exit()
589 // // exit() calls requestExit(), what exitPending() observes
590 // // exit() calls signal(), which is dropped since no waiters
591 // // context switch back from exit() to here
592 // mWaitWorkCV.wait(...);
593 // // now thread is hung
594 // }
595 AutoMutex lock(mLock);
596 requestExit();
597 mWaitWorkCV.broadcast();
598 }
599 // When Thread::requestExitAndWait is made virtual and this method is renamed to
600 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
601 requestExitAndWait();
602}
603
604status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
605{
606 status_t status;
607
608 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
609 Mutex::Autolock _l(mLock);
610
Eric Laurent10351942014-05-08 18:49:52 -0700611 return sendSetParameterConfigEvent_l(keyValuePairs);
612}
613
614// sendConfigEvent_l() must be called with ThreadBase::mLock held
615// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
616status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
617{
618 status_t status = NO_ERROR;
619
Eric Laurent72e3f392015-05-20 14:43:50 -0700620 if (event->mRequiresSystemReady && !mSystemReady) {
621 event->mWaitStatus = false;
622 mPendingConfigEvents.add(event);
623 return status;
624 }
Eric Laurent10351942014-05-08 18:49:52 -0700625 mConfigEvents.add(event);
626 ALOGV("sendConfigEvent_l() num events %d event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800627 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700628 mLock.unlock();
629 {
630 Mutex::Autolock _l(event->mLock);
631 while (event->mWaitStatus) {
632 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
633 event->mStatus = TIMED_OUT;
634 event->mWaitStatus = false;
635 }
636 }
637 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800638 }
Eric Laurent10351942014-05-08 18:49:52 -0700639 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800640 return status;
641}
642
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700643void AudioFlinger::ThreadBase::sendIoConfigEvent(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800644{
645 Mutex::Autolock _l(mLock);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700646 sendIoConfigEvent_l(event, pid);
Eric Laurent81784c32012-11-19 14:55:58 -0800647}
648
649// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700650void AudioFlinger::ThreadBase::sendIoConfigEvent_l(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800651{
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700652 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid);
Eric Laurent10351942014-05-08 18:49:52 -0700653 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800654}
655
Eric Laurent72e3f392015-05-20 14:43:50 -0700656void AudioFlinger::ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio)
657{
658 Mutex::Autolock _l(mLock);
659 sendPrioConfigEvent_l(pid, tid, prio);
660}
661
Eric Laurent81784c32012-11-19 14:55:58 -0800662// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
663void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
664{
Eric Laurent10351942014-05-08 18:49:52 -0700665 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio);
666 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800667}
668
Eric Laurent10351942014-05-08 18:49:52 -0700669// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
670status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800671{
Eric Laurent10351942014-05-08 18:49:52 -0700672 sp<ConfigEvent> configEvent = (ConfigEvent *)new SetParameterConfigEvent(keyValuePair);
673 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700674}
675
Eric Laurent1c333e22014-05-20 10:48:17 -0700676status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
677 const struct audio_patch *patch,
678 audio_patch_handle_t *handle)
679{
680 Mutex::Autolock _l(mLock);
681 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
682 status_t status = sendConfigEvent_l(configEvent);
683 if (status == NO_ERROR) {
684 CreateAudioPatchConfigEventData *data =
685 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
686 *handle = data->mHandle;
687 }
688 return status;
689}
690
691status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
692 const audio_patch_handle_t handle)
693{
694 Mutex::Autolock _l(mLock);
695 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
696 return sendConfigEvent_l(configEvent);
697}
698
699
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700700// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700701void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700702{
Eric Laurent10351942014-05-08 18:49:52 -0700703 bool configChanged = false;
704
Eric Laurent81784c32012-11-19 14:55:58 -0800705 while (!mConfigEvents.isEmpty()) {
Eric Laurent10351942014-05-08 18:49:52 -0700706 ALOGV("processConfigEvents_l() remaining events %d", mConfigEvents.size());
707 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800708 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700709 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700710 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700711 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
712 // FIXME Need to understand why this has to be done asynchronously
713 int err = requestPriority(data->mPid, data->mTid, data->mPrio,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700714 true /*asynchronous*/);
715 if (err != 0) {
716 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700717 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700718 }
719 } break;
720 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700721 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700722 ioConfigChanged(data->mEvent, data->mPid);
Eric Laurent10351942014-05-08 18:49:52 -0700723 } break;
724 case CFG_EVENT_SET_PARAMETER: {
725 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
726 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
727 configChanged = true;
Glenn Kastend5418eb2013-08-14 13:11:06 -0700728 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700729 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700730 case CFG_EVENT_CREATE_AUDIO_PATCH: {
731 CreateAudioPatchConfigEventData *data =
732 (CreateAudioPatchConfigEventData *)event->mData.get();
733 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
734 } break;
735 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
736 ReleaseAudioPatchConfigEventData *data =
737 (ReleaseAudioPatchConfigEventData *)event->mData.get();
738 event->mStatus = releaseAudioPatch_l(data->mHandle);
739 } break;
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700740 default:
Eric Laurent10351942014-05-08 18:49:52 -0700741 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700742 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800743 }
Eric Laurent10351942014-05-08 18:49:52 -0700744 {
745 Mutex::Autolock _l(event->mLock);
746 if (event->mWaitStatus) {
747 event->mWaitStatus = false;
748 event->mCond.signal();
749 }
750 }
751 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
752 }
753
754 if (configChanged) {
755 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800756 }
Eric Laurent81784c32012-11-19 14:55:58 -0800757}
758
Marco Nelissenb2208842014-02-07 14:00:50 -0800759String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
760 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700761 const audio_channel_representation_t representation =
762 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700763
764 switch (representation) {
765 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
766 if (output) {
767 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
768 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
769 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
770 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
771 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
772 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
773 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
774 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
775 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
776 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
777 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
778 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
779 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
780 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
781 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
782 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
783 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
784 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
785 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
786 } else {
787 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
788 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
789 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
790 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
791 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
792 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
793 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
794 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
795 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
796 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
797 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
798 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
799 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
800 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
801 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
802 }
803 const int len = s.length();
804 if (len > 2) {
805 char *str = s.lockBuffer(len); // needed?
806 s.unlockBuffer(len - 2); // remove trailing ", "
807 }
808 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800809 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700810 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
811 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
812 return s;
813 default:
814 s.appendFormat("unknown mask, representation:%d bits:%#x",
815 representation, audio_channel_mask_get_bits(mask));
816 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800817 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800818}
819
Glenn Kasten0f11b512014-01-31 16:18:54 -0800820void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800821{
822 const size_t SIZE = 256;
823 char buffer[SIZE];
824 String8 result;
825
826 bool locked = AudioFlinger::dumpTryLock(mLock);
827 if (!locked) {
Glenn Kasten97b7b752014-09-28 13:04:24 -0700828 dprintf(fd, "thread %p may be deadlocked\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -0800829 }
830
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800831 dprintf(fd, " Thread name: %s\n", mThreadName);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700832 dprintf(fd, " I/O handle: %d\n", mId);
833 dprintf(fd, " TID: %d\n", getTid());
834 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700835 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700836 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700837 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat));
Elliott Hughes87cebad2014-05-22 10:14:43 -0700838 dprintf(fd, " HAL buffer size: %u bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700839 dprintf(fd, " Channel count: %u\n", mChannelCount);
840 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800841 channelMaskToString(mChannelMask, mType != RECORD).string());
Glenn Kastenf87c2f52015-08-21 08:03:57 -0700842 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat, formatToString(mFormat));
843 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700844 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800845 size_t numConfig = mConfigEvents.size();
846 if (numConfig) {
847 for (size_t i = 0; i < numConfig; i++) {
848 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700849 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800850 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700851 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800852 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700853 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800854 }
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800855 dprintf(fd, " Output device: %#x (%s)\n", mOutDevice, devicesToString(mOutDevice).string());
856 dprintf(fd, " Input device: %#x (%s)\n", mInDevice, devicesToString(mInDevice).string());
857 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, sourceToString(mAudioSource));
Eric Laurent81784c32012-11-19 14:55:58 -0800858
859 if (locked) {
860 mLock.unlock();
861 }
862}
863
864void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
865{
866 const size_t SIZE = 256;
867 char buffer[SIZE];
868 String8 result;
869
Marco Nelissenb2208842014-02-07 14:00:50 -0800870 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000871 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800872 write(fd, buffer, strlen(buffer));
873
Marco Nelissenb2208842014-02-07 14:00:50 -0800874 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800875 sp<EffectChain> chain = mEffectChains[i];
876 if (chain != 0) {
877 chain->dump(fd, args);
878 }
879 }
880}
881
Marco Nelissene14a5d62013-10-03 08:51:24 -0700882void AudioFlinger::ThreadBase::acquireWakeLock(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800883{
884 Mutex::Autolock _l(mLock);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700885 acquireWakeLock_l(uid);
Eric Laurent81784c32012-11-19 14:55:58 -0800886}
887
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100888String16 AudioFlinger::ThreadBase::getWakeLockTag()
889{
890 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -0800891 case MIXER:
892 return String16("AudioMix");
893 case DIRECT:
894 return String16("AudioDirectOut");
895 case DUPLICATING:
896 return String16("AudioDup");
897 case RECORD:
898 return String16("AudioIn");
899 case OFFLOAD:
900 return String16("AudioOffload");
901 default:
902 ALOG_ASSERT(false);
903 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100904 }
905}
906
Marco Nelissene14a5d62013-10-03 08:51:24 -0700907void AudioFlinger::ThreadBase::acquireWakeLock_l(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800908{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800909 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800910 if (mPowerManager != 0) {
911 sp<IBinder> binder = new BBinder();
Marco Nelissene14a5d62013-10-03 08:51:24 -0700912 status_t status;
913 if (uid >= 0) {
Eric Laurent547789d2013-10-04 11:46:55 -0700914 status = mPowerManager->acquireWakeLockWithUid(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700915 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100916 getWakeLockTag(),
Marco Nelissene14a5d62013-10-03 08:51:24 -0700917 String16("media"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700918 uid,
919 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700920 } else {
Eric Laurent547789d2013-10-04 11:46:55 -0700921 status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700922 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100923 getWakeLockTag(),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700924 String16("media"),
925 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700926 }
Eric Laurent81784c32012-11-19 14:55:58 -0800927 if (status == NO_ERROR) {
928 mWakeLockToken = binder;
929 }
Glenn Kastend7dca052015-03-05 16:05:54 -0800930 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Eric Laurent81784c32012-11-19 14:55:58 -0800931 }
Wei Jia3f273d12015-11-24 09:06:49 -0800932
933 if (!mNotifiedBatteryStart) {
934 BatteryNotifier::getInstance().noteStartAudio();
935 mNotifiedBatteryStart = true;
936 }
Eric Laurent81784c32012-11-19 14:55:58 -0800937}
938
939void AudioFlinger::ThreadBase::releaseWakeLock()
940{
941 Mutex::Autolock _l(mLock);
942 releaseWakeLock_l();
943}
944
945void AudioFlinger::ThreadBase::releaseWakeLock_l()
946{
947 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800948 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -0800949 if (mPowerManager != 0) {
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700950 mPowerManager->releaseWakeLock(mWakeLockToken, 0,
951 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800952 }
953 mWakeLockToken.clear();
954 }
Wei Jia3f273d12015-11-24 09:06:49 -0800955
956 if (mNotifiedBatteryStart) {
957 BatteryNotifier::getInstance().noteStopAudio();
958 mNotifiedBatteryStart = false;
959 }
Eric Laurent81784c32012-11-19 14:55:58 -0800960}
961
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800962void AudioFlinger::ThreadBase::updateWakeLockUids(const SortedVector<int> &uids) {
963 Mutex::Autolock _l(mLock);
964 updateWakeLockUids_l(uids);
965}
966
967void AudioFlinger::ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -0700968 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800969 // use checkService() to avoid blocking if power service is not up yet
970 sp<IBinder> binder =
971 defaultServiceManager()->checkService(String16("power"));
972 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800973 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800974 } else {
975 mPowerManager = interface_cast<IPowerManager>(binder);
976 binder->linkToDeath(mDeathRecipient);
977 }
978 }
979}
980
981void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<int> &uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800982 getPowerManager_l();
983 if (mWakeLockToken == NULL) {
984 ALOGE("no wake lock to update!");
985 return;
986 }
987 if (mPowerManager != 0) {
988 sp<IBinder> binder = new BBinder();
989 status_t status;
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700990 status = mPowerManager->updateWakeLockUids(mWakeLockToken, uids.size(), uids.array(),
991 true /* FIXME force oneway contrary to .aidl */);
Glenn Kastend7dca052015-03-05 16:05:54 -0800992 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800993 }
994}
995
Eric Laurent81784c32012-11-19 14:55:58 -0800996void AudioFlinger::ThreadBase::clearPowerManager()
997{
998 Mutex::Autolock _l(mLock);
999 releaseWakeLock_l();
1000 mPowerManager.clear();
1001}
1002
Glenn Kasten0f11b512014-01-31 16:18:54 -08001003void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001004{
1005 sp<ThreadBase> thread = mThread.promote();
1006 if (thread != 0) {
1007 thread->clearPowerManager();
1008 }
1009 ALOGW("power manager service died !!!");
1010}
1011
1012void AudioFlinger::ThreadBase::setEffectSuspended(
1013 const effect_uuid_t *type, bool suspend, int sessionId)
1014{
1015 Mutex::Autolock _l(mLock);
1016 setEffectSuspended_l(type, suspend, sessionId);
1017}
1018
1019void AudioFlinger::ThreadBase::setEffectSuspended_l(
1020 const effect_uuid_t *type, bool suspend, int sessionId)
1021{
1022 sp<EffectChain> chain = getEffectChain_l(sessionId);
1023 if (chain != 0) {
1024 if (type != NULL) {
1025 chain->setEffectSuspended_l(type, suspend);
1026 } else {
1027 chain->setEffectSuspendedAll_l(suspend);
1028 }
1029 }
1030
1031 updateSuspendedSessions_l(type, suspend, sessionId);
1032}
1033
1034void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1035{
1036 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1037 if (index < 0) {
1038 return;
1039 }
1040
1041 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1042 mSuspendedSessions.valueAt(index);
1043
1044 for (size_t i = 0; i < sessionEffects.size(); i++) {
1045 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
1046 for (int j = 0; j < desc->mRefCount; j++) {
1047 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1048 chain->setEffectSuspendedAll_l(true);
1049 } else {
1050 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1051 desc->mType.timeLow);
1052 chain->setEffectSuspended_l(&desc->mType, true);
1053 }
1054 }
1055 }
1056}
1057
1058void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1059 bool suspend,
1060 int sessionId)
1061{
1062 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1063
1064 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1065
1066 if (suspend) {
1067 if (index >= 0) {
1068 sessionEffects = mSuspendedSessions.valueAt(index);
1069 } else {
1070 mSuspendedSessions.add(sessionId, sessionEffects);
1071 }
1072 } else {
1073 if (index < 0) {
1074 return;
1075 }
1076 sessionEffects = mSuspendedSessions.valueAt(index);
1077 }
1078
1079
1080 int key = EffectChain::kKeyForSuspendAll;
1081 if (type != NULL) {
1082 key = type->timeLow;
1083 }
1084 index = sessionEffects.indexOfKey(key);
1085
1086 sp<SuspendedSessionDesc> desc;
1087 if (suspend) {
1088 if (index >= 0) {
1089 desc = sessionEffects.valueAt(index);
1090 } else {
1091 desc = new SuspendedSessionDesc();
1092 if (type != NULL) {
1093 desc->mType = *type;
1094 }
1095 sessionEffects.add(key, desc);
1096 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1097 }
1098 desc->mRefCount++;
1099 } else {
1100 if (index < 0) {
1101 return;
1102 }
1103 desc = sessionEffects.valueAt(index);
1104 if (--desc->mRefCount == 0) {
1105 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1106 sessionEffects.removeItemsAt(index);
1107 if (sessionEffects.isEmpty()) {
1108 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1109 sessionId);
1110 mSuspendedSessions.removeItem(sessionId);
1111 }
1112 }
1113 }
1114 if (!sessionEffects.isEmpty()) {
1115 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1116 }
1117}
1118
1119void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1120 bool enabled,
1121 int sessionId)
1122{
1123 Mutex::Autolock _l(mLock);
1124 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1125}
1126
1127void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1128 bool enabled,
1129 int sessionId)
1130{
1131 if (mType != RECORD) {
1132 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1133 // another session. This gives the priority to well behaved effect control panels
1134 // and applications not using global effects.
1135 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1136 // global effects
1137 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
1138 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1139 }
1140 }
1141
1142 sp<EffectChain> chain = getEffectChain_l(sessionId);
1143 if (chain != 0) {
1144 chain->checkSuspendOnEffectEnabled(effect, enabled);
1145 }
1146}
1147
1148// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1149sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1150 const sp<AudioFlinger::Client>& client,
1151 const sp<IEffectClient>& effectClient,
1152 int32_t priority,
1153 int sessionId,
1154 effect_descriptor_t *desc,
1155 int *enabled,
Glenn Kasten9156ef32013-08-06 15:39:08 -07001156 status_t *status)
Eric Laurent81784c32012-11-19 14:55:58 -08001157{
1158 sp<EffectModule> effect;
1159 sp<EffectHandle> handle;
1160 status_t lStatus;
1161 sp<EffectChain> chain;
1162 bool chainCreated = false;
1163 bool effectCreated = false;
1164 bool effectRegistered = false;
1165
1166 lStatus = initCheck();
1167 if (lStatus != NO_ERROR) {
1168 ALOGW("createEffect_l() Audio driver not initialized.");
1169 goto Exit;
1170 }
1171
Andy Hung98ef9782014-03-04 14:46:50 -08001172 // Reject any effect on Direct output threads for now, since the format of
1173 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1174 if (mType == DIRECT) {
1175 ALOGW("createEffect_l() Cannot add effect %s on Direct output type thread %s",
Glenn Kastend7dca052015-03-05 16:05:54 -08001176 desc->name, mThreadName);
Andy Hung98ef9782014-03-04 14:46:50 -08001177 lStatus = BAD_VALUE;
1178 goto Exit;
1179 }
1180
Andy Hung389cfdb2014-08-07 17:49:53 -07001181 // Reject any effect on mixer or duplicating multichannel sinks.
Andy Hung9a592762014-07-21 21:56:01 -07001182 // TODO: fix both format and multichannel issues with effects.
Andy Hung389cfdb2014-08-07 17:49:53 -07001183 if ((mType == MIXER || mType == DUPLICATING) && mChannelCount != FCC_2) {
1184 ALOGW("createEffect_l() Cannot add effect %s for multichannel(%d) %s threads",
1185 desc->name, mChannelCount, mType == MIXER ? "MIXER" : "DUPLICATING");
Andy Hung9a592762014-07-21 21:56:01 -07001186 lStatus = BAD_VALUE;
1187 goto Exit;
1188 }
1189
Eric Laurent5baf2af2013-09-12 17:37:00 -07001190 // Allow global effects only on offloaded and mixer threads
1191 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1192 switch (mType) {
1193 case MIXER:
1194 case OFFLOAD:
1195 break;
1196 case DIRECT:
1197 case DUPLICATING:
1198 case RECORD:
1199 default:
Glenn Kastend7dca052015-03-05 16:05:54 -08001200 ALOGW("createEffect_l() Cannot add global effect %s on thread %s",
1201 desc->name, mThreadName);
Eric Laurent5baf2af2013-09-12 17:37:00 -07001202 lStatus = BAD_VALUE;
1203 goto Exit;
1204 }
Eric Laurent81784c32012-11-19 14:55:58 -08001205 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07001206
Eric Laurent81784c32012-11-19 14:55:58 -08001207 // Only Pre processor effects are allowed on input threads and only on input threads
1208 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
1209 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
1210 desc->name, desc->flags, mType);
1211 lStatus = BAD_VALUE;
1212 goto Exit;
1213 }
1214
1215 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1216
1217 { // scope for mLock
1218 Mutex::Autolock _l(mLock);
1219
1220 // check for existing effect chain with the requested audio session
1221 chain = getEffectChain_l(sessionId);
1222 if (chain == 0) {
1223 // create a new chain for this session
1224 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1225 chain = new EffectChain(this, sessionId);
1226 addEffectChain_l(chain);
1227 chain->setStrategy(getStrategyForSession_l(sessionId));
1228 chainCreated = true;
1229 } else {
1230 effect = chain->getEffectFromDesc_l(desc);
1231 }
1232
1233 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1234
1235 if (effect == 0) {
1236 int id = mAudioFlinger->nextUniqueId();
1237 // Check CPU and memory usage
1238 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
1239 if (lStatus != NO_ERROR) {
1240 goto Exit;
1241 }
1242 effectRegistered = true;
1243 // create a new effect module if none present in the chain
1244 effect = new EffectModule(this, chain, desc, id, sessionId);
1245 lStatus = effect->status();
1246 if (lStatus != NO_ERROR) {
1247 goto Exit;
1248 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07001249 effect->setOffloaded(mType == OFFLOAD, mId);
1250
Eric Laurent81784c32012-11-19 14:55:58 -08001251 lStatus = chain->addEffect_l(effect);
1252 if (lStatus != NO_ERROR) {
1253 goto Exit;
1254 }
1255 effectCreated = true;
1256
1257 effect->setDevice(mOutDevice);
1258 effect->setDevice(mInDevice);
1259 effect->setMode(mAudioFlinger->getMode());
1260 effect->setAudioSource(mAudioSource);
1261 }
1262 // create effect handle and connect it to effect module
1263 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001264 lStatus = handle->initCheck();
1265 if (lStatus == OK) {
1266 lStatus = effect->addHandle(handle.get());
1267 }
Eric Laurent81784c32012-11-19 14:55:58 -08001268 if (enabled != NULL) {
1269 *enabled = (int)effect->isEnabled();
1270 }
1271 }
1272
1273Exit:
1274 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1275 Mutex::Autolock _l(mLock);
1276 if (effectCreated) {
1277 chain->removeEffect_l(effect);
1278 }
1279 if (effectRegistered) {
1280 AudioSystem::unregisterEffect(effect->id());
1281 }
1282 if (chainCreated) {
1283 removeEffectChain_l(chain);
1284 }
1285 handle.clear();
1286 }
1287
Glenn Kasten9156ef32013-08-06 15:39:08 -07001288 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001289 return handle;
1290}
1291
1292sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
1293{
1294 Mutex::Autolock _l(mLock);
1295 return getEffect_l(sessionId, effectId);
1296}
1297
1298sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
1299{
1300 sp<EffectChain> chain = getEffectChain_l(sessionId);
1301 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1302}
1303
1304// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1305// PlaybackThread::mLock held
1306status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1307{
1308 // check for existing effect chain with the requested audio session
1309 int sessionId = effect->sessionId();
1310 sp<EffectChain> chain = getEffectChain_l(sessionId);
1311 bool chainCreated = false;
1312
Eric Laurent5baf2af2013-09-12 17:37:00 -07001313 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
1314 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
1315 this, effect->desc().name, effect->desc().flags);
1316
Eric Laurent81784c32012-11-19 14:55:58 -08001317 if (chain == 0) {
1318 // create a new chain for this session
1319 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1320 chain = new EffectChain(this, sessionId);
1321 addEffectChain_l(chain);
1322 chain->setStrategy(getStrategyForSession_l(sessionId));
1323 chainCreated = true;
1324 }
1325 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1326
1327 if (chain->getEffectFromId_l(effect->id()) != 0) {
1328 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1329 this, effect->desc().name, chain.get());
1330 return BAD_VALUE;
1331 }
1332
Eric Laurent5baf2af2013-09-12 17:37:00 -07001333 effect->setOffloaded(mType == OFFLOAD, mId);
1334
Eric Laurent81784c32012-11-19 14:55:58 -08001335 status_t status = chain->addEffect_l(effect);
1336 if (status != NO_ERROR) {
1337 if (chainCreated) {
1338 removeEffectChain_l(chain);
1339 }
1340 return status;
1341 }
1342
1343 effect->setDevice(mOutDevice);
1344 effect->setDevice(mInDevice);
1345 effect->setMode(mAudioFlinger->getMode());
1346 effect->setAudioSource(mAudioSource);
1347 return NO_ERROR;
1348}
1349
1350void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
1351
1352 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
1353 effect_descriptor_t desc = effect->desc();
1354 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1355 detachAuxEffect_l(effect->id());
1356 }
1357
1358 sp<EffectChain> chain = effect->chain().promote();
1359 if (chain != 0) {
1360 // remove effect chain if removing last effect
1361 if (chain->removeEffect_l(effect) == 0) {
1362 removeEffectChain_l(chain);
1363 }
1364 } else {
1365 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1366 }
1367}
1368
1369void AudioFlinger::ThreadBase::lockEffectChains_l(
1370 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1371{
1372 effectChains = mEffectChains;
1373 for (size_t i = 0; i < mEffectChains.size(); i++) {
1374 mEffectChains[i]->lock();
1375 }
1376}
1377
1378void AudioFlinger::ThreadBase::unlockEffectChains(
1379 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1380{
1381 for (size_t i = 0; i < effectChains.size(); i++) {
1382 effectChains[i]->unlock();
1383 }
1384}
1385
1386sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
1387{
1388 Mutex::Autolock _l(mLock);
1389 return getEffectChain_l(sessionId);
1390}
1391
1392sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const
1393{
1394 size_t size = mEffectChains.size();
1395 for (size_t i = 0; i < size; i++) {
1396 if (mEffectChains[i]->sessionId() == sessionId) {
1397 return mEffectChains[i];
1398 }
1399 }
1400 return 0;
1401}
1402
1403void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1404{
1405 Mutex::Autolock _l(mLock);
1406 size_t size = mEffectChains.size();
1407 for (size_t i = 0; i < size; i++) {
1408 mEffectChains[i]->setMode_l(mode);
1409 }
1410}
1411
Eric Laurent83b88082014-06-20 18:31:16 -07001412void AudioFlinger::ThreadBase::getAudioPortConfig(struct audio_port_config *config)
1413{
1414 config->type = AUDIO_PORT_TYPE_MIX;
1415 config->ext.mix.handle = mId;
1416 config->sample_rate = mSampleRate;
1417 config->format = mFormat;
1418 config->channel_mask = mChannelMask;
1419 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1420 AUDIO_PORT_CONFIG_FORMAT;
1421}
1422
Eric Laurent72e3f392015-05-20 14:43:50 -07001423void AudioFlinger::ThreadBase::systemReady()
1424{
1425 Mutex::Autolock _l(mLock);
1426 if (mSystemReady) {
1427 return;
1428 }
1429 mSystemReady = true;
1430
1431 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1432 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1433 }
1434 mPendingConfigEvents.clear();
1435}
1436
Eric Laurent83b88082014-06-20 18:31:16 -07001437
Eric Laurent81784c32012-11-19 14:55:58 -08001438// ----------------------------------------------------------------------------
1439// Playback
1440// ----------------------------------------------------------------------------
1441
1442AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1443 AudioStreamOut* output,
1444 audio_io_handle_t id,
1445 audio_devices_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07001446 type_t type,
1447 bool systemReady)
1448 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type, systemReady),
Andy Hung2098f272014-02-27 14:00:06 -08001449 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001450 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001451 mMixerBuffer(NULL),
1452 mMixerBufferSize(0),
1453 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1454 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001455 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001456 mEffectBuffer(NULL),
1457 mEffectBufferSize(0),
1458 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1459 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001460 mSuspended(0), mBytesWritten(0),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001461 mActiveTracksGeneration(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001462 // mStreamTypes[] initialized in constructor body
1463 mOutput(output),
1464 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
1465 mMixerStatus(MIXER_IDLE),
1466 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001467 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001468 mBytesRemaining(0),
1469 mCurrentWriteLength(0),
1470 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001471 mWriteAckSequence(0),
1472 mDrainSequence(0),
Eric Laurentede6c3b2013-09-19 14:37:46 -07001473 mSignalPending(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001474 mScreenState(AudioFlinger::mScreenState),
1475 // index 0 is reserved for normal mixer's submix
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001476 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1),
Eric Laurentd1f69b02014-12-15 14:33:13 -08001477 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001478 // mLatchD, mLatchQ,
1479 mLatchDValid(false), mLatchQValid(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001480{
Glenn Kastend7dca052015-03-05 16:05:54 -08001481 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1482 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001483
1484 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1485 // it would be safer to explicitly pass initial masterVolume/masterMute as
1486 // parameter.
1487 //
1488 // If the HAL we are using has support for master volume or master mute,
1489 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1490 // and the mute set to false).
1491 mMasterVolume = audioFlinger->masterVolume_l();
1492 mMasterMute = audioFlinger->masterMute_l();
1493 if (mOutput && mOutput->audioHwDev) {
1494 if (mOutput->audioHwDev->canSetMasterVolume()) {
1495 mMasterVolume = 1.0;
1496 }
1497
1498 if (mOutput->audioHwDev->canSetMasterMute()) {
1499 mMasterMute = false;
1500 }
1501 }
1502
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001503 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001504
Eric Laurent223fd5c2014-11-11 13:43:36 -08001505 // ++ operator does not compile
Glenn Kasten66e46352014-01-16 17:44:23 -08001506 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001507 stream = (audio_stream_type_t) (stream + 1)) {
1508 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1509 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1510 }
Eric Laurent81784c32012-11-19 14:55:58 -08001511}
1512
1513AudioFlinger::PlaybackThread::~PlaybackThread()
1514{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001515 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001516 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001517 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001518 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001519}
1520
1521void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1522{
1523 dumpInternals(fd, args);
1524 dumpTracks(fd, args);
1525 dumpEffectChains(fd, args);
1526}
1527
Glenn Kasten0f11b512014-01-31 16:18:54 -08001528void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001529{
1530 const size_t SIZE = 256;
1531 char buffer[SIZE];
1532 String8 result;
1533
Marco Nelissenb2208842014-02-07 14:00:50 -08001534 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001535 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1536 const stream_type_t *st = &mStreamTypes[i];
1537 if (i > 0) {
1538 result.appendFormat(", ");
1539 }
1540 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1541 if (st->mute) {
1542 result.append("M");
1543 }
1544 }
1545 result.append("\n");
1546 write(fd, result.string(), result.length());
1547 result.clear();
1548
Eric Laurent81784c32012-11-19 14:55:58 -08001549 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1550 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001551 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001552 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001553
1554 size_t numtracks = mTracks.size();
1555 size_t numactive = mActiveTracks.size();
Elliott Hughes87cebad2014-05-22 10:14:43 -07001556 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001557 size_t numactiveseen = 0;
1558 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07001559 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08001560 Track::appendDumpHeader(result);
1561 for (size_t i = 0; i < numtracks; ++i) {
1562 sp<Track> track = mTracks[i];
1563 if (track != 0) {
1564 bool active = mActiveTracks.indexOf(track) >= 0;
1565 if (active) {
1566 numactiveseen++;
1567 }
1568 track->dump(buffer, SIZE, active);
1569 result.append(buffer);
1570 }
1571 }
1572 } else {
1573 result.append("\n");
1574 }
1575 if (numactiveseen != numactive) {
1576 // some tracks in the active list were not in the tracks list
1577 snprintf(buffer, SIZE, " The following tracks are in the active list but"
1578 " not in the track list\n");
1579 result.append(buffer);
1580 Track::appendDumpHeader(result);
1581 for (size_t i = 0; i < numactive; ++i) {
1582 sp<Track> track = mActiveTracks[i].promote();
1583 if (track != 0 && mTracks.indexOf(track) < 0) {
1584 track->dump(buffer, SIZE, true);
1585 result.append(buffer);
1586 }
1587 }
1588 }
1589
1590 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001591}
1592
1593void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1594{
Glenn Kasten97b7b752014-09-28 13:04:24 -07001595 dprintf(fd, "\nOutput thread %p type %d (%s):\n", this, type(), threadTypeToString(type()));
Glenn Kasten44182c22015-03-05 17:12:23 -08001596
1597 dumpBase(fd, args);
1598
Elliott Hughes87cebad2014-05-22 10:14:43 -07001599 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
1600 dprintf(fd, " Last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1601 dprintf(fd, " Total writes: %d\n", mNumWrites);
1602 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1603 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1604 dprintf(fd, " Suspend count: %d\n", mSuspended);
1605 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1606 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1607 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1608 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001609 AudioStreamOut *output = mOutput;
1610 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
1611 String8 flagsAsString = outputFlagsToString(flags);
1612 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n", output, flags, flagsAsString.string());
Eric Laurent81784c32012-11-19 14:55:58 -08001613}
1614
1615// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001616
1617void AudioFlinger::PlaybackThread::onFirstRef()
1618{
Glenn Kastend7dca052015-03-05 16:05:54 -08001619 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001620}
1621
1622// ThreadBase virtuals
1623void AudioFlinger::PlaybackThread::preExit()
1624{
1625 ALOGV(" preExit()");
1626 // FIXME this is using hard-coded strings but in the future, this functionality will be
1627 // converted to use audio HAL extensions required to support tunneling
1628 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1629}
1630
1631// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1632sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1633 const sp<AudioFlinger::Client>& client,
1634 audio_stream_type_t streamType,
1635 uint32_t sampleRate,
1636 audio_format_t format,
1637 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001638 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001639 const sp<IMemory>& sharedBuffer,
1640 int sessionId,
1641 IAudioFlinger::track_flags_t *flags,
1642 pid_t tid,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001643 int uid,
Eric Laurent81784c32012-11-19 14:55:58 -08001644 status_t *status)
1645{
Glenn Kasten74935e42013-12-19 08:56:45 -08001646 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001647 sp<Track> track;
1648 status_t lStatus;
1649
1650 bool isTimed = (*flags & IAudioFlinger::TRACK_TIMED) != 0;
1651
1652 // client expresses a preference for FAST, but we get the final say
1653 if (*flags & IAudioFlinger::TRACK_FAST) {
1654 if (
1655 // not timed
1656 (!isTimed) &&
1657 // either of these use cases:
1658 (
1659 // use case 1: shared buffer with any frame count
1660 (
1661 (sharedBuffer != 0)
1662 ) ||
Glenn Kasten1dfe2f92015-03-09 12:03:14 -07001663 // use case 2: frame count is default or at least as large as HAL
Eric Laurent81784c32012-11-19 14:55:58 -08001664 (
Glenn Kasten1dfe2f92015-03-09 12:03:14 -07001665 // we formerly checked for a callback handler (non-0 tid),
1666 // but that is no longer required for TRANSFER_OBTAIN mode
Eric Laurent81784c32012-11-19 14:55:58 -08001667 ((frameCount == 0) ||
Glenn Kastenb5fed682013-12-03 09:06:43 -08001668 (frameCount >= mFrameCount))
Eric Laurent81784c32012-11-19 14:55:58 -08001669 )
1670 ) &&
1671 // PCM data
1672 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07001673 // TODO: extract as a data library function that checks that a computationally
1674 // expensive downmixer is not required: isFastOutputChannelConversion()
Andy Hung9a592762014-07-21 21:56:01 -07001675 (channelMask == mChannelMask ||
Andy Hung1f439e12015-05-19 12:57:41 -07001676 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
1677 (channelMask == AUDIO_CHANNEL_OUT_MONO
1678 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001679 // hardware sample rate
1680 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001681 // normal mixer has an associated fast mixer
1682 hasFastMixer() &&
1683 // there are sufficient fast track slots available
1684 (mFastTrackAvailMask != 0)
1685 // FIXME test that MixerThread for this fast track has a capable output HAL
1686 // FIXME add a permission test also?
1687 ) {
1688 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1689 if (frameCount == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001690 // read the fast track multiplier property the first time it is needed
1691 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1692 if (ok != 0) {
1693 ALOGE("%s pthread_once failed: %d", __func__, ok);
1694 }
1695 frameCount = mFrameCount * sFastTrackMultiplier;
Eric Laurent81784c32012-11-19 14:55:58 -08001696 }
1697 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
1698 frameCount, mFrameCount);
1699 } else {
1700 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
Andy Hung6146c082014-03-18 11:56:15 -07001701 "mFrameCount=%d format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
1702 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001703 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Andy Hung6146c082014-03-18 11:56:15 -07001704 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001705 audio_is_linear_pcm(format),
1706 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
1707 *flags &= ~IAudioFlinger::TRACK_FAST;
Andy Hung0e48d252015-01-26 11:43:15 -08001708 }
1709 }
1710 // For normal PCM streaming tracks, update minimum frame count.
1711 // For compatibility with AudioTrack calculation, buffer depth is forced
1712 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1713 // This is probably too conservative, but legacy application code may depend on it.
1714 // If you change this calculation, also review the start threshold which is related.
1715 if (!(*flags & IAudioFlinger::TRACK_FAST)
1716 && audio_is_linear_pcm(format) && sharedBuffer == 0) {
Andy Hung8edb8dc2015-03-26 19:13:55 -07001717 // this must match AudioTrack.cpp calculateMinFrameCount().
1718 // TODO: Move to a common library
Eric Laurent81784c32012-11-19 14:55:58 -08001719 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1720 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1721 if (minBufCount < 2) {
1722 minBufCount = 2;
1723 }
Andy Hung8edb8dc2015-03-26 19:13:55 -07001724 // For normal mixing tracks, if speed is > 1.0f (normal), AudioTrack
1725 // or the client should compute and pass in a larger buffer request.
Andy Hung0e48d252015-01-26 11:43:15 -08001726 size_t minFrameCount =
Andy Hung8edb8dc2015-03-26 19:13:55 -07001727 minBufCount * sourceFramesNeededWithTimestretch(
1728 sampleRate, mNormalFrameCount,
1729 mSampleRate, AUDIO_TIMESTRETCH_SPEED_NORMAL /*speed*/);
Andy Hung0e48d252015-01-26 11:43:15 -08001730 if (frameCount < minFrameCount) { // including frameCount == 0
Eric Laurent81784c32012-11-19 14:55:58 -08001731 frameCount = minFrameCount;
1732 }
Eric Laurent81784c32012-11-19 14:55:58 -08001733 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001734 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001735
Glenn Kastenc3df8382014-03-13 15:05:25 -07001736 switch (mType) {
1737
1738 case DIRECT:
Glenn Kasten993fa062014-05-02 11:14:34 -07001739 if (audio_is_linear_pcm(format)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001740 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001741 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1742 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001743 sampleRate, format, channelMask, mOutput, mFormat);
1744 lStatus = BAD_VALUE;
1745 goto Exit;
1746 }
1747 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001748 break;
1749
1750 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001751 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001752 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1753 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001754 sampleRate, format, channelMask, mOutput, mFormat);
1755 lStatus = BAD_VALUE;
1756 goto Exit;
1757 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001758 break;
1759
1760 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07001761 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001762 ALOGE("createTrack_l() Bad parameter: format %#x \""
1763 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001764 format, mOutput, mFormat);
1765 lStatus = BAD_VALUE;
1766 goto Exit;
1767 }
Andy Hungcd044842014-08-07 11:04:34 -07001768 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08001769 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1770 lStatus = BAD_VALUE;
1771 goto Exit;
1772 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001773 break;
1774
Eric Laurent81784c32012-11-19 14:55:58 -08001775 }
1776
1777 lStatus = initCheck();
1778 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07001779 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08001780 goto Exit;
1781 }
1782
1783 { // scope for mLock
1784 Mutex::Autolock _l(mLock);
1785
1786 // all tracks in same audio session must share the same routing strategy otherwise
1787 // conflicts will happen when tracks are moved from one output to another by audio policy
1788 // manager
1789 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1790 for (size_t i = 0; i < mTracks.size(); ++i) {
1791 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07001792 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001793 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1794 if (sessionId == t->sessionId() && strategy != actual) {
1795 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1796 strategy, actual);
1797 lStatus = BAD_VALUE;
1798 goto Exit;
1799 }
1800 }
1801 }
1802
1803 if (!isTimed) {
1804 track = new Track(this, client, streamType, sampleRate, format,
Eric Laurent83b88082014-06-20 18:31:16 -07001805 channelMask, frameCount, NULL, sharedBuffer,
1806 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08001807 } else {
1808 track = TimedTrack::create(this, client, streamType, sampleRate, format,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001809 channelMask, frameCount, sharedBuffer, sessionId, uid);
Eric Laurent81784c32012-11-19 14:55:58 -08001810 }
Glenn Kasten03003332013-08-06 15:40:54 -07001811
1812 // new Track always returns non-NULL,
1813 // but TimedTrack::create() is a factory that could fail by returning NULL
1814 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
1815 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08001816 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001817 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08001818 goto Exit;
1819 }
1820 mTracks.add(track);
1821
1822 sp<EffectChain> chain = getEffectChain_l(sessionId);
1823 if (chain != 0) {
1824 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1825 track->setMainBuffer(chain->inBuffer());
1826 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1827 chain->incTrackCnt();
1828 }
1829
1830 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1831 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1832 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1833 // so ask activity manager to do this on our behalf
1834 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1835 }
1836 }
1837
1838 lStatus = NO_ERROR;
1839
1840Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001841 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001842 return track;
1843}
1844
1845uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1846{
1847 return latency;
1848}
1849
1850uint32_t AudioFlinger::PlaybackThread::latency() const
1851{
1852 Mutex::Autolock _l(mLock);
1853 return latency_l();
1854}
1855uint32_t AudioFlinger::PlaybackThread::latency_l() const
1856{
1857 if (initCheck() == NO_ERROR) {
1858 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
1859 } else {
1860 return 0;
1861 }
1862}
1863
1864void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1865{
1866 Mutex::Autolock _l(mLock);
1867 // Don't apply master volume in SW if our HAL can do it for us.
1868 if (mOutput && mOutput->audioHwDev &&
1869 mOutput->audioHwDev->canSetMasterVolume()) {
1870 mMasterVolume = 1.0;
1871 } else {
1872 mMasterVolume = value;
1873 }
1874}
1875
1876void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1877{
1878 Mutex::Autolock _l(mLock);
1879 // Don't apply master mute in SW if our HAL can do it for us.
1880 if (mOutput && mOutput->audioHwDev &&
1881 mOutput->audioHwDev->canSetMasterMute()) {
1882 mMasterMute = false;
1883 } else {
1884 mMasterMute = muted;
1885 }
1886}
1887
1888void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
1889{
1890 Mutex::Autolock _l(mLock);
1891 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001892 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001893}
1894
1895void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
1896{
1897 Mutex::Autolock _l(mLock);
1898 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001899 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001900}
1901
1902float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
1903{
1904 Mutex::Autolock _l(mLock);
1905 return mStreamTypes[stream].volume;
1906}
1907
1908// addTrack_l() must be called with ThreadBase::mLock held
1909status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1910{
1911 status_t status = ALREADY_EXISTS;
1912
1913 // set retry count for buffer fill
1914 track->mRetryCount = kMaxTrackStartupRetries;
1915 if (mActiveTracks.indexOf(track) < 0) {
1916 // the track is newly added, make sure it fills up all its
1917 // buffers before playing. This is to ensure the client will
1918 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07001919 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001920 TrackBase::track_state state = track->mState;
1921 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08001922 status = AudioSystem::startOutput(mId, track->streamType(),
1923 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001924 mLock.lock();
1925 // abort track was stopped/paused while we released the lock
1926 if (state != track->mState) {
1927 if (status == NO_ERROR) {
1928 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08001929 AudioSystem::stopOutput(mId, track->streamType(),
1930 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001931 mLock.lock();
1932 }
1933 return INVALID_OPERATION;
1934 }
1935 // abort if start is rejected by audio policy manager
1936 if (status != NO_ERROR) {
1937 return PERMISSION_DENIED;
1938 }
1939#ifdef ADD_BATTERY_DATA
1940 // to track the speaker usage
1941 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
1942#endif
1943 }
1944
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001945 track->mFillingUpStatus = track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent81784c32012-11-19 14:55:58 -08001946 track->mResetDone = false;
1947 track->mPresentationCompleteFrames = 0;
1948 mActiveTracks.add(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001949 mWakeLockUids.add(track->uid());
1950 mActiveTracksGeneration++;
Eric Laurentfd477972013-10-25 18:10:40 -07001951 mLatestActiveTrack = track;
Eric Laurentd0107bc2013-06-11 14:38:48 -07001952 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1953 if (chain != 0) {
1954 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
1955 track->sessionId());
1956 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08001957 }
1958
1959 status = NO_ERROR;
1960 }
1961
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08001962 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001963 return status;
1964}
1965
Eric Laurentbfb1b832013-01-07 09:53:42 -08001966bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08001967{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001968 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08001969 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001970 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
1971 track->mState = TrackBase::STOPPED;
1972 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08001973 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07001974 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001975 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08001976 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001977
1978 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08001979}
1980
1981void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1982{
1983 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
1984 mTracks.remove(track);
1985 deleteTrackName_l(track->name());
1986 // redundant as track is about to be destroyed, for dumpsys only
1987 track->mName = -1;
1988 if (track->isFastTrack()) {
1989 int index = track->mFastIndex;
1990 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
1991 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1992 mFastTrackAvailMask |= 1 << index;
1993 // redundant as track is about to be destroyed, for dumpsys only
1994 track->mFastIndex = -1;
1995 }
1996 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1997 if (chain != 0) {
1998 chain->decTrackCnt();
1999 }
2000}
2001
Eric Laurentede6c3b2013-09-19 14:37:46 -07002002void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002003{
2004 // Thread could be blocked waiting for async
2005 // so signal it to handle state changes immediately
2006 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
2007 // be lost so we also flag to prevent it blocking on mWaitWorkCV
2008 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002009 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002010}
2011
Eric Laurent81784c32012-11-19 14:55:58 -08002012String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2013{
Eric Laurent81784c32012-11-19 14:55:58 -08002014 Mutex::Autolock _l(mLock);
2015 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07002016 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002017 }
2018
Glenn Kastend8ea6992013-07-16 14:17:15 -07002019 char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
2020 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08002021 free(s);
2022 return out_s8;
2023}
2024
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002025void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002026 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2027 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002028
Eric Laurent73e26b62015-04-27 16:55:58 -07002029 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002030
2031 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002032 case AUDIO_OUTPUT_OPENED:
2033 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002034 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002035 desc->mChannelMask = mChannelMask;
2036 desc->mSamplingRate = mSampleRate;
2037 desc->mFormat = mFormat;
2038 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002039 // AudioFlinger::frameCount(audio_io_handle_t)
Eric Laurent73e26b62015-04-27 16:55:58 -07002040 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002041 break;
2042
Eric Laurent73e26b62015-04-27 16:55:58 -07002043 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002044 default:
2045 break;
2046 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002047 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002048}
2049
Eric Laurentbfb1b832013-01-07 09:53:42 -08002050void AudioFlinger::PlaybackThread::writeCallback()
2051{
2052 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002053 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002054}
2055
2056void AudioFlinger::PlaybackThread::drainCallback()
2057{
2058 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002059 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002060}
2061
Eric Laurent3b4529e2013-09-05 18:09:19 -07002062void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002063{
2064 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002065 // reject out of sequence requests
2066 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2067 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002068 mWaitWorkCV.signal();
2069 }
2070}
2071
Eric Laurent3b4529e2013-09-05 18:09:19 -07002072void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002073{
2074 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002075 // reject out of sequence requests
2076 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
2077 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002078 mWaitWorkCV.signal();
2079 }
2080}
2081
2082// static
2083int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
Glenn Kasten0f11b512014-01-31 16:18:54 -08002084 void *param __unused,
Eric Laurentbfb1b832013-01-07 09:53:42 -08002085 void *cookie)
2086{
2087 AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
2088 ALOGV("asyncCallback() event %d", event);
2089 switch (event) {
2090 case STREAM_CBK_EVENT_WRITE_READY:
2091 me->writeCallback();
2092 break;
2093 case STREAM_CBK_EVENT_DRAIN_READY:
2094 me->drainCallback();
2095 break;
2096 default:
2097 ALOGW("asyncCallback() unknown event %d", event);
2098 break;
2099 }
2100 return 0;
2101}
2102
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002103void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002104{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002105 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Phil Burkca5e6142015-07-14 09:42:29 -07002106 mSampleRate = mOutput->getSampleRate();
2107 mChannelMask = mOutput->getChannelMask();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002108 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002109 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002110 }
Andy Hung9a592762014-07-21 21:56:01 -07002111 if ((mType == MIXER || mType == DUPLICATING)
2112 && !isValidPcmSinkChannelMask(mChannelMask)) {
2113 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2114 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002115 }
Andy Hunge5412692014-05-16 11:25:07 -07002116 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002117
2118 // Get actual HAL format.
Andy Hung463be252014-07-10 16:56:07 -07002119 mHALFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Phil Burkca5e6142015-07-14 09:42:29 -07002120 // Get format from the shim, which will be different than the HAL format
2121 // if playing compressed audio over HDMI passthrough.
2122 mFormat = mOutput->getFormat();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002123 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002124 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002125 }
Andy Hung6146c082014-03-18 11:56:15 -07002126 if ((mType == MIXER || mType == DUPLICATING)
2127 && !isValidPcmSinkFormat(mFormat)) {
2128 LOG_FATAL("HAL format %#x not supported for mixed output",
2129 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002130 }
Phil Burk062e67a2015-02-11 13:40:50 -08002131 mFrameSize = mOutput->getFrameSize();
Glenn Kasten70949c42013-08-06 07:40:12 -07002132 mBufferSize = mOutput->stream->common.get_buffer_size(&mOutput->stream->common);
2133 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002134 if (mFrameCount & 15) {
2135 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
2136 mFrameCount);
2137 }
2138
Eric Laurentbfb1b832013-01-07 09:53:42 -08002139 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
2140 (mOutput->stream->set_callback != NULL)) {
2141 if (mOutput->stream->set_callback(mOutput->stream,
2142 AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
2143 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002144 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002145 }
2146 }
2147
Eric Laurentd1f69b02014-12-15 14:33:13 -08002148 mHwSupportsPause = false;
2149 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
2150 if (mOutput->stream->pause != NULL) {
2151 if (mOutput->stream->resume != NULL) {
2152 mHwSupportsPause = true;
2153 } else {
2154 ALOGW("direct output implements pause but not resume");
2155 }
2156 } else if (mOutput->stream->resume != NULL) {
2157 ALOGW("direct output implements resume but not pause");
2158 }
2159 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002160 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2161 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2162 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002163
Andy Hungfbfc3952015-01-15 13:33:51 -08002164 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2165 // For best precision, we use float instead of the associated output
2166 // device format (typically PCM 16 bit).
2167
2168 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2169 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2170 mBufferSize = mFrameSize * mFrameCount;
2171
2172 // TODO: We currently use the associated output device channel mask and sample rate.
2173 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2174 // (if a valid mask) to avoid premature downmix.
2175 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2176 // instead of the output device sample rate to avoid loss of high frequency information.
2177 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2178 }
2179
Andy Hung09a50072014-02-27 14:30:47 -08002180 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002181 double multiplier = 1.0;
2182 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2183 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002184 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2185 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Eric Laurent81784c32012-11-19 14:55:58 -08002186 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2187 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2188 maxNormalFrameCount = maxNormalFrameCount & ~15;
2189 if (maxNormalFrameCount < minNormalFrameCount) {
2190 maxNormalFrameCount = minNormalFrameCount;
2191 }
2192 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2193 if (multiplier <= 1.0) {
2194 multiplier = 1.0;
2195 } else if (multiplier <= 2.0) {
2196 if (2 * mFrameCount <= maxNormalFrameCount) {
2197 multiplier = 2.0;
2198 } else {
2199 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2200 }
2201 } else {
2202 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
Andy Hung09a50072014-02-27 14:30:47 -08002203 // 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 -08002204 // track, but we sometimes have to do this to satisfy the maximum frame count
2205 // constraint)
2206 // FIXME this rounding up should not be done if no HAL SRC
2207 uint32_t truncMult = (uint32_t) multiplier;
2208 if ((truncMult & 1)) {
2209 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
2210 ++truncMult;
2211 }
2212 }
2213 multiplier = (double) truncMult;
2214 }
2215 }
2216 mNormalFrameCount = multiplier * mFrameCount;
2217 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002218 if (mType == MIXER || mType == DUPLICATING) {
2219 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2220 }
Andy Hung09a50072014-02-27 14:30:47 -08002221 ALOGI("HAL output buffer size %u frames, normal sink buffer size %u frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002222 mNormalFrameCount);
2223
Andy Hung08fb1742015-05-31 23:22:10 -07002224 // Check if we want to throttle the processing to no more than 2x normal rate
2225 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002226 mThreadThrottleTimeMs = 0;
2227 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002228 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2229
Andy Hung010a1a12014-03-13 13:57:33 -07002230 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2231 // Originally this was int16_t[] array, need to remove legacy implications.
2232 free(mSinkBuffer);
2233 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002234 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2235 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2236 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002237 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002238
Andy Hung69aed5f2014-02-25 17:24:40 -08002239 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2240 // drives the output.
2241 free(mMixerBuffer);
2242 mMixerBuffer = NULL;
2243 if (mMixerBufferEnabled) {
2244 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2245 mMixerBufferSize = mNormalFrameCount * mChannelCount
2246 * audio_bytes_per_sample(mMixerBufferFormat);
2247 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2248 }
Andy Hung98ef9782014-03-04 14:46:50 -08002249 free(mEffectBuffer);
2250 mEffectBuffer = NULL;
2251 if (mEffectBufferEnabled) {
2252 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
2253 mEffectBufferSize = mNormalFrameCount * mChannelCount
2254 * audio_bytes_per_sample(mEffectBufferFormat);
2255 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2256 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002257
Eric Laurent81784c32012-11-19 14:55:58 -08002258 // force reconfiguration of effect chains and engines to take new buffer size and audio
2259 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002260 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002261 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2262 // matter.
2263 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2264 Vector< sp<EffectChain> > effectChains = mEffectChains;
2265 for (size_t i = 0; i < effectChains.size(); i ++) {
2266 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2267 }
2268}
2269
2270
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002271status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002272{
2273 if (halFrames == NULL || dspFrames == NULL) {
2274 return BAD_VALUE;
2275 }
2276 Mutex::Autolock _l(mLock);
2277 if (initCheck() != NO_ERROR) {
2278 return INVALID_OPERATION;
2279 }
2280 size_t framesWritten = mBytesWritten / mFrameSize;
2281 *halFrames = framesWritten;
2282
2283 if (isSuspended()) {
2284 // return an estimation of rendered frames when the output is suspended
2285 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
2286 *dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0;
2287 return NO_ERROR;
2288 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002289 status_t status;
2290 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002291 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002292 *dspFrames = (size_t)frames;
2293 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002294 }
2295}
2296
2297uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
2298{
2299 Mutex::Autolock _l(mLock);
2300 uint32_t result = 0;
2301 if (getEffectChain_l(sessionId) != 0) {
2302 result = EFFECT_SESSION;
2303 }
2304
2305 for (size_t i = 0; i < mTracks.size(); ++i) {
2306 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002307 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002308 result |= TRACK_SESSION;
2309 break;
2310 }
2311 }
2312
2313 return result;
2314}
2315
2316uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
2317{
2318 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2319 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2320 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2321 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2322 }
2323 for (size_t i = 0; i < mTracks.size(); i++) {
2324 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002325 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002326 return AudioSystem::getStrategyForStream(track->streamType());
2327 }
2328 }
2329 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2330}
2331
2332
Phil Burk062e67a2015-02-11 13:40:50 -08002333AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002334{
2335 Mutex::Autolock _l(mLock);
2336 return mOutput;
2337}
2338
Phil Burk062e67a2015-02-11 13:40:50 -08002339AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002340{
2341 Mutex::Autolock _l(mLock);
2342 AudioStreamOut *output = mOutput;
2343 mOutput = NULL;
2344 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2345 // must push a NULL and wait for ack
2346 mOutputSink.clear();
2347 mPipeSink.clear();
2348 mNormalSink.clear();
2349 return output;
2350}
2351
2352// this method must always be called either with ThreadBase mLock held or inside the thread loop
2353audio_stream_t* AudioFlinger::PlaybackThread::stream() const
2354{
2355 if (mOutput == NULL) {
2356 return NULL;
2357 }
2358 return &mOutput->stream->common;
2359}
2360
2361uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2362{
2363 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2364}
2365
2366status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2367{
2368 if (!isValidSyncEvent(event)) {
2369 return BAD_VALUE;
2370 }
2371
2372 Mutex::Autolock _l(mLock);
2373
2374 for (size_t i = 0; i < mTracks.size(); ++i) {
2375 sp<Track> track = mTracks[i];
2376 if (event->triggerSession() == track->sessionId()) {
2377 (void) track->setSyncEvent(event);
2378 return NO_ERROR;
2379 }
2380 }
2381
2382 return NAME_NOT_FOUND;
2383}
2384
2385bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2386{
2387 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2388}
2389
2390void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2391 const Vector< sp<Track> >& tracksToRemove)
2392{
2393 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002394 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002395 for (size_t i = 0 ; i < count ; i++) {
2396 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002397 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002398 AudioSystem::stopOutput(mId, track->streamType(),
2399 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002400#ifdef ADD_BATTERY_DATA
2401 // to track the speaker usage
2402 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2403#endif
2404 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002405 AudioSystem::releaseOutput(mId, track->streamType(),
2406 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002407 }
Eric Laurent81784c32012-11-19 14:55:58 -08002408 }
2409 }
2410 }
Eric Laurent81784c32012-11-19 14:55:58 -08002411}
2412
2413void AudioFlinger::PlaybackThread::checkSilentMode_l()
2414{
2415 if (!mMasterMute) {
2416 char value[PROPERTY_VALUE_MAX];
2417 if (property_get("ro.audio.silent", value, "0") > 0) {
2418 char *endptr;
2419 unsigned long ul = strtoul(value, &endptr, 0);
2420 if (*endptr == '\0' && ul != 0) {
2421 ALOGD("Silence is golden");
2422 // The setprop command will not allow a property to be changed after
2423 // the first time it is set, so we don't have to worry about un-muting.
2424 setMasterMute_l(true);
2425 }
2426 }
2427 }
2428}
2429
2430// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002431ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002432{
2433 // FIXME rewrite to reduce number of system calls
2434 mLastWriteTime = systemTime();
2435 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002436 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002437 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002438
2439 // If an NBAIO sink is present, use it to write the normal mixer's submix
2440 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002441
Andy Hung010a1a12014-03-13 13:57:33 -07002442 const size_t count = mBytesRemaining / mFrameSize;
2443
Simon Wilson2d590962012-11-29 15:18:50 -08002444 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002445 // update the setpoint when AudioFlinger::mScreenState changes
2446 uint32_t screenState = AudioFlinger::mScreenState;
2447 if (screenState != mScreenState) {
2448 mScreenState = screenState;
2449 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2450 if (pipe != NULL) {
2451 pipe->setAvgFrames((mScreenState & 1) ?
2452 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2453 }
2454 }
Andy Hung010a1a12014-03-13 13:57:33 -07002455 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002456 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002457 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002458 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002459 } else {
2460 bytesWritten = framesWritten;
2461 }
Glenn Kastenefaa7ab2014-08-20 08:48:54 -07002462 mLatchDValid = false;
Glenn Kasten767094d2013-08-23 13:51:43 -07002463 status_t status = mNormalSink->getTimestamp(mLatchD.mTimestamp);
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002464 if (status == NO_ERROR) {
2465 size_t totalFramesWritten = mNormalSink->framesWritten();
2466 if (totalFramesWritten >= mLatchD.mTimestamp.mPosition) {
2467 mLatchD.mUnpresentedFrames = totalFramesWritten - mLatchD.mTimestamp.mPosition;
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002468 // mLatchD.mFramesReleased is set immediately before D is clocked into Q
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002469 mLatchDValid = true;
2470 }
2471 }
Eric Laurent81784c32012-11-19 14:55:58 -08002472 // otherwise use the HAL / AudioStreamOut directly
2473 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002474 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002475
Eric Laurentbfb1b832013-01-07 09:53:42 -08002476 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002477 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2478 mWriteAckSequence += 2;
2479 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002480 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002481 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002482 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002483 // FIXME We should have an implementation of timestamps for direct output threads.
2484 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002485 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002486 if (mUseAsyncWrite &&
2487 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2488 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002489 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002490 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002491 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002492 }
Eric Laurent81784c32012-11-19 14:55:58 -08002493 }
2494
Eric Laurent81784c32012-11-19 14:55:58 -08002495 mNumWrites++;
2496 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002497 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002498 return bytesWritten;
2499}
2500
2501void AudioFlinger::PlaybackThread::threadLoop_drain()
2502{
2503 if (mOutput->stream->drain) {
2504 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2505 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002506 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2507 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002508 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002509 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002510 }
2511 mOutput->stream->drain(mOutput->stream,
2512 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
2513 : AUDIO_DRAIN_ALL);
2514 }
2515}
2516
2517void AudioFlinger::PlaybackThread::threadLoop_exit()
2518{
Eric Laurent275e8e92014-11-30 15:14:47 -08002519 {
2520 Mutex::Autolock _l(mLock);
2521 for (size_t i = 0; i < mTracks.size(); i++) {
2522 sp<Track> track = mTracks[i];
2523 track->invalidate();
2524 }
2525 }
Eric Laurent81784c32012-11-19 14:55:58 -08002526}
2527
2528/*
2529The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002530 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002531 - mActiveSleepTimeUs from activeSleepTimeUs()
2532 - mIdleSleepTimeUs from idleSleepTimeUs()
2533 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only)
Eric Laurent81784c32012-11-19 14:55:58 -08002534 - maxPeriod from frame count and sample rate (MIXER only)
2535
2536The parameters that affect these derived values are:
2537 - frame count
2538 - frame size
2539 - sample rate
2540 - device type: A2DP or not
2541 - device latency
2542 - format: PCM or not
2543 - active sleep time
2544 - idle sleep time
2545*/
2546
2547void AudioFlinger::PlaybackThread::cacheParameters_l()
2548{
Andy Hung25c2dac2014-02-27 14:56:00 -08002549 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002550 mActiveSleepTimeUs = activeSleepTimeUs();
2551 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent81784c32012-11-19 14:55:58 -08002552}
2553
2554void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2555{
Glenn Kasten7c027242012-12-26 14:43:16 -08002556 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurent81784c32012-11-19 14:55:58 -08002557 this, streamType, mTracks.size());
2558 Mutex::Autolock _l(mLock);
2559
2560 size_t size = mTracks.size();
2561 for (size_t i = 0; i < size; i++) {
2562 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07002563 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002564 t->invalidate();
Eric Laurent81784c32012-11-19 14:55:58 -08002565 }
2566 }
2567}
2568
2569status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2570{
2571 int session = chain->sessionId();
Andy Hung010a1a12014-03-13 13:57:33 -07002572 int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled
2573 ? mEffectBuffer : mSinkBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002574 bool ownsBuffer = false;
2575
2576 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
2577 if (session > 0) {
2578 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002579 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002580 if (mType != DIRECT) {
2581 size_t numSamples = mNormalFrameCount * mChannelCount;
2582 buffer = new int16_t[numSamples];
2583 memset(buffer, 0, numSamples * sizeof(int16_t));
2584 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2585 ownsBuffer = true;
2586 }
2587
2588 // Attach all tracks with same session ID to this chain.
2589 for (size_t i = 0; i < mTracks.size(); ++i) {
2590 sp<Track> track = mTracks[i];
2591 if (session == track->sessionId()) {
2592 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2593 buffer);
2594 track->setMainBuffer(buffer);
2595 chain->incTrackCnt();
2596 }
2597 }
2598
2599 // indicate all active tracks in the chain
2600 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2601 sp<Track> track = mActiveTracks[i].promote();
2602 if (track == 0) {
2603 continue;
2604 }
2605 if (session == track->sessionId()) {
2606 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2607 chain->incActiveTrackCnt();
2608 }
2609 }
2610 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002611 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08002612 chain->setInBuffer(buffer, ownsBuffer);
Andy Hung010a1a12014-03-13 13:57:33 -07002613 chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled
2614 ? mEffectBuffer : mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002615 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
2616 // chains list in order to be processed last as it contains output stage effects
2617 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2618 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
2619 // after track specific effects and before output stage
2620 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
2621 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
2622 // Effect chain for other sessions are inserted at beginning of effect
2623 // chains list to be processed before output mix effects. Relative order between other
2624 // sessions is not important
2625 size_t size = mEffectChains.size();
2626 size_t i = 0;
2627 for (i = 0; i < size; i++) {
2628 if (mEffectChains[i]->sessionId() < session) {
2629 break;
2630 }
2631 }
2632 mEffectChains.insertAt(chain, i);
2633 checkSuspendOnAddEffectChain_l(chain);
2634
2635 return NO_ERROR;
2636}
2637
2638size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2639{
2640 int session = chain->sessionId();
2641
2642 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2643
2644 for (size_t i = 0; i < mEffectChains.size(); i++) {
2645 if (chain == mEffectChains[i]) {
2646 mEffectChains.removeAt(i);
2647 // detach all active tracks from the chain
2648 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2649 sp<Track> track = mActiveTracks[i].promote();
2650 if (track == 0) {
2651 continue;
2652 }
2653 if (session == track->sessionId()) {
2654 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2655 chain.get(), session);
2656 chain->decActiveTrackCnt();
2657 }
2658 }
2659
2660 // detach all tracks with same session ID from this chain
2661 for (size_t i = 0; i < mTracks.size(); ++i) {
2662 sp<Track> track = mTracks[i];
2663 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002664 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002665 chain->decTrackCnt();
2666 }
2667 }
2668 break;
2669 }
2670 }
2671 return mEffectChains.size();
2672}
2673
2674status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2675 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2676{
2677 Mutex::Autolock _l(mLock);
2678 return attachAuxEffect_l(track, EffectId);
2679}
2680
2681status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2682 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2683{
2684 status_t status = NO_ERROR;
2685
2686 if (EffectId == 0) {
2687 track->setAuxBuffer(0, NULL);
2688 } else {
2689 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2690 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2691 if (effect != 0) {
2692 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2693 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2694 } else {
2695 status = INVALID_OPERATION;
2696 }
2697 } else {
2698 status = BAD_VALUE;
2699 }
2700 }
2701 return status;
2702}
2703
2704void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2705{
2706 for (size_t i = 0; i < mTracks.size(); ++i) {
2707 sp<Track> track = mTracks[i];
2708 if (track->auxEffectId() == effectId) {
2709 attachAuxEffect_l(track, 0);
2710 }
2711 }
2712}
2713
2714bool AudioFlinger::PlaybackThread::threadLoop()
2715{
2716 Vector< sp<Track> > tracksToRemove;
2717
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002718 mStandbyTimeNs = systemTime();
Eric Laurent81784c32012-11-19 14:55:58 -08002719
2720 // MIXER
2721 nsecs_t lastWarning = 0;
2722
2723 // DUPLICATING
2724 // FIXME could this be made local to while loop?
2725 writeFrames = 0;
2726
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002727 int lastGeneration = 0;
2728
Eric Laurent81784c32012-11-19 14:55:58 -08002729 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002730 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08002731
2732 if (mType == MIXER) {
2733 sleepTimeShift = 0;
2734 }
2735
2736 CpuStats cpuStats;
2737 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2738
2739 acquireWakeLock();
2740
Glenn Kasten9e58b552013-01-18 15:09:48 -08002741 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2742 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2743 // and then that string will be logged at the next convenient opportunity.
2744 const char *logString = NULL;
2745
Eric Laurent664539d2013-09-23 18:24:31 -07002746 checkSilentMode_l();
2747
Eric Laurent81784c32012-11-19 14:55:58 -08002748 while (!exitPending())
2749 {
2750 cpuStats.sample(myName);
2751
2752 Vector< sp<EffectChain> > effectChains;
2753
Eric Laurent81784c32012-11-19 14:55:58 -08002754 { // scope for mLock
2755
2756 Mutex::Autolock _l(mLock);
2757
Eric Laurent021cf962014-05-13 10:18:14 -07002758 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07002759
Glenn Kasten9e58b552013-01-18 15:09:48 -08002760 if (logString != NULL) {
2761 mNBLogWriter->logTimestamp();
2762 mNBLogWriter->log(logString);
2763 logString = NULL;
2764 }
2765
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002766 // Gather the framesReleased counters for all active tracks,
2767 // and latch them atomically with the timestamp.
2768 // FIXME We're using raw pointers as indices. A unique track ID would be a better index.
2769 mLatchD.mFramesReleased.clear();
2770 size_t size = mActiveTracks.size();
2771 for (size_t i = 0; i < size; i++) {
2772 sp<Track> t = mActiveTracks[i].promote();
2773 if (t != 0) {
2774 mLatchD.mFramesReleased.add(t.get(),
2775 t->mAudioTrackServerProxy->framesReleased());
2776 }
2777 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002778 if (mLatchDValid) {
2779 mLatchQ = mLatchD;
2780 mLatchDValid = false;
2781 mLatchQValid = true;
2782 }
2783
Eric Laurent81784c32012-11-19 14:55:58 -08002784 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002785 if (mSignalPending) {
2786 // A signal was raised while we were unlocked
2787 mSignalPending = false;
2788 } else if (waitingAsyncCallback_l()) {
2789 if (exitPending()) {
2790 break;
2791 }
Marco Nelissen078538c2015-05-12 09:17:57 -07002792 bool released = false;
2793 // The following works around a bug in the offload driver. Ideally we would release
2794 // the wake lock every time, but that causes the last offload buffer(s) to be
2795 // dropped while the device is on battery, so we need to hold a wake lock during
2796 // the drain phase.
2797 if (mBytesRemaining && !(mDrainSequence & 1)) {
2798 releaseWakeLock_l();
2799 released = true;
2800 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002801 mWakeLockUids.clear();
2802 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002803 ALOGV("wait async completion");
2804 mWaitWorkCV.wait(mLock);
2805 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07002806 if (released) {
2807 acquireWakeLock_l();
2808 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002809 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
2810 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002811
2812 continue;
2813 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002814 if ((!mActiveTracks.size() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08002815 isSuspended()) {
2816 // put audio hardware into standby after short delay
2817 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002818
2819 threadLoop_standby();
2820
2821 mStandby = true;
2822 }
2823
2824 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2825 // we're about to wait, flush the binder command buffer
2826 IPCThreadState::self()->flushCommands();
2827
2828 clearOutputTracks();
2829
2830 if (exitPending()) {
2831 break;
2832 }
2833
2834 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002835 mWakeLockUids.clear();
2836 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002837 // wait until we have something to do...
2838 ALOGV("%s going to sleep", myName.string());
2839 mWaitWorkCV.wait(mLock);
2840 ALOGV("%s waking up", myName.string());
2841 acquireWakeLock_l();
2842
2843 mMixerStatus = MIXER_IDLE;
2844 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2845 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002846 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002847 checkSilentMode_l();
2848
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002849 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
2850 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08002851 if (mType == MIXER) {
2852 sleepTimeShift = 0;
2853 }
2854
2855 continue;
2856 }
2857 }
Eric Laurent81784c32012-11-19 14:55:58 -08002858 // mMixerStatusIgnoringFastTracks is also updated internally
2859 mMixerStatus = prepareTracks_l(&tracksToRemove);
2860
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002861 // compare with previously applied list
2862 if (lastGeneration != mActiveTracksGeneration) {
2863 // update wakelock
2864 updateWakeLockUids_l(mWakeLockUids);
2865 lastGeneration = mActiveTracksGeneration;
2866 }
2867
Eric Laurent81784c32012-11-19 14:55:58 -08002868 // prevent any changes in effect chain list and in each effect chain
2869 // during mixing and effect process as the audio buffers could be deleted
2870 // or modified if an effect is created or deleted
2871 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002872 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08002873
Eric Laurentbfb1b832013-01-07 09:53:42 -08002874 if (mBytesRemaining == 0) {
2875 mCurrentWriteLength = 0;
2876 if (mMixerStatus == MIXER_TRACKS_READY) {
2877 // threadLoop_mix() sets mCurrentWriteLength
2878 threadLoop_mix();
2879 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
2880 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002881 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08002882 // must be written to HAL
2883 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002884 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08002885 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002886 }
2887 }
Andy Hung98ef9782014-03-04 14:46:50 -08002888 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002889 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08002890 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
2891 // or mSinkBuffer (if there are no effects).
2892 //
2893 // This is done pre-effects computation; if effects change to
2894 // support higher precision, this needs to move.
2895 //
2896 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002897 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08002898 if (mMixerBufferValid) {
2899 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
2900 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
2901
2902 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
2903 mNormalFrameCount * mChannelCount);
2904 }
2905
Eric Laurentbfb1b832013-01-07 09:53:42 -08002906 mBytesRemaining = mCurrentWriteLength;
2907 if (isSuspended()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002908 mSleepTimeUs = suspendSleepTimeUs();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002909 // simulate write to HAL when suspended
Andy Hung25c2dac2014-02-27 14:56:00 -08002910 mBytesWritten += mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002911 mBytesRemaining = 0;
2912 }
Eric Laurent81784c32012-11-19 14:55:58 -08002913
Eric Laurentbfb1b832013-01-07 09:53:42 -08002914 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002915 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002916 for (size_t i = 0; i < effectChains.size(); i ++) {
2917 effectChains[i]->process_l();
2918 }
Eric Laurent81784c32012-11-19 14:55:58 -08002919 }
2920 }
Eric Laurent59fe0102013-09-27 18:48:26 -07002921 // Process effect chains for offloaded thread even if no audio
2922 // was read from audio track: process only updates effect state
2923 // and thus does have to be synchronized with audio writes but may have
2924 // to be called while waiting for async write callback
2925 if (mType == OFFLOAD) {
2926 for (size_t i = 0; i < effectChains.size(); i ++) {
2927 effectChains[i]->process_l();
2928 }
2929 }
Eric Laurent81784c32012-11-19 14:55:58 -08002930
Andy Hung98ef9782014-03-04 14:46:50 -08002931 // Only if the Effects buffer is enabled and there is data in the
2932 // Effects buffer (buffer valid), we need to
2933 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002934 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08002935 if (mEffectBufferValid) {
2936 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
2937 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
2938 mNormalFrameCount * mChannelCount);
2939 }
2940
Eric Laurent81784c32012-11-19 14:55:58 -08002941 // enable changes in effect chain
2942 unlockEffectChains(effectChains);
2943
Eric Laurentbfb1b832013-01-07 09:53:42 -08002944 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002945 // mSleepTimeUs == 0 means we must write to audio hardware
2946 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07002947 ssize_t ret = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002948 if (mBytesRemaining) {
Andy Hung08fb1742015-05-31 23:22:10 -07002949 ret = threadLoop_write();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002950 if (ret < 0) {
2951 mBytesRemaining = 0;
2952 } else {
2953 mBytesWritten += ret;
2954 mBytesRemaining -= ret;
2955 }
2956 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
2957 (mMixerStatus == MIXER_DRAIN_ALL)) {
2958 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08002959 }
Andy Hung08fb1742015-05-31 23:22:10 -07002960 if (mType == MIXER && !mStandby) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07002961 // write blocked detection
2962 nsecs_t now = systemTime();
2963 nsecs_t delta = now - mLastWriteTime;
Andy Hung08fb1742015-05-31 23:22:10 -07002964 if (delta > maxPeriod) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07002965 mNumDelayedWrites++;
2966 if ((now - lastWarning) > kWarningThrottleNs) {
2967 ATRACE_NAME("underrun");
2968 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2969 ns2ms(delta), mNumDelayedWrites, this);
2970 lastWarning = now;
2971 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002972 }
Andy Hung08fb1742015-05-31 23:22:10 -07002973
2974 if (mThreadThrottle
2975 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
2976 && ret > 0) { // we wrote something
2977 // Limit MixerThread data processing to no more than twice the
2978 // expected processing rate.
2979 //
2980 // This helps prevent underruns with NuPlayer and other applications
2981 // which may set up buffers that are close to the minimum size, or use
2982 // deep buffers, and rely on a double-buffering sleep strategy to fill.
2983 //
2984 // The throttle smooths out sudden large data drains from the device,
2985 // e.g. when it comes out of standby, which often causes problems with
2986 // (1) mixer threads without a fast mixer (which has its own warm-up)
2987 // (2) minimum buffer sized tracks (even if the track is full,
2988 // the app won't fill fast enough to handle the sudden draw).
2989
2990 const int32_t deltaMs = delta / 1000000;
2991 const int32_t throttleMs = mHalfBufferMs - deltaMs;
2992 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
2993 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07002994 // notify of throttle start on verbose log
2995 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
2996 "mixer(%p) throttle begin:"
2997 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07002998 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07002999 mThreadThrottleTimeMs += throttleMs;
3000 } else {
3001 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3002 if (diff > 0) {
3003 // notify of throttle end on debug log
3004 ALOGD("mixer(%p) throttle end: throttle time(%u)", this, diff);
3005 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3006 }
Andy Hung08fb1742015-05-31 23:22:10 -07003007 }
3008 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003009 }
Eric Laurent81784c32012-11-19 14:55:58 -08003010
Eric Laurentbfb1b832013-01-07 09:53:42 -08003011 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003012 ATRACE_BEGIN("sleep");
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003013 usleep(mSleepTimeUs);
Glenn Kastene7754022014-10-31 12:11:26 -07003014 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003015 }
Eric Laurent81784c32012-11-19 14:55:58 -08003016 }
3017
3018 // Finally let go of removed track(s), without the lock held
3019 // since we can't guarantee the destructors won't acquire that
3020 // same lock. This will also mutate and push a new fast mixer state.
3021 threadLoop_removeTracks(tracksToRemove);
3022 tracksToRemove.clear();
3023
3024 // FIXME I don't understand the need for this here;
3025 // it was in the original code but maybe the
3026 // assignment in saveOutputTracks() makes this unnecessary?
3027 clearOutputTracks();
3028
3029 // Effect chains will be actually deleted here if they were removed from
3030 // mEffectChains list during mixing or effects processing
3031 effectChains.clear();
3032
3033 // FIXME Note that the above .clear() is no longer necessary since effectChains
3034 // is now local to this block, but will keep it for now (at least until merge done).
3035 }
3036
Eric Laurentbfb1b832013-01-07 09:53:42 -08003037 threadLoop_exit();
3038
Eric Laurentcf817a22014-08-04 20:36:31 -07003039 if (!mStandby) {
3040 threadLoop_standby();
3041 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003042 }
3043
3044 releaseWakeLock();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003045 mWakeLockUids.clear();
3046 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08003047
3048 ALOGV("Thread %p type %d exiting", this, mType);
3049 return false;
3050}
3051
Eric Laurentbfb1b832013-01-07 09:53:42 -08003052// removeTracks_l() must be called with ThreadBase::mLock held
3053void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3054{
3055 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07003056 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003057 for (size_t i=0 ; i<count ; i++) {
3058 const sp<Track>& track = tracksToRemove.itemAt(i);
3059 mActiveTracks.remove(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003060 mWakeLockUids.remove(track->uid());
3061 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003062 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
3063 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3064 if (chain != 0) {
3065 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
3066 track->sessionId());
3067 chain->decActiveTrackCnt();
3068 }
3069 if (track->isTerminated()) {
3070 removeTrack_l(track);
3071 }
3072 }
3073 }
3074
3075}
Eric Laurent81784c32012-11-19 14:55:58 -08003076
Eric Laurentaccc1472013-09-20 09:36:34 -07003077status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3078{
3079 if (mNormalSink != 0) {
3080 return mNormalSink->getTimestamp(timestamp);
3081 }
Andy Hung9a1c8892014-12-03 11:37:42 -08003082 if ((mType == OFFLOAD || mType == DIRECT)
3083 && mOutput != NULL && mOutput->stream->get_presentation_position) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003084 uint64_t position64;
Phil Burk062e67a2015-02-11 13:40:50 -08003085 int ret = mOutput->getPresentationPosition(&position64, &timestamp.mTime);
Eric Laurentaccc1472013-09-20 09:36:34 -07003086 if (ret == 0) {
3087 timestamp.mPosition = (uint32_t)position64;
3088 return NO_ERROR;
3089 }
3090 }
3091 return INVALID_OPERATION;
3092}
Eric Laurent1c333e22014-05-20 10:48:17 -07003093
Eric Laurent054d9d32015-04-24 08:48:48 -07003094status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
3095 audio_patch_handle_t *handle)
3096{
3097 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3098 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3099 if (mFastMixer != 0) {
3100 FastMixerStateQueue *sq = mFastMixer->sq();
3101 FastMixerState *state = sq->begin();
3102 if (!(state->mCommand & FastMixerState::IDLE)) {
3103 previousCommand = state->mCommand;
3104 state->mCommand = FastMixerState::HOT_IDLE;
3105 sq->end();
3106 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3107 } else {
3108 sq->end(false /*didModify*/);
3109 }
3110 }
3111 status_t status = PlaybackThread::createAudioPatch_l(patch, handle);
3112
3113 if (!(previousCommand & FastMixerState::IDLE)) {
3114 ALOG_ASSERT(mFastMixer != 0);
3115 FastMixerStateQueue *sq = mFastMixer->sq();
3116 FastMixerState *state = sq->begin();
3117 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3118 state->mCommand = previousCommand;
3119 sq->end();
3120 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3121 }
3122
3123 return status;
3124}
3125
Eric Laurent1c333e22014-05-20 10:48:17 -07003126status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3127 audio_patch_handle_t *handle)
3128{
3129 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003130
3131 // store new device and send to effects
3132 audio_devices_t type = AUDIO_DEVICE_NONE;
3133 for (unsigned int i = 0; i < patch->num_sinks; i++) {
3134 type |= patch->sinks[i].ext.device.type;
3135 }
3136
3137#ifdef ADD_BATTERY_DATA
3138 // when changing the audio output device, call addBatteryData to notify
3139 // the change
3140 if (mOutDevice != type) {
3141 uint32_t params = 0;
3142 // check whether speaker is on
3143 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3144 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003145 }
3146
Eric Laurent054d9d32015-04-24 08:48:48 -07003147 audio_devices_t deviceWithoutSpeaker
3148 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3149 // check if any other device (except speaker) is on
3150 if (type & deviceWithoutSpeaker) {
3151 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3152 }
3153
3154 if (params != 0) {
3155 addBatteryData(params);
3156 }
3157 }
3158#endif
3159
3160 for (size_t i = 0; i < mEffectChains.size(); i++) {
3161 mEffectChains[i]->setDevice_l(type);
3162 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003163
3164 // mPrevOutDevice is the latest device set by createAudioPatch_l(). It is not set when
3165 // the thread is created so that the first patch creation triggers an ioConfigChanged callback
3166 bool configChanged = mPrevOutDevice != type;
Eric Laurent054d9d32015-04-24 08:48:48 -07003167 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003168 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003169
3170 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003171 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
3172 status = hwDevice->create_audio_patch(hwDevice,
3173 patch->num_sources,
3174 patch->sources,
3175 patch->num_sinks,
3176 patch->sinks,
3177 handle);
3178 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003179 char *address;
3180 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3181 //FIXME: we only support address on first sink with HAL version < 3.0
3182 address = audio_device_address_to_parameter(
3183 patch->sinks[0].ext.device.type,
3184 patch->sinks[0].ext.device.address);
3185 } else {
3186 address = (char *)calloc(1, 1);
3187 }
3188 AudioParameter param = AudioParameter(String8(address));
3189 free(address);
3190 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), (int)type);
3191 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3192 param.toString().string());
3193 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003194 }
Eric Laurente8726fe2015-06-26 09:39:24 -07003195 if (configChanged) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003196 mPrevOutDevice = type;
Eric Laurente8726fe2015-06-26 09:39:24 -07003197 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
3198 }
Eric Laurent1c333e22014-05-20 10:48:17 -07003199 return status;
3200}
3201
Eric Laurent054d9d32015-04-24 08:48:48 -07003202status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3203{
3204 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3205 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3206 if (mFastMixer != 0) {
3207 FastMixerStateQueue *sq = mFastMixer->sq();
3208 FastMixerState *state = sq->begin();
3209 if (!(state->mCommand & FastMixerState::IDLE)) {
3210 previousCommand = state->mCommand;
3211 state->mCommand = FastMixerState::HOT_IDLE;
3212 sq->end();
3213 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3214 } else {
3215 sq->end(false /*didModify*/);
3216 }
3217 }
3218
3219 status_t status = PlaybackThread::releaseAudioPatch_l(handle);
3220
3221 if (!(previousCommand & FastMixerState::IDLE)) {
3222 ALOG_ASSERT(mFastMixer != 0);
3223 FastMixerStateQueue *sq = mFastMixer->sq();
3224 FastMixerState *state = sq->begin();
3225 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3226 state->mCommand = previousCommand;
3227 sq->end();
3228 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3229 }
3230
3231 return status;
3232}
3233
Eric Laurent1c333e22014-05-20 10:48:17 -07003234status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3235{
3236 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003237
3238 mOutDevice = AUDIO_DEVICE_NONE;
3239
Eric Laurent1c333e22014-05-20 10:48:17 -07003240 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
3241 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
3242 status = hwDevice->release_audio_patch(hwDevice, handle);
3243 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003244 AudioParameter param;
3245 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
3246 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3247 param.toString().string());
Eric Laurent1c333e22014-05-20 10:48:17 -07003248 }
3249 return status;
3250}
3251
Eric Laurent83b88082014-06-20 18:31:16 -07003252void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3253{
3254 Mutex::Autolock _l(mLock);
3255 mTracks.add(track);
3256}
3257
3258void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3259{
3260 Mutex::Autolock _l(mLock);
3261 destroyTrack_l(track);
3262}
3263
3264void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
3265{
3266 ThreadBase::getAudioPortConfig(config);
3267 config->role = AUDIO_PORT_ROLE_SOURCE;
3268 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3269 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
3270}
3271
Eric Laurent81784c32012-11-19 14:55:58 -08003272// ----------------------------------------------------------------------------
3273
3274AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurent72e3f392015-05-20 14:43:50 -07003275 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
3276 : PlaybackThread(audioFlinger, output, id, device, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08003277 // mAudioMixer below
3278 // mFastMixer below
3279 mFastMixerFutex(0)
3280 // mOutputSink below
3281 // mPipeSink below
3282 // mNormalSink below
3283{
3284 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07003285 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, "
Eric Laurent81784c32012-11-19 14:55:58 -08003286 "mFrameCount=%d, mNormalFrameCount=%d",
3287 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3288 mNormalFrameCount);
3289 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3290
Andy Hungfbfc3952015-01-15 13:33:51 -08003291 if (type == DUPLICATING) {
3292 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3293 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3294 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3295 return;
3296 }
Eric Laurent81784c32012-11-19 14:55:58 -08003297 // create an NBAIO sink for the HAL output stream, and negotiate
3298 mOutputSink = new AudioStreamOutSink(output->stream);
3299 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003300 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Eric Laurent81784c32012-11-19 14:55:58 -08003301 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
3302 ALOG_ASSERT(index == 0);
3303
3304 // initialize fast mixer depending on configuration
3305 bool initFastMixer;
3306 switch (kUseFastMixer) {
3307 case FastMixer_Never:
3308 initFastMixer = false;
3309 break;
3310 case FastMixer_Always:
3311 initFastMixer = true;
3312 break;
3313 case FastMixer_Static:
3314 case FastMixer_Dynamic:
3315 initFastMixer = mFrameCount < mNormalFrameCount;
3316 break;
3317 }
3318 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003319 audio_format_t fastMixerFormat;
3320 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3321 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3322 } else {
3323 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3324 }
3325 if (mFormat != fastMixerFormat) {
3326 // change our Sink format to accept our intermediate precision
3327 mFormat = fastMixerFormat;
3328 free(mSinkBuffer);
3329 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3330 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3331 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3332 }
Eric Laurent81784c32012-11-19 14:55:58 -08003333
3334 // create a MonoPipe to connect our submix to FastMixer
3335 NBAIO_Format format = mOutputSink->format();
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003336 NBAIO_Format origformat = format;
Andy Hung1258c1a2014-05-23 21:22:17 -07003337 // adjust format to match that of the Fast Mixer
Glenn Kasten97b7b752014-09-28 13:04:24 -07003338 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003339 format.mFormat = fastMixerFormat;
3340 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3341
Eric Laurent81784c32012-11-19 14:55:58 -08003342 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3343 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3344 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3345 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3346 const NBAIO_Format offers[1] = {format};
3347 size_t numCounterOffers = 0;
3348 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
3349 ALOG_ASSERT(index == 0);
3350 monoPipe->setAvgFrames((mScreenState & 1) ?
3351 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3352 mPipeSink = monoPipe;
3353
Glenn Kasten46909e72013-02-26 09:20:22 -08003354#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08003355 if (mTeeSinkOutputEnabled) {
3356 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003357 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
3358 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08003359 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003360 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003361 ALOG_ASSERT(index == 0);
3362 mTeeSink = teeSink;
3363 PipeReader *teeSource = new PipeReader(*teeSink);
3364 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003365 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003366 ALOG_ASSERT(index == 0);
3367 mTeeSource = teeSource;
3368 }
Glenn Kasten46909e72013-02-26 09:20:22 -08003369#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003370
3371 // create fast mixer and configure it initially with just one fast track for our submix
3372 mFastMixer = new FastMixer();
3373 FastMixerStateQueue *sq = mFastMixer->sq();
3374#ifdef STATE_QUEUE_DUMP
3375 sq->setObserverDump(&mStateQueueObserverDump);
3376 sq->setMutatorDump(&mStateQueueMutatorDump);
3377#endif
3378 FastMixerState *state = sq->begin();
3379 FastTrack *fastTrack = &state->mFastTracks[0];
3380 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3381 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3382 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003383 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3384 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003385 fastTrack->mGeneration++;
3386 state->mFastTracksGen++;
3387 state->mTrackMask = 1;
3388 // fast mixer will use the HAL output sink
3389 state->mOutputSink = mOutputSink.get();
3390 state->mOutputSinkGen++;
3391 state->mFrameCount = mFrameCount;
3392 state->mCommand = FastMixerState::COLD_IDLE;
3393 // already done in constructor initialization list
3394 //mFastMixerFutex = 0;
3395 state->mColdFutexAddr = &mFastMixerFutex;
3396 state->mColdGen++;
3397 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08003398#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003399 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08003400#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08003401 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3402 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003403 sq->end();
3404 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3405
3406 // start the fast mixer
3407 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3408 pid_t tid = mFastMixer->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003409 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003410
3411#ifdef AUDIO_WATCHDOG
3412 // create and start the watchdog
3413 mAudioWatchdog = new AudioWatchdog();
3414 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3415 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3416 tid = mAudioWatchdog->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003417 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003418#endif
3419
Eric Laurent81784c32012-11-19 14:55:58 -08003420 }
3421
3422 switch (kUseFastMixer) {
3423 case FastMixer_Never:
3424 case FastMixer_Dynamic:
3425 mNormalSink = mOutputSink;
3426 break;
3427 case FastMixer_Always:
3428 mNormalSink = mPipeSink;
3429 break;
3430 case FastMixer_Static:
3431 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3432 break;
3433 }
3434}
3435
3436AudioFlinger::MixerThread::~MixerThread()
3437{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003438 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003439 FastMixerStateQueue *sq = mFastMixer->sq();
3440 FastMixerState *state = sq->begin();
3441 if (state->mCommand == FastMixerState::COLD_IDLE) {
3442 int32_t old = android_atomic_inc(&mFastMixerFutex);
3443 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003444 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003445 }
3446 }
3447 state->mCommand = FastMixerState::EXIT;
3448 sq->end();
3449 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3450 mFastMixer->join();
3451 // Though the fast mixer thread has exited, it's state queue is still valid.
3452 // We'll use that extract the final state which contains one remaining fast track
3453 // corresponding to our sub-mix.
3454 state = sq->begin();
3455 ALOG_ASSERT(state->mTrackMask == 1);
3456 FastTrack *fastTrack = &state->mFastTracks[0];
3457 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3458 delete fastTrack->mBufferProvider;
3459 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003460 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003461#ifdef AUDIO_WATCHDOG
3462 if (mAudioWatchdog != 0) {
3463 mAudioWatchdog->requestExit();
3464 mAudioWatchdog->requestExitAndWait();
3465 mAudioWatchdog.clear();
3466 }
3467#endif
3468 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003469 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003470 delete mAudioMixer;
3471}
3472
3473
3474uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3475{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003476 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003477 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3478 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3479 }
3480 return latency;
3481}
3482
3483
3484void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3485{
3486 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3487}
3488
Eric Laurentbfb1b832013-01-07 09:53:42 -08003489ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003490{
3491 // FIXME we should only do one push per cycle; confirm this is true
3492 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003493 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003494 FastMixerStateQueue *sq = mFastMixer->sq();
3495 FastMixerState *state = sq->begin();
3496 if (state->mCommand != FastMixerState::MIX_WRITE &&
3497 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3498 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07003499
3500 // FIXME workaround for first HAL write being CPU bound on some devices
3501 ATRACE_BEGIN("write");
3502 mOutput->write((char *)mSinkBuffer, 0);
3503 ATRACE_END();
3504
Eric Laurent81784c32012-11-19 14:55:58 -08003505 int32_t old = android_atomic_inc(&mFastMixerFutex);
3506 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003507 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003508 }
3509#ifdef AUDIO_WATCHDOG
3510 if (mAudioWatchdog != 0) {
3511 mAudioWatchdog->resume();
3512 }
3513#endif
3514 }
3515 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08003516#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003517 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08003518 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08003519#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003520 sq->end();
3521 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3522 if (kUseFastMixer == FastMixer_Dynamic) {
3523 mNormalSink = mPipeSink;
3524 }
3525 } else {
3526 sq->end(false /*didModify*/);
3527 }
3528 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003529 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003530}
3531
3532void AudioFlinger::MixerThread::threadLoop_standby()
3533{
3534 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003535 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003536 FastMixerStateQueue *sq = mFastMixer->sq();
3537 FastMixerState *state = sq->begin();
3538 if (!(state->mCommand & FastMixerState::IDLE)) {
3539 state->mCommand = FastMixerState::COLD_IDLE;
3540 state->mColdFutexAddr = &mFastMixerFutex;
3541 state->mColdGen++;
3542 mFastMixerFutex = 0;
3543 sq->end();
3544 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3545 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3546 if (kUseFastMixer == FastMixer_Dynamic) {
3547 mNormalSink = mOutputSink;
3548 }
3549#ifdef AUDIO_WATCHDOG
3550 if (mAudioWatchdog != 0) {
3551 mAudioWatchdog->pause();
3552 }
3553#endif
3554 } else {
3555 sq->end(false /*didModify*/);
3556 }
3557 }
3558 PlaybackThread::threadLoop_standby();
3559}
3560
Eric Laurentbfb1b832013-01-07 09:53:42 -08003561bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3562{
3563 return false;
3564}
3565
3566bool AudioFlinger::PlaybackThread::shouldStandby_l()
3567{
3568 return !mStandby;
3569}
3570
3571bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3572{
3573 Mutex::Autolock _l(mLock);
3574 return waitingAsyncCallback_l();
3575}
3576
Eric Laurent81784c32012-11-19 14:55:58 -08003577// shared by MIXER and DIRECT, overridden by DUPLICATING
3578void AudioFlinger::PlaybackThread::threadLoop_standby()
3579{
3580 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08003581 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003582 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003583 // discard any pending drain or write ack by incrementing sequence
3584 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3585 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003586 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003587 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3588 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003589 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003590 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003591}
3592
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003593void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3594{
3595 ALOGV("signal playback thread");
3596 broadcast_l();
3597}
3598
Eric Laurent81784c32012-11-19 14:55:58 -08003599void AudioFlinger::MixerThread::threadLoop_mix()
3600{
3601 // obtain the presentation timestamp of the next output buffer
3602 int64_t pts;
3603 status_t status = INVALID_OPERATION;
3604
3605 if (mNormalSink != 0) {
3606 status = mNormalSink->getNextWriteTimestamp(&pts);
3607 } else {
3608 status = mOutputSink->getNextWriteTimestamp(&pts);
3609 }
3610
3611 if (status != NO_ERROR) {
3612 pts = AudioBufferProvider::kInvalidPTS;
3613 }
3614
3615 // mix buffers...
3616 mAudioMixer->process(pts);
Andy Hung25c2dac2014-02-27 14:56:00 -08003617 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003618 // increase sleep time progressively when application underrun condition clears.
3619 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3620 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3621 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003622 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003623 sleepTimeShift--;
3624 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003625 mSleepTimeUs = 0;
3626 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08003627 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003628
Eric Laurent81784c32012-11-19 14:55:58 -08003629}
3630
3631void AudioFlinger::MixerThread::threadLoop_sleepTime()
3632{
3633 // If no tracks are ready, sleep once for the duration of an output
3634 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003635 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003636 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003637 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
3638 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
3639 mSleepTimeUs = kMinThreadSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003640 }
3641 // reduce sleep time in case of consecutive application underruns to avoid
3642 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3643 // duration we would end up writing less data than needed by the audio HAL if
3644 // the condition persists.
3645 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3646 sleepTimeShift++;
3647 }
3648 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003649 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003650 }
3651 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003652 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3653 // before effects processing or output.
3654 if (mMixerBufferValid) {
3655 memset(mMixerBuffer, 0, mMixerBufferSize);
3656 } else {
3657 memset(mSinkBuffer, 0, mSinkBufferSize);
3658 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003659 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003660 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3661 "anticipated start");
3662 }
3663 // TODO add standby time extension fct of effect tail
3664}
3665
3666// prepareTracks_l() must be called with ThreadBase::mLock held
3667AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3668 Vector< sp<Track> > *tracksToRemove)
3669{
3670
3671 mixer_state mixerStatus = MIXER_IDLE;
3672 // find out which tracks need to be processed
3673 size_t count = mActiveTracks.size();
3674 size_t mixedTracks = 0;
3675 size_t tracksWithEffect = 0;
3676 // counts only _active_ fast tracks
3677 size_t fastTracks = 0;
3678 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
3679
3680 float masterVolume = mMasterVolume;
3681 bool masterMute = mMasterMute;
3682
3683 if (masterMute) {
3684 masterVolume = 0;
3685 }
3686 // Delegate master volume control to effect in output mix effect chain if needed
3687 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3688 if (chain != 0) {
3689 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
3690 chain->setVolume_l(&v, &v);
3691 masterVolume = (float)((v + (1 << 23)) >> 24);
3692 chain.clear();
3693 }
3694
3695 // prepare a new state to push
3696 FastMixerStateQueue *sq = NULL;
3697 FastMixerState *state = NULL;
3698 bool didModify = false;
3699 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003700 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003701 sq = mFastMixer->sq();
3702 state = sq->begin();
3703 }
3704
Andy Hung69aed5f2014-02-25 17:24:40 -08003705 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08003706 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08003707
Eric Laurent81784c32012-11-19 14:55:58 -08003708 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003709 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003710 if (t == 0) {
3711 continue;
3712 }
3713
3714 // this const just means the local variable doesn't change
3715 Track* const track = t.get();
3716
3717 // process fast tracks
3718 if (track->isFastTrack()) {
3719
3720 // It's theoretically possible (though unlikely) for a fast track to be created
3721 // and then removed within the same normal mix cycle. This is not a problem, as
3722 // the track never becomes active so it's fast mixer slot is never touched.
3723 // The converse, of removing an (active) track and then creating a new track
3724 // at the identical fast mixer slot within the same normal mix cycle,
3725 // is impossible because the slot isn't marked available until the end of each cycle.
3726 int j = track->mFastIndex;
3727 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
3728 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
3729 FastTrack *fastTrack = &state->mFastTracks[j];
3730
3731 // Determine whether the track is currently in underrun condition,
3732 // and whether it had a recent underrun.
3733 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
3734 FastTrackUnderruns underruns = ftDump->mUnderruns;
3735 uint32_t recentFull = (underruns.mBitFields.mFull -
3736 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
3737 uint32_t recentPartial = (underruns.mBitFields.mPartial -
3738 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
3739 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
3740 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
3741 uint32_t recentUnderruns = recentPartial + recentEmpty;
3742 track->mObservedUnderruns = underruns;
3743 // don't count underruns that occur while stopping or pausing
3744 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07003745 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
3746 recentUnderruns > 0) {
3747 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
3748 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003749 }
3750
3751 // This is similar to the state machine for normal tracks,
3752 // with a few modifications for fast tracks.
3753 bool isActive = true;
3754 switch (track->mState) {
3755 case TrackBase::STOPPING_1:
3756 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08003757 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003758 track->mState = TrackBase::STOPPING_2;
3759 }
3760 break;
3761 case TrackBase::PAUSING:
3762 // ramp down is not yet implemented
3763 track->setPaused();
3764 break;
3765 case TrackBase::RESUMING:
3766 // ramp up is not yet implemented
3767 track->mState = TrackBase::ACTIVE;
3768 break;
3769 case TrackBase::ACTIVE:
3770 if (recentFull > 0 || recentPartial > 0) {
3771 // track has provided at least some frames recently: reset retry count
3772 track->mRetryCount = kMaxTrackRetries;
3773 }
3774 if (recentUnderruns == 0) {
3775 // no recent underruns: stay active
3776 break;
3777 }
3778 // there has recently been an underrun of some kind
3779 if (track->sharedBuffer() == 0) {
3780 // were any of the recent underruns "empty" (no frames available)?
3781 if (recentEmpty == 0) {
3782 // no, then ignore the partial underruns as they are allowed indefinitely
3783 break;
3784 }
3785 // there has recently been an "empty" underrun: decrement the retry counter
3786 if (--(track->mRetryCount) > 0) {
3787 break;
3788 }
3789 // indicate to client process that the track was disabled because of underrun;
3790 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003791 android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003792 // remove from active list, but state remains ACTIVE [confusing but true]
3793 isActive = false;
3794 break;
3795 }
3796 // fall through
3797 case TrackBase::STOPPING_2:
3798 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003799 case TrackBase::STOPPED:
3800 case TrackBase::FLUSHED: // flush() while active
3801 // Check for presentation complete if track is inactive
3802 // We have consumed all the buffers of this track.
3803 // This would be incomplete if we auto-paused on underrun
3804 {
3805 size_t audioHALFrames =
3806 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3807 size_t framesWritten = mBytesWritten / mFrameSize;
3808 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
3809 // track stays in active list until presentation is complete
3810 break;
3811 }
3812 }
3813 if (track->isStopping_2()) {
3814 track->mState = TrackBase::STOPPED;
3815 }
3816 if (track->isStopped()) {
3817 // Can't reset directly, as fast mixer is still polling this track
3818 // track->reset();
3819 // So instead mark this track as needing to be reset after push with ack
3820 resetMask |= 1 << i;
3821 }
3822 isActive = false;
3823 break;
3824 case TrackBase::IDLE:
3825 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08003826 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08003827 }
3828
3829 if (isActive) {
3830 // was it previously inactive?
3831 if (!(state->mTrackMask & (1 << j))) {
3832 ExtendedAudioBufferProvider *eabp = track;
3833 VolumeProvider *vp = track;
3834 fastTrack->mBufferProvider = eabp;
3835 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08003836 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003837 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08003838 fastTrack->mGeneration++;
3839 state->mTrackMask |= 1 << j;
3840 didModify = true;
3841 // no acknowledgement required for newly active tracks
3842 }
3843 // cache the combined master volume and stream type volume for fast mixer; this
3844 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08003845 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08003846 ++fastTracks;
3847 } else {
3848 // was it previously active?
3849 if (state->mTrackMask & (1 << j)) {
3850 fastTrack->mBufferProvider = NULL;
3851 fastTrack->mGeneration++;
3852 state->mTrackMask &= ~(1 << j);
3853 didModify = true;
3854 // If any fast tracks were removed, we must wait for acknowledgement
3855 // because we're about to decrement the last sp<> on those tracks.
3856 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3857 } else {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003858 LOG_ALWAYS_FATAL("fast track %d should have been active", j);
Eric Laurent81784c32012-11-19 14:55:58 -08003859 }
3860 tracksToRemove->add(track);
3861 // Avoids a misleading display in dumpsys
3862 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
3863 }
3864 continue;
3865 }
3866
3867 { // local variable scope to avoid goto warning
3868
3869 audio_track_cblk_t* cblk = track->cblk();
3870
3871 // The first time a track is added we wait
3872 // for all its buffers to be filled before processing it
3873 int name = track->name();
3874 // make sure that we have enough frames to mix one full buffer.
3875 // enforce this condition only once to enable draining the buffer in case the client
3876 // app does not call stop() and relies on underrun to stop:
3877 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
3878 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003879 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07003880 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07003881 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07003882
3883 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07003884 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07003885 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
3886 // add frames already consumed but not yet released by the resampler
3887 // because mAudioTrackServerProxy->framesReady() will include these frames
3888 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
3889
Eric Laurent81784c32012-11-19 14:55:58 -08003890 uint32_t minFrames = 1;
3891 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
3892 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003893 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08003894 }
Eric Laurent13e4c962013-12-20 17:36:01 -08003895
3896 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07003897 if (ATRACE_ENABLED()) {
3898 // I wish we had formatted trace names
3899 char traceName[16];
3900 strcpy(traceName, "nRdy");
3901 int name = track->name();
3902 if (AudioMixer::TRACK0 <= name &&
3903 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
3904 name -= AudioMixer::TRACK0;
3905 traceName[4] = (name / 10) + '0';
3906 traceName[5] = (name % 10) + '0';
3907 } else {
3908 traceName[4] = '?';
3909 traceName[5] = '?';
3910 }
3911 traceName[6] = '\0';
3912 ATRACE_INT(traceName, framesReady);
3913 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003914 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08003915 !track->isPaused() && !track->isTerminated())
3916 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003917 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003918
3919 mixedTracks++;
3920
Andy Hung69aed5f2014-02-25 17:24:40 -08003921 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
3922 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08003923 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08003924 if (track->mainBuffer() != mSinkBuffer &&
3925 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08003926 if (mEffectBufferEnabled) {
3927 mEffectBufferValid = true; // Later can set directly.
3928 }
Eric Laurent81784c32012-11-19 14:55:58 -08003929 chain = getEffectChain_l(track->sessionId());
3930 // Delegate volume control to effect in track effect chain if needed
3931 if (chain != 0) {
3932 tracksWithEffect++;
3933 } else {
3934 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
3935 "session %d",
3936 name, track->sessionId());
3937 }
3938 }
3939
3940
3941 int param = AudioMixer::VOLUME;
3942 if (track->mFillingUpStatus == Track::FS_FILLED) {
3943 // no ramp for the first volume setting
3944 track->mFillingUpStatus = Track::FS_ACTIVE;
3945 if (track->mState == TrackBase::RESUMING) {
3946 track->mState = TrackBase::ACTIVE;
3947 param = AudioMixer::RAMP_VOLUME;
3948 }
3949 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003950 // FIXME should not make a decision based on mServer
3951 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003952 // If the track is stopped before the first frame was mixed,
3953 // do not apply ramp
3954 param = AudioMixer::RAMP_VOLUME;
3955 }
3956
3957 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07003958 uint32_t vl, vr; // in U8.24 integer format
3959 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08003960 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07003961 vl = vr = 0;
3962 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08003963 if (track->isPausing()) {
3964 track->setPaused();
3965 }
3966 } else {
3967
3968 // read original volumes with volume control
3969 float typeVolume = mStreamTypes[track->streamType()].volume;
3970 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003971 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07003972 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07003973 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
3974 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08003975 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07003976 if (vlf > GAIN_FLOAT_UNITY) {
3977 ALOGV("Track left volume out of range: %.3g", vlf);
3978 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003979 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07003980 if (vrf > GAIN_FLOAT_UNITY) {
3981 ALOGV("Track right volume out of range: %.3g", vrf);
3982 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003983 }
3984 // now apply the master volume and stream type volume
Andy Hung6be49402014-05-30 10:42:03 -07003985 vlf *= v;
3986 vrf *= v;
Eric Laurent81784c32012-11-19 14:55:58 -08003987 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07003988 // then derive vl and vr as U8.24 versions for the effect chain
3989 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
3990 vl = (uint32_t) (scaleto8_24 * vlf);
3991 vr = (uint32_t) (scaleto8_24 * vrf);
3992 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08003993 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08003994 // send level comes from shared memory and so may be corrupt
3995 if (sendLevel > MAX_GAIN_INT) {
3996 ALOGV("Track send level out of range: %04X", sendLevel);
3997 sendLevel = MAX_GAIN_INT;
3998 }
Andy Hung6be49402014-05-30 10:42:03 -07003999 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
4000 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08004001 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004002
Eric Laurent81784c32012-11-19 14:55:58 -08004003 // Delegate volume control to effect in track effect chain if needed
4004 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
4005 // Do not ramp volume if volume is controlled by effect
4006 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08004007 // Update remaining floating point volume levels
4008 vlf = (float)vl / (1 << 24);
4009 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08004010 track->mHasVolumeController = true;
4011 } else {
4012 // force no volume ramp when volume controller was just disabled or removed
4013 // from effect chain to avoid volume spike
4014 if (track->mHasVolumeController) {
4015 param = AudioMixer::VOLUME;
4016 }
4017 track->mHasVolumeController = false;
4018 }
4019
Eric Laurent81784c32012-11-19 14:55:58 -08004020 // XXX: these things DON'T need to be done each time
4021 mAudioMixer->setBufferProvider(name, track);
4022 mAudioMixer->enable(name);
4023
Andy Hung6be49402014-05-30 10:42:03 -07004024 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
4025 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
4026 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08004027 mAudioMixer->setParameter(
4028 name,
4029 AudioMixer::TRACK,
4030 AudioMixer::FORMAT, (void *)track->format());
4031 mAudioMixer->setParameter(
4032 name,
4033 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004034 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07004035 mAudioMixer->setParameter(
4036 name,
4037 AudioMixer::TRACK,
4038 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08004039 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07004040 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004041 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08004042 if (reqSampleRate == 0) {
4043 reqSampleRate = mSampleRate;
4044 } else if (reqSampleRate > maxSampleRate) {
4045 reqSampleRate = maxSampleRate;
4046 }
Eric Laurent81784c32012-11-19 14:55:58 -08004047 mAudioMixer->setParameter(
4048 name,
4049 AudioMixer::RESAMPLE,
4050 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004051 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004052
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004053 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004054 mAudioMixer->setParameter(
4055 name,
4056 AudioMixer::TIMESTRETCH,
4057 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004058 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004059
Andy Hung69aed5f2014-02-25 17:24:40 -08004060 /*
4061 * Select the appropriate output buffer for the track.
4062 *
Andy Hung98ef9782014-03-04 14:46:50 -08004063 * Tracks with effects go into their own effects chain buffer
4064 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08004065 *
4066 * Other tracks can use mMixerBuffer for higher precision
4067 * channel accumulation. If this buffer is enabled
4068 * (mMixerBufferEnabled true), then selected tracks will accumulate
4069 * into it.
4070 *
4071 */
4072 if (mMixerBufferEnabled
4073 && (track->mainBuffer() == mSinkBuffer
4074 || track->mainBuffer() == mMixerBuffer)) {
4075 mAudioMixer->setParameter(
4076 name,
4077 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004078 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08004079 mAudioMixer->setParameter(
4080 name,
4081 AudioMixer::TRACK,
4082 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
4083 // TODO: override track->mainBuffer()?
4084 mMixerBufferValid = true;
4085 } else {
4086 mAudioMixer->setParameter(
4087 name,
4088 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004089 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08004090 mAudioMixer->setParameter(
4091 name,
4092 AudioMixer::TRACK,
4093 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
4094 }
Eric Laurent81784c32012-11-19 14:55:58 -08004095 mAudioMixer->setParameter(
4096 name,
4097 AudioMixer::TRACK,
4098 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
4099
4100 // reset retry count
4101 track->mRetryCount = kMaxTrackRetries;
4102
4103 // If one track is ready, set the mixer ready if:
4104 // - the mixer was not ready during previous round OR
4105 // - no other track is not ready
4106 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
4107 mixerStatus != MIXER_TRACKS_ENABLED) {
4108 mixerStatus = MIXER_TRACKS_READY;
4109 }
4110 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004111 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hung08fb1742015-05-31 23:22:10 -07004112 ALOGV("track(%p) underrun, framesReady(%zu) < framesDesired(%zd)",
4113 track, framesReady, desiredFrames);
Glenn Kasten82aaf942013-07-17 16:05:07 -07004114 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004115 }
Eric Laurent81784c32012-11-19 14:55:58 -08004116 // clear effect chain input buffer if an active track underruns to avoid sending
4117 // previous audio buffer again to effects
4118 chain = getEffectChain_l(track->sessionId());
4119 if (chain != 0) {
4120 chain->clearInputBuffer();
4121 }
4122
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004123 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004124 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
4125 track->isStopped() || track->isPaused()) {
4126 // We have consumed all the buffers of this track.
4127 // Remove it from the list of active tracks.
4128 // TODO: use actual buffer filling status instead of latency when available from
4129 // audio HAL
4130 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
4131 size_t framesWritten = mBytesWritten / mFrameSize;
4132 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
4133 if (track->isStopped()) {
4134 track->reset();
4135 }
4136 tracksToRemove->add(track);
4137 }
4138 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08004139 // No buffers for this track. Give it a few chances to
4140 // fill a buffer, then remove it from active list.
4141 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004142 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004143 tracksToRemove->add(track);
4144 // indicate to client process that the track was disabled because of underrun;
4145 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07004146 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08004147 // If one track is not ready, mark the mixer also not ready if:
4148 // - the mixer was ready during previous round OR
4149 // - no other track is ready
4150 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
4151 mixerStatus != MIXER_TRACKS_READY) {
4152 mixerStatus = MIXER_TRACKS_ENABLED;
4153 }
4154 }
4155 mAudioMixer->disable(name);
4156 }
4157
4158 } // local variable scope to avoid goto warning
4159track_is_ready: ;
4160
4161 }
4162
4163 // Push the new FastMixer state if necessary
4164 bool pauseAudioWatchdog = false;
4165 if (didModify) {
4166 state->mFastTracksGen++;
4167 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4168 if (kUseFastMixer == FastMixer_Dynamic &&
4169 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4170 state->mCommand = FastMixerState::COLD_IDLE;
4171 state->mColdFutexAddr = &mFastMixerFutex;
4172 state->mColdGen++;
4173 mFastMixerFutex = 0;
4174 if (kUseFastMixer == FastMixer_Dynamic) {
4175 mNormalSink = mOutputSink;
4176 }
4177 // If we go into cold idle, need to wait for acknowledgement
4178 // so that fast mixer stops doing I/O.
4179 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4180 pauseAudioWatchdog = true;
4181 }
Eric Laurent81784c32012-11-19 14:55:58 -08004182 }
4183 if (sq != NULL) {
4184 sq->end(didModify);
4185 sq->push(block);
4186 }
4187#ifdef AUDIO_WATCHDOG
4188 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4189 mAudioWatchdog->pause();
4190 }
4191#endif
4192
4193 // Now perform the deferred reset on fast tracks that have stopped
4194 while (resetMask != 0) {
4195 size_t i = __builtin_ctz(resetMask);
4196 ALOG_ASSERT(i < count);
4197 resetMask &= ~(1 << i);
4198 sp<Track> t = mActiveTracks[i].promote();
4199 if (t == 0) {
4200 continue;
4201 }
4202 Track* track = t.get();
4203 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
4204 track->reset();
4205 }
4206
4207 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004208 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004209
Eric Laurent97d547d2014-09-02 14:45:53 -07004210 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
4211 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07004212 }
4213
4214 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07004215 // as long as there are effects we should clear the effects buffer, to avoid
4216 // passing a non-clean buffer to the effect chain
4217 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07004218 }
Andy Hung69aed5f2014-02-25 17:24:40 -08004219 // sink or mix buffer must be cleared if all tracks are connected to an
4220 // effect chain as in this case the mixer will not write to the sink or mix buffer
4221 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08004222 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4223 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08004224 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08004225 if (mMixerBufferValid) {
4226 memset(mMixerBuffer, 0, mMixerBufferSize);
4227 // TODO: In testing, mSinkBuffer below need not be cleared because
4228 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
4229 // after mixing.
4230 //
4231 // To enforce this guarantee:
4232 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4233 // (mixedTracks == 0 && fastTracks > 0))
4234 // must imply MIXER_TRACKS_READY.
4235 // Later, we may clear buffers regardless, and skip much of this logic.
4236 }
Andy Hung98ef9782014-03-04 14:46:50 -08004237 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07004238 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004239 }
4240
4241 // if any fast tracks, then status is ready
4242 mMixerStatusIgnoringFastTracks = mixerStatus;
4243 if (fastTracks > 0) {
4244 mixerStatus = MIXER_TRACKS_READY;
4245 }
4246 return mixerStatus;
4247}
4248
4249// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07004250int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
4251 audio_format_t format, int sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08004252{
Andy Hunge8a1ced2014-05-09 15:02:21 -07004253 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08004254}
4255
4256// deleteTrackName_l() must be called with ThreadBase::mLock held
4257void AudioFlinger::MixerThread::deleteTrackName_l(int name)
4258{
4259 ALOGV("remove track (%d) and delete from mixer", name);
4260 mAudioMixer->deleteTrackName(name);
4261}
4262
Eric Laurent10351942014-05-08 18:49:52 -07004263// checkForNewParameter_l() must be called with ThreadBase::mLock held
4264bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
4265 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004266{
Eric Laurent81784c32012-11-19 14:55:58 -08004267 bool reconfig = false;
4268
Eric Laurent10351942014-05-08 18:49:52 -07004269 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004270
Eric Laurent10351942014-05-08 18:49:52 -07004271 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
4272 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004273 if (mFastMixer != 0) {
Eric Laurent10351942014-05-08 18:49:52 -07004274 FastMixerStateQueue *sq = mFastMixer->sq();
4275 FastMixerState *state = sq->begin();
4276 if (!(state->mCommand & FastMixerState::IDLE)) {
4277 previousCommand = state->mCommand;
4278 state->mCommand = FastMixerState::HOT_IDLE;
4279 sq->end();
4280 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
4281 } else {
4282 sq->end(false /*didModify*/);
Eric Laurent81784c32012-11-19 14:55:58 -08004283 }
Eric Laurent10351942014-05-08 18:49:52 -07004284 }
Eric Laurent81784c32012-11-19 14:55:58 -08004285
Eric Laurent10351942014-05-08 18:49:52 -07004286 AudioParameter param = AudioParameter(keyValuePair);
4287 int value;
4288 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4289 reconfig = true;
4290 }
4291 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004292 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004293 status = BAD_VALUE;
4294 } else {
4295 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08004296 reconfig = true;
4297 }
Eric Laurent10351942014-05-08 18:49:52 -07004298 }
4299 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004300 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004301 status = BAD_VALUE;
4302 } else {
4303 // no need to save value, since it's constant
4304 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004305 }
Eric Laurent10351942014-05-08 18:49:52 -07004306 }
4307 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4308 // do not accept frame count changes if tracks are open as the track buffer
4309 // size depends on frame count and correct behavior would not be guaranteed
4310 // if frame count is changed after track creation
4311 if (!mTracks.isEmpty()) {
4312 status = INVALID_OPERATION;
4313 } else {
4314 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004315 }
Eric Laurent10351942014-05-08 18:49:52 -07004316 }
4317 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004318#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07004319 // when changing the audio output device, call addBatteryData to notify
4320 // the change
4321 if (mOutDevice != value) {
4322 uint32_t params = 0;
4323 // check whether speaker is on
4324 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
4325 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08004326 }
Eric Laurent10351942014-05-08 18:49:52 -07004327
4328 audio_devices_t deviceWithoutSpeaker
4329 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
4330 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07004331 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07004332 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4333 }
4334
4335 if (params != 0) {
4336 addBatteryData(params);
4337 }
4338 }
Eric Laurent81784c32012-11-19 14:55:58 -08004339#endif
4340
Eric Laurent10351942014-05-08 18:49:52 -07004341 // forward device change to effects that have requested to be
4342 // aware of attached audio device.
4343 if (value != AUDIO_DEVICE_NONE) {
4344 mOutDevice = value;
4345 for (size_t i = 0; i < mEffectChains.size(); i++) {
4346 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08004347 }
4348 }
Eric Laurent10351942014-05-08 18:49:52 -07004349 }
Eric Laurent81784c32012-11-19 14:55:58 -08004350
Eric Laurent10351942014-05-08 18:49:52 -07004351 if (status == NO_ERROR) {
4352 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4353 keyValuePair.string());
4354 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004355 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004356 mStandby = true;
4357 mBytesWritten = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004358 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Eric Laurent10351942014-05-08 18:49:52 -07004359 keyValuePair.string());
Eric Laurent81784c32012-11-19 14:55:58 -08004360 }
Eric Laurent10351942014-05-08 18:49:52 -07004361 if (status == NO_ERROR && reconfig) {
4362 readOutputParameters_l();
4363 delete mAudioMixer;
4364 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4365 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07004366 int name = getTrackName_l(mTracks[i]->mChannelMask,
4367 mTracks[i]->mFormat, mTracks[i]->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07004368 if (name < 0) {
4369 break;
4370 }
4371 mTracks[i]->mName = name;
4372 }
Eric Laurent73e26b62015-04-27 16:55:58 -07004373 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004374 }
Eric Laurent81784c32012-11-19 14:55:58 -08004375 }
4376
4377 if (!(previousCommand & FastMixerState::IDLE)) {
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004378 ALOG_ASSERT(mFastMixer != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08004379 FastMixerStateQueue *sq = mFastMixer->sq();
4380 FastMixerState *state = sq->begin();
4381 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
4382 state->mCommand = previousCommand;
4383 sq->end();
4384 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4385 }
4386
4387 return reconfig;
4388}
4389
4390
4391void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
4392{
4393 const size_t SIZE = 256;
4394 char buffer[SIZE];
4395 String8 result;
4396
4397 PlaybackThread::dumpInternals(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07004398 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Elliott Hughes87cebad2014-05-22 10:14:43 -07004399 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Eric Laurent81784c32012-11-19 14:55:58 -08004400
4401 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten2f90c512015-12-02 11:40:09 -08004402 // while we are dumping it. It may be inconsistent, but it won't mutate!
4403 // This is a large object so we place it on the heap.
4404 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
4405 const FastMixerDumpState *copy = new FastMixerDumpState(mFastMixerDumpState);
4406 copy->dump(fd);
4407 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08004408
4409#ifdef STATE_QUEUE_DUMP
4410 // Similar for state queue
4411 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4412 observerCopy.dump(fd);
4413 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4414 mutatorCopy.dump(fd);
4415#endif
4416
Glenn Kasten46909e72013-02-26 09:20:22 -08004417#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08004418 // Write the tee output to a .wav file
4419 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08004420#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004421
4422#ifdef AUDIO_WATCHDOG
4423 if (mAudioWatchdog != 0) {
4424 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4425 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4426 wdCopy.dump(fd);
4427 }
4428#endif
4429}
4430
4431uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4432{
4433 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4434}
4435
4436uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4437{
4438 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4439}
4440
4441void AudioFlinger::MixerThread::cacheParameters_l()
4442{
4443 PlaybackThread::cacheParameters_l();
4444
4445 // FIXME: Relaxed timing because of a certain device that can't meet latency
4446 // Should be reduced to 2x after the vendor fixes the driver issue
4447 // increase threshold again due to low power audio mode. The way this warning
4448 // threshold is calculated and its usefulness should be reconsidered anyway.
4449 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4450}
4451
4452// ----------------------------------------------------------------------------
4453
4454AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07004455 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device, bool systemReady)
4456 : PlaybackThread(audioFlinger, output, id, device, DIRECT, systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08004457 // mLeftVolFloat, mRightVolFloat
4458{
4459}
4460
Eric Laurentbfb1b832013-01-07 09:53:42 -08004461AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4462 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07004463 ThreadBase::type_t type, bool systemReady)
4464 : PlaybackThread(audioFlinger, output, id, device, type, systemReady)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004465 // mLeftVolFloat, mRightVolFloat
4466{
4467}
4468
Eric Laurent81784c32012-11-19 14:55:58 -08004469AudioFlinger::DirectOutputThread::~DirectOutputThread()
4470{
4471}
4472
Eric Laurentbfb1b832013-01-07 09:53:42 -08004473void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
4474{
4475 audio_track_cblk_t* cblk = track->cblk();
4476 float left, right;
4477
4478 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4479 left = right = 0;
4480 } else {
4481 float typeVolume = mStreamTypes[track->streamType()].volume;
4482 float v = mMasterVolume * typeVolume;
4483 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004484 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4485 left = float_from_gain(gain_minifloat_unpack_left(vlr));
4486 if (left > GAIN_FLOAT_UNITY) {
4487 left = GAIN_FLOAT_UNITY;
4488 }
4489 left *= v;
4490 right = float_from_gain(gain_minifloat_unpack_right(vlr));
4491 if (right > GAIN_FLOAT_UNITY) {
4492 right = GAIN_FLOAT_UNITY;
4493 }
4494 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004495 }
4496
4497 if (lastTrack) {
4498 if (left != mLeftVolFloat || right != mRightVolFloat) {
4499 mLeftVolFloat = left;
4500 mRightVolFloat = right;
4501
4502 // Convert volumes from float to 8.24
4503 uint32_t vl = (uint32_t)(left * (1 << 24));
4504 uint32_t vr = (uint32_t)(right * (1 << 24));
4505
4506 // Delegate volume control to effect in track effect chain if needed
4507 // only one effect chain can be present on DirectOutputThread, so if
4508 // there is one, the track is connected to it
4509 if (!mEffectChains.isEmpty()) {
4510 mEffectChains[0]->setVolume_l(&vl, &vr);
4511 left = (float)vl / (1 << 24);
4512 right = (float)vr / (1 << 24);
4513 }
4514 if (mOutput->stream->set_volume) {
4515 mOutput->stream->set_volume(mOutput->stream, left, right);
4516 }
4517 }
4518 }
4519}
4520
Phil Burk43b4dcc2015-06-09 16:53:44 -07004521void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
4522{
4523 sp<Track> previousTrack = mPreviousTrack.promote();
4524 sp<Track> latestTrack = mLatestActiveTrack.promote();
4525
Eric Laurent0f0631e2015-07-06 18:01:25 -07004526 if (previousTrack != 0 && latestTrack != 0) {
4527 if (mType == DIRECT) {
4528 if (previousTrack.get() != latestTrack.get()) {
4529 mFlushPending = true;
4530 }
4531 } else /* mType == OFFLOAD */ {
4532 if (previousTrack->sessionId() != latestTrack->sessionId()) {
4533 mFlushPending = true;
4534 }
4535 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004536 }
4537 PlaybackThread::onAddNewTrack_l();
4538}
Eric Laurentbfb1b832013-01-07 09:53:42 -08004539
Eric Laurent81784c32012-11-19 14:55:58 -08004540AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4541 Vector< sp<Track> > *tracksToRemove
4542)
4543{
Eric Laurentd595b7c2013-04-03 17:27:56 -07004544 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08004545 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004546 bool doHwPause = false;
4547 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004548
4549 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07004550 for (size_t i = 0; i < count; i++) {
4551 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08004552 // The track died recently
4553 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004554 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08004555 }
4556
Phil Burk43b4dcc2015-06-09 16:53:44 -07004557 if (t->isInvalid()) {
4558 ALOGW("An invalidated track shouldn't be in active list");
4559 tracksToRemove->add(t);
4560 continue;
4561 }
4562
Eric Laurent81784c32012-11-19 14:55:58 -08004563 Track* const track = t.get();
4564 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07004565 // Only consider last track started for volume and mixer state control.
4566 // In theory an older track could underrun and restart after the new one starts
4567 // but as we only care about the transition phase between two tracks on a
4568 // direct output, it is not a problem to ignore the underrun case.
4569 sp<Track> l = mLatestActiveTrack.promote();
4570 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08004571
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004572 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004573 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004574 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004575 doHwPause = true;
4576 mHwPaused = true;
4577 }
4578 tracksToRemove->add(track);
4579 } else if (track->isFlushPending()) {
4580 track->flushAck();
4581 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004582 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004583 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004584 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004585 track->resumeAck();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004586 if (last && mHwPaused) {
4587 doHwResume = true;
4588 mHwPaused = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004589 }
4590 }
4591
Eric Laurent81784c32012-11-19 14:55:58 -08004592 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08004593 // for all its buffers to be filled before processing it.
4594 // Allow draining the buffer in case the client
4595 // app does not call stop() and relies on underrun to stop:
4596 // hence the test on (track->mRetryCount > 1).
4597 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07004598 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08004599 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08004600 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkca5e6142015-07-14 09:42:29 -07004601 && (track->mRetryCount > 1) && audio_is_linear_pcm(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004602 minFrames = mNormalFrameCount;
4603 } else {
4604 minFrames = 1;
4605 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004606
Eric Laurentab5cdba2014-06-09 17:22:27 -07004607 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4608 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08004609 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004610 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08004611
4612 if (track->mFillingUpStatus == Track::FS_FILLED) {
4613 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004614 // make sure processVolume_l() will apply new volume even if 0
4615 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004616 if (!mHwSupportsPause) {
4617 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08004618 }
4619 }
4620
4621 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004622 processVolume_l(track, last);
4623 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004624 sp<Track> previousTrack = mPreviousTrack.promote();
4625 if (previousTrack != 0) {
4626 if (track != previousTrack.get()) {
4627 // Flush any data still being written from last track
4628 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07004629 // Invalidate previous track to force a seek when resuming.
4630 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004631 }
4632 }
4633 mPreviousTrack = track;
4634
Eric Laurentd595b7c2013-04-03 17:27:56 -07004635 // reset retry count
4636 track->mRetryCount = kMaxTrackRetriesDirect;
4637 mActiveTrack = t;
4638 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07004639 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004640 doHwResume = true;
4641 mHwPaused = false;
4642 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004643 }
Eric Laurent81784c32012-11-19 14:55:58 -08004644 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004645 // clear effect chain input buffer if the last active track started underruns
4646 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07004647 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004648 mEffectChains[0]->clearInputBuffer();
4649 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004650 if (track->isStopping_1()) {
4651 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07004652 if (last && mHwPaused) {
4653 doHwResume = true;
4654 mHwPaused = false;
4655 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004656 }
4657 if ((track->sharedBuffer() != 0) || track->isStopped() ||
4658 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004659 // We have consumed all the buffers of this track.
4660 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07004661 size_t audioHALFrames;
4662 if (audio_is_linear_pcm(mFormat)) {
4663 audioHALFrames = (latency_l() * mSampleRate) / 1000;
4664 } else {
4665 audioHALFrames = 0;
4666 }
4667
Eric Laurent81784c32012-11-19 14:55:58 -08004668 size_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07004669 if (mStandby || !last ||
4670 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004671 if (track->isStopping_2()) {
4672 track->mState = TrackBase::STOPPED;
4673 }
Eric Laurent81784c32012-11-19 14:55:58 -08004674 if (track->isStopped()) {
4675 track->reset();
4676 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004677 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08004678 }
4679 } else {
4680 // No buffers for this track. Give it a few chances to
4681 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07004682 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08004683 if (--(track->mRetryCount) <= 0) {
4684 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07004685 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004686 // indicate to client process that the track was disabled because of underrun;
4687 // it will then automatically call start() when data is available
4688 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004689 } else if (last) {
Phil Burkca5e6142015-07-14 09:42:29 -07004690 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
4691 "minFrames = %u, mFormat = %#x",
4692 track->framesReady(), minFrames, mFormat);
Eric Laurent81784c32012-11-19 14:55:58 -08004693 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07004694 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004695 doHwPause = true;
4696 mHwPaused = true;
4697 }
Eric Laurent81784c32012-11-19 14:55:58 -08004698 }
4699 }
4700 }
4701 }
4702
Eric Laurentd1f69b02014-12-15 14:33:13 -08004703 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07004704 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004705 for (size_t i = 0; i < mTracks.size(); i++) {
4706 if (mTracks[i]->isFlushPending()) {
4707 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004708 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004709 }
4710 }
4711 }
4712
4713 // make sure the pause/flush/resume sequence is executed in the right order.
4714 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4715 // before flush and then resume HW. This can happen in case of pause/flush/resume
4716 // if resume is received before pause is executed.
4717 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07004718 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004719 mOutput->stream->pause(mOutput->stream);
4720 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004721 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004722 flushHw_l();
4723 }
4724 if (mHwSupportsPause && !mStandby && doHwResume) {
4725 mOutput->stream->resume(mOutput->stream);
4726 }
Eric Laurent81784c32012-11-19 14:55:58 -08004727 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004728 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004729
4730 return mixerStatus;
4731}
4732
4733void AudioFlinger::DirectOutputThread::threadLoop_mix()
4734{
Eric Laurent81784c32012-11-19 14:55:58 -08004735 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08004736 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004737 // output audio to hardware
4738 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07004739 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004740 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08004741 status_t status = mActiveTrack->getNextBuffer(&buffer);
4742 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08004743 memset(curBuf, 0, frameCount * mFrameSize);
4744 break;
4745 }
4746 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
4747 frameCount -= buffer.frameCount;
4748 curBuf += buffer.frameCount * mFrameSize;
4749 mActiveTrack->releaseBuffer(&buffer);
4750 }
Andy Hung2098f272014-02-27 14:00:06 -08004751 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004752 mSleepTimeUs = 0;
4753 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08004754 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004755}
4756
4757void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
4758{
Eric Laurentd1f69b02014-12-15 14:33:13 -08004759 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004760 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004761 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004762 return;
4763 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004764 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004765 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004766 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004767 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004768 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004769 }
4770 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08004771 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004772 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004773 }
4774}
4775
Eric Laurentd1f69b02014-12-15 14:33:13 -08004776void AudioFlinger::DirectOutputThread::threadLoop_exit()
4777{
4778 {
4779 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08004780 for (size_t i = 0; i < mTracks.size(); i++) {
4781 if (mTracks[i]->isFlushPending()) {
4782 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004783 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004784 }
4785 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004786 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004787 flushHw_l();
4788 }
4789 }
4790 PlaybackThread::threadLoop_exit();
4791}
4792
4793// must be called with thread mutex locked
4794bool AudioFlinger::DirectOutputThread::shouldStandby_l()
4795{
4796 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07004797 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004798
4799 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4800 // after a timeout and we will enter standby then.
4801 if (mTracks.size() > 0) {
4802 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07004803 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
4804 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004805 }
4806
Eric Laurent5cff4032015-05-26 13:49:58 -07004807 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08004808}
4809
Eric Laurent81784c32012-11-19 14:55:58 -08004810// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004811int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Andy Hunge8a1ced2014-05-09 15:02:21 -07004812 audio_format_t format __unused, int sessionId __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004813{
4814 return 0;
4815}
4816
4817// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004818void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004819{
4820}
4821
Eric Laurent10351942014-05-08 18:49:52 -07004822// checkForNewParameter_l() must be called with ThreadBase::mLock held
4823bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
4824 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004825{
4826 bool reconfig = false;
4827
Eric Laurent10351942014-05-08 18:49:52 -07004828 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004829
Eric Laurent10351942014-05-08 18:49:52 -07004830 AudioParameter param = AudioParameter(keyValuePair);
4831 int value;
4832 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4833 // forward device change to effects that have requested to be
4834 // aware of attached audio device.
4835 if (value != AUDIO_DEVICE_NONE) {
4836 mOutDevice = value;
4837 for (size_t i = 0; i < mEffectChains.size(); i++) {
4838 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07004839 }
4840 }
Eric Laurent81784c32012-11-19 14:55:58 -08004841 }
Eric Laurent10351942014-05-08 18:49:52 -07004842 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4843 // do not accept frame count changes if tracks are open as the track buffer
4844 // size depends on frame count and correct behavior would not be garantied
4845 // if frame count is changed after track creation
4846 if (!mTracks.isEmpty()) {
4847 status = INVALID_OPERATION;
4848 } else {
4849 reconfig = true;
4850 }
4851 }
4852 if (status == NO_ERROR) {
4853 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4854 keyValuePair.string());
4855 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004856 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004857 mStandby = true;
4858 mBytesWritten = 0;
4859 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4860 keyValuePair.string());
4861 }
4862 if (status == NO_ERROR && reconfig) {
4863 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07004864 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004865 }
4866 }
4867
Eric Laurent81784c32012-11-19 14:55:58 -08004868 return reconfig;
4869}
4870
4871uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
4872{
4873 uint32_t time;
4874 if (audio_is_linear_pcm(mFormat)) {
4875 time = PlaybackThread::activeSleepTimeUs();
4876 } else {
4877 time = 10000;
4878 }
4879 return time;
4880}
4881
4882uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
4883{
4884 uint32_t time;
4885 if (audio_is_linear_pcm(mFormat)) {
4886 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
4887 } else {
4888 time = 10000;
4889 }
4890 return time;
4891}
4892
4893uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
4894{
4895 uint32_t time;
4896 if (audio_is_linear_pcm(mFormat)) {
4897 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
4898 } else {
4899 time = 10000;
4900 }
4901 return time;
4902}
4903
4904void AudioFlinger::DirectOutputThread::cacheParameters_l()
4905{
4906 PlaybackThread::cacheParameters_l();
4907
4908 // use shorter standby delay as on normal output to release
4909 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07004910 // no delay on outputs with HW A/V sync
4911 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004912 mStandbyDelayNs = 0;
Eric Laurent5cff4032015-05-26 13:49:58 -07004913 } else if ((mType == OFFLOAD) && !audio_is_linear_pcm(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004914 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07004915 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004916 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07004917 }
Eric Laurent81784c32012-11-19 14:55:58 -08004918}
4919
Eric Laurente659ef42014-09-29 13:06:46 -07004920void AudioFlinger::DirectOutputThread::flushHw_l()
4921{
Phil Burk062e67a2015-02-11 13:40:50 -08004922 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08004923 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07004924 mFlushPending = false;
Eric Laurente659ef42014-09-29 13:06:46 -07004925}
4926
Eric Laurent81784c32012-11-19 14:55:58 -08004927// ----------------------------------------------------------------------------
4928
Eric Laurentbfb1b832013-01-07 09:53:42 -08004929AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07004930 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004931 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07004932 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07004933 mWriteAckSequence(0),
4934 mDrainSequence(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004935{
4936}
4937
4938AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
4939{
4940}
4941
4942void AudioFlinger::AsyncCallbackThread::onFirstRef()
4943{
4944 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
4945}
4946
4947bool AudioFlinger::AsyncCallbackThread::threadLoop()
4948{
4949 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004950 uint32_t writeAckSequence;
4951 uint32_t drainSequence;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004952
4953 {
4954 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08004955 while (!((mWriteAckSequence & 1) ||
4956 (mDrainSequence & 1) ||
4957 exitPending())) {
4958 mWaitWorkCV.wait(mLock);
4959 }
4960
Eric Laurentbfb1b832013-01-07 09:53:42 -08004961 if (exitPending()) {
4962 break;
4963 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004964 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
4965 mWriteAckSequence, mDrainSequence);
4966 writeAckSequence = mWriteAckSequence;
4967 mWriteAckSequence &= ~1;
4968 drainSequence = mDrainSequence;
4969 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004970 }
4971 {
Eric Laurent4de95592013-09-26 15:28:21 -07004972 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
4973 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004974 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004975 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004976 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004977 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004978 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004979 }
4980 }
4981 }
4982 }
4983 return false;
4984}
4985
4986void AudioFlinger::AsyncCallbackThread::exit()
4987{
4988 ALOGV("AsyncCallbackThread::exit");
4989 Mutex::Autolock _l(mLock);
4990 requestExit();
4991 mWaitWorkCV.broadcast();
4992}
4993
Eric Laurent3b4529e2013-09-05 18:09:19 -07004994void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004995{
4996 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004997 // bit 0 is cleared
4998 mWriteAckSequence = sequence << 1;
4999}
5000
5001void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
5002{
5003 Mutex::Autolock _l(mLock);
5004 // ignore unexpected callbacks
5005 if (mWriteAckSequence & 2) {
5006 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005007 mWaitWorkCV.signal();
5008 }
5009}
5010
Eric Laurent3b4529e2013-09-05 18:09:19 -07005011void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005012{
5013 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005014 // bit 0 is cleared
5015 mDrainSequence = sequence << 1;
5016}
5017
5018void AudioFlinger::AsyncCallbackThread::resetDraining()
5019{
5020 Mutex::Autolock _l(mLock);
5021 // ignore unexpected callbacks
5022 if (mDrainSequence & 2) {
5023 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005024 mWaitWorkCV.signal();
5025 }
5026}
5027
5028
5029// ----------------------------------------------------------------------------
5030AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07005031 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady)
5032 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady),
Eric Laurentd7e59222013-11-15 12:02:28 -08005033 mPausedBytesRemaining(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005034{
Eric Laurentfd477972013-10-25 18:10:40 -07005035 //FIXME: mStandby should be set to true by ThreadBase constructor
5036 mStandby = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005037}
5038
Eric Laurentbfb1b832013-01-07 09:53:42 -08005039void AudioFlinger::OffloadThread::threadLoop_exit()
5040{
5041 if (mFlushPending || mHwPaused) {
5042 // If a flush is pending or track was paused, just discard buffered data
5043 flushHw_l();
5044 } else {
5045 mMixerStatus = MIXER_DRAIN_ALL;
5046 threadLoop_drain();
5047 }
Uday Gupta56604aa2014-05-13 11:19:17 -07005048 if (mUseAsyncWrite) {
5049 ALOG_ASSERT(mCallbackThread != 0);
5050 mCallbackThread->exit();
5051 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005052 PlaybackThread::threadLoop_exit();
5053}
5054
5055AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
5056 Vector< sp<Track> > *tracksToRemove
5057)
5058{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005059 size_t count = mActiveTracks.size();
5060
5061 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07005062 bool doHwPause = false;
5063 bool doHwResume = false;
5064
Eric Laurentede6c3b2013-09-19 14:37:46 -07005065 ALOGV("OffloadThread::prepareTracks_l active tracks %d", count);
5066
Eric Laurentbfb1b832013-01-07 09:53:42 -08005067 // find out which tracks need to be processed
5068 for (size_t i = 0; i < count; i++) {
5069 sp<Track> t = mActiveTracks[i].promote();
5070 // The track died recently
5071 if (t == 0) {
5072 continue;
5073 }
5074 Track* const track = t.get();
5075 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07005076 // Only consider last track started for volume and mixer state control.
5077 // In theory an older track could underrun and restart after the new one starts
5078 // but as we only care about the transition phase between two tracks on a
5079 // direct output, it is not a problem to ignore the underrun case.
5080 sp<Track> l = mLatestActiveTrack.promote();
5081 bool last = l.get() == track;
5082
Haynes Mathew George7844f672014-01-15 12:32:55 -08005083 if (track->isInvalid()) {
5084 ALOGW("An invalidated track shouldn't be in active list");
5085 tracksToRemove->add(track);
5086 continue;
5087 }
5088
5089 if (track->mState == TrackBase::IDLE) {
5090 ALOGW("An idle track shouldn't be in active list");
5091 continue;
5092 }
5093
Eric Laurentbfb1b832013-01-07 09:53:42 -08005094 if (track->isPausing()) {
5095 track->setPaused();
5096 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07005097 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07005098 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005099 mHwPaused = true;
5100 }
5101 // If we were part way through writing the mixbuffer to
5102 // the HAL we must save this until we resume
5103 // BUG - this will be wrong if a different track is made active,
5104 // in that case we want to discard the pending data in the
5105 // mixbuffer and tell the client to present it again when the
5106 // track is resumed
5107 mPausedWriteLength = mCurrentWriteLength;
5108 mPausedBytesRemaining = mBytesRemaining;
5109 mBytesRemaining = 0; // stop writing
5110 }
5111 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08005112 } else if (track->isFlushPending()) {
5113 track->flushAck();
5114 if (last) {
5115 mFlushPending = true;
5116 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005117 } else if (track->isResumePending()){
5118 track->resumeAck();
5119 if (last) {
5120 if (mPausedBytesRemaining) {
5121 // Need to continue write that was interrupted
5122 mCurrentWriteLength = mPausedWriteLength;
5123 mBytesRemaining = mPausedBytesRemaining;
5124 mPausedBytesRemaining = 0;
5125 }
5126 if (mHwPaused) {
5127 doHwResume = true;
5128 mHwPaused = false;
5129 // threadLoop_mix() will handle the case that we need to
5130 // resume an interrupted write
5131 }
5132 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005133 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005134
5135 // Do not handle new data in this iteration even if track->framesReady()
5136 mixerStatus = MIXER_TRACKS_ENABLED;
5137 }
5138 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07005139 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005140 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005141 if (track->mFillingUpStatus == Track::FS_FILLED) {
5142 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07005143 // make sure processVolume_l() will apply new volume even if 0
5144 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005145 }
5146
5147 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08005148 sp<Track> previousTrack = mPreviousTrack.promote();
5149 if (previousTrack != 0) {
5150 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08005151 // Flush any data still being written from last track
5152 mBytesRemaining = 0;
5153 if (mPausedBytesRemaining) {
5154 // Last track was paused so we also need to flush saved
5155 // mixbuffer state and invalidate track so that it will
5156 // re-submit that unwritten data when it is next resumed
5157 mPausedBytesRemaining = 0;
5158 // Invalidate is a bit drastic - would be more efficient
5159 // to have a flag to tell client that some of the
5160 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08005161 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005162 }
5163 // flush data already sent to the DSP if changing audio session as audio
5164 // comes from a different source. Also invalidate previous track to force a
5165 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08005166 if (previousTrack->sessionId() != track->sessionId()) {
5167 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005168 }
5169 }
5170 }
5171 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005172 // reset retry count
5173 track->mRetryCount = kMaxTrackRetriesOffload;
5174 mActiveTrack = t;
5175 mixerStatus = MIXER_TRACKS_READY;
5176 }
5177 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005178 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005179 if (track->isStopping_1()) {
5180 // Hardware buffer can hold a large amount of audio so we must
5181 // wait for all current track's data to drain before we say
5182 // that the track is stopped.
5183 if (mBytesRemaining == 0) {
5184 // Only start draining when all data in mixbuffer
5185 // has been written
5186 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
5187 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005188 // do not drain if no data was ever sent to HAL (mStandby == true)
5189 if (last && !mStandby) {
Eric Laurent1b9f9b12013-11-12 19:10:17 -08005190 // do not modify drain sequence if we are already draining. This happens
5191 // when resuming from pause after drain.
5192 if ((mDrainSequence & 1) == 0) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005193 mSleepTimeUs = 0;
5194 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent1b9f9b12013-11-12 19:10:17 -08005195 mixerStatus = MIXER_DRAIN_TRACK;
5196 mDrainSequence += 2;
5197 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005198 if (mHwPaused) {
5199 // It is possible to move from PAUSED to STOPPING_1 without
5200 // a resume so we must ensure hardware is running
Eric Laurent1b9f9b12013-11-12 19:10:17 -08005201 doHwResume = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005202 mHwPaused = false;
5203 }
5204 }
5205 }
5206 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005207 // Drain has completed or we are in standby, signal presentation complete
5208 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005209 track->mState = TrackBase::STOPPED;
5210 size_t audioHALFrames =
5211 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
5212 size_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08005213 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005214 track->presentationComplete(framesWritten, audioHALFrames);
5215 track->reset();
5216 tracksToRemove->add(track);
5217 }
5218 } else {
5219 // No buffers for this track. Give it a few chances to
5220 // fill a buffer, then remove it from active list.
5221 if (--(track->mRetryCount) <= 0) {
5222 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
5223 track->name());
5224 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08005225 // indicate to client process that the track was disabled because of underrun;
5226 // it will then automatically call start() when data is available
5227 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005228 } else if (last){
5229 mixerStatus = MIXER_TRACKS_ENABLED;
5230 }
5231 }
5232 }
5233 // compute volume for this track
5234 processVolume_l(track, last);
5235 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005236
Eric Laurentea0fade2013-10-04 16:23:48 -07005237 // make sure the pause/flush/resume sequence is executed in the right order.
5238 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5239 // before flush and then resume HW. This can happen in case of pause/flush/resume
5240 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07005241 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurent972a1732013-09-04 09:42:59 -07005242 mOutput->stream->pause(mOutput->stream);
5243 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005244 if (mFlushPending) {
5245 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005246 }
Eric Laurentfd477972013-10-25 18:10:40 -07005247 if (!mStandby && doHwResume) {
Eric Laurent972a1732013-09-04 09:42:59 -07005248 mOutput->stream->resume(mOutput->stream);
5249 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005250
Eric Laurentbfb1b832013-01-07 09:53:42 -08005251 // remove all the tracks that need to be...
5252 removeTracks_l(*tracksToRemove);
5253
5254 return mixerStatus;
5255}
5256
Eric Laurentbfb1b832013-01-07 09:53:42 -08005257// must be called with thread mutex locked
5258bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
5259{
Eric Laurent3b4529e2013-09-05 18:09:19 -07005260 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
5261 mWriteAckSequence, mDrainSequence);
5262 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005263 return true;
5264 }
5265 return false;
5266}
5267
Eric Laurentbfb1b832013-01-07 09:53:42 -08005268bool AudioFlinger::OffloadThread::waitingAsyncCallback()
5269{
5270 Mutex::Autolock _l(mLock);
5271 return waitingAsyncCallback_l();
5272}
5273
5274void AudioFlinger::OffloadThread::flushHw_l()
5275{
Eric Laurente659ef42014-09-29 13:06:46 -07005276 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005277 // Flush anything still waiting in the mixbuffer
5278 mCurrentWriteLength = 0;
5279 mBytesRemaining = 0;
5280 mPausedWriteLength = 0;
5281 mPausedBytesRemaining = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08005282
Eric Laurentbfb1b832013-01-07 09:53:42 -08005283 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005284 // discard any pending drain or write ack by incrementing sequence
5285 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5286 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005287 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005288 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5289 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005290 }
5291}
5292
5293// ----------------------------------------------------------------------------
5294
Eric Laurent81784c32012-11-19 14:55:58 -08005295AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07005296 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08005297 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
Eric Laurent72e3f392015-05-20 14:43:50 -07005298 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08005299 mWaitTimeMs(UINT_MAX)
5300{
5301 addOutputTrack(mainThread);
5302}
5303
5304AudioFlinger::DuplicatingThread::~DuplicatingThread()
5305{
5306 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5307 mOutputTracks[i]->destroy();
5308 }
5309}
5310
5311void AudioFlinger::DuplicatingThread::threadLoop_mix()
5312{
5313 // mix buffers...
5314 if (outputsReady(outputTracks)) {
5315 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
5316 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08005317 if (mMixerBufferValid) {
5318 memset(mMixerBuffer, 0, mMixerBufferSize);
5319 } else {
5320 memset(mSinkBuffer, 0, mSinkBufferSize);
5321 }
Eric Laurent81784c32012-11-19 14:55:58 -08005322 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005323 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005324 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005325 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005326 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005327}
5328
5329void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
5330{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005331 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005332 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005333 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005334 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005335 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005336 }
5337 } else if (mBytesWritten != 0) {
5338 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5339 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005340 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005341 } else {
5342 // flush remaining overflow buffers in output tracks
5343 writeFrames = 0;
5344 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005345 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005346 }
5347}
5348
Eric Laurentbfb1b832013-01-07 09:53:42 -08005349ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005350{
5351 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08005352 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005353 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07005354 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08005355 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005356}
5357
5358void AudioFlinger::DuplicatingThread::threadLoop_standby()
5359{
5360 // DuplicatingThread implements standby by stopping all tracks
5361 for (size_t i = 0; i < outputTracks.size(); i++) {
5362 outputTracks[i]->stop();
5363 }
5364}
5365
5366void AudioFlinger::DuplicatingThread::saveOutputTracks()
5367{
5368 outputTracks = mOutputTracks;
5369}
5370
5371void AudioFlinger::DuplicatingThread::clearOutputTracks()
5372{
5373 outputTracks.clear();
5374}
5375
5376void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
5377{
5378 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08005379 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
5380 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
5381 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
5382 const size_t frameCount =
5383 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
5384 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
5385 // from different OutputTracks and their associated MixerThreads (e.g. one may
5386 // nearly empty and the other may be dropping data).
5387
5388 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08005389 this,
5390 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08005391 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08005392 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005393 frameCount,
5394 IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08005395 if (outputTrack->cblk() != NULL) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005396 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
Eric Laurent81784c32012-11-19 14:55:58 -08005397 mOutputTracks.add(outputTrack);
Andy Hungc25b84a2015-01-14 19:04:10 -08005398 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005399 updateWaitTime_l();
5400 }
5401}
5402
5403void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
5404{
5405 Mutex::Autolock _l(mLock);
5406 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5407 if (mOutputTracks[i]->thread() == thread) {
5408 mOutputTracks[i]->destroy();
5409 mOutputTracks.removeAt(i);
5410 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07005411 if (thread->getOutput() == mOutput) {
5412 mOutput = NULL;
5413 }
Eric Laurent81784c32012-11-19 14:55:58 -08005414 return;
5415 }
5416 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07005417 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005418}
5419
5420// caller must hold mLock
5421void AudioFlinger::DuplicatingThread::updateWaitTime_l()
5422{
5423 mWaitTimeMs = UINT_MAX;
5424 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5425 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
5426 if (strong != 0) {
5427 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
5428 if (waitTimeMs < mWaitTimeMs) {
5429 mWaitTimeMs = waitTimeMs;
5430 }
5431 }
5432 }
5433}
5434
5435
5436bool AudioFlinger::DuplicatingThread::outputsReady(
5437 const SortedVector< sp<OutputTrack> > &outputTracks)
5438{
5439 for (size_t i = 0; i < outputTracks.size(); i++) {
5440 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
5441 if (thread == 0) {
5442 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
5443 outputTracks[i].get());
5444 return false;
5445 }
5446 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5447 // see note at standby() declaration
5448 if (playbackThread->standby() && !playbackThread->isSuspended()) {
5449 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
5450 thread.get());
5451 return false;
5452 }
5453 }
5454 return true;
5455}
5456
5457uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
5458{
5459 return (mWaitTimeMs * 1000) / 2;
5460}
5461
5462void AudioFlinger::DuplicatingThread::cacheParameters_l()
5463{
5464 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
5465 updateWaitTime_l();
5466
5467 MixerThread::cacheParameters_l();
5468}
5469
5470// ----------------------------------------------------------------------------
5471// Record
5472// ----------------------------------------------------------------------------
5473
5474AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5475 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08005476 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08005477 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07005478 audio_devices_t inDevice,
5479 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08005480#ifdef TEE_SINK
5481 , const sp<NBAIO_Sink>& teeSink
5482#endif
5483 ) :
Eric Laurent72e3f392015-05-20 14:43:50 -07005484 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005485 mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005486 // mRsmpInFrames and mRsmpInFramesP2 are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005487 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08005488#ifdef TEE_SINK
5489 , mTeeSink(teeSink)
5490#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07005491 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
5492 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005493 // mFastCapture below
5494 , mFastCaptureFutex(0)
5495 // mInputSource
5496 // mPipeSink
5497 // mPipeSource
5498 , mPipeFramesP2(0)
5499 // mPipeMemory
5500 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005501 , mFastTrackAvail(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005502{
Glenn Kastend7dca052015-03-05 16:05:54 -08005503 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
5504 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08005505
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005506 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005507
5508 // create an NBAIO source for the HAL input stream, and negotiate
5509 mInputSource = new AudioStreamInSource(input->stream);
5510 size_t numCounterOffers = 0;
5511 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
5512 ssize_t index = mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
5513 ALOG_ASSERT(index == 0);
5514
5515 // initialize fast capture depending on configuration
5516 bool initFastCapture;
5517 switch (kUseFastCapture) {
5518 case FastCapture_Never:
5519 initFastCapture = false;
5520 break;
5521 case FastCapture_Always:
5522 initFastCapture = true;
5523 break;
5524 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07005525 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005526 break;
5527 // case FastCapture_Dynamic:
5528 }
5529
5530 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07005531 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005532 NBAIO_Format format = mInputSource->format();
Glenn Kasten49d00ad2014-07-21 11:22:03 -07005533 size_t pipeFramesP2 = roundup(mSampleRate / 25); // double-buffering of 20 ms each
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005534 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
5535 void *pipeBuffer;
5536 const sp<MemoryDealer> roHeap(readOnlyHeap());
5537 sp<IMemory> pipeMemory;
5538 if ((roHeap == 0) ||
5539 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
5540 (pipeBuffer = pipeMemory->pointer()) == NULL) {
5541 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
5542 goto failed;
5543 }
5544 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
5545 memset(pipeBuffer, 0, pipeSize);
5546 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
5547 const NBAIO_Format offers[1] = {format};
5548 size_t numCounterOffers = 0;
5549 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
5550 ALOG_ASSERT(index == 0);
5551 mPipeSink = pipe;
5552 PipeReader *pipeReader = new PipeReader(*pipe);
5553 numCounterOffers = 0;
5554 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
5555 ALOG_ASSERT(index == 0);
5556 mPipeSource = pipeReader;
5557 mPipeFramesP2 = pipeFramesP2;
5558 mPipeMemory = pipeMemory;
5559
5560 // create fast capture
5561 mFastCapture = new FastCapture();
5562 FastCaptureStateQueue *sq = mFastCapture->sq();
5563#ifdef STATE_QUEUE_DUMP
5564 // FIXME
5565#endif
5566 FastCaptureState *state = sq->begin();
5567 state->mCblk = NULL;
5568 state->mInputSource = mInputSource.get();
5569 state->mInputSourceGen++;
5570 state->mPipeSink = pipe;
5571 state->mPipeSinkGen++;
5572 state->mFrameCount = mFrameCount;
5573 state->mCommand = FastCaptureState::COLD_IDLE;
5574 // already done in constructor initialization list
5575 //mFastCaptureFutex = 0;
5576 state->mColdFutexAddr = &mFastCaptureFutex;
5577 state->mColdGen++;
5578 state->mDumpState = &mFastCaptureDumpState;
5579#ifdef TEE_SINK
5580 // FIXME
5581#endif
5582 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
5583 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
5584 sq->end();
5585 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5586
5587 // start the fast capture
5588 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
5589 pid_t tid = mFastCapture->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07005590 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005591#ifdef AUDIO_WATCHDOG
5592 // FIXME
5593#endif
5594
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005595 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005596 }
5597failed: ;
5598
5599 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08005600}
5601
Eric Laurent81784c32012-11-19 14:55:58 -08005602AudioFlinger::RecordThread::~RecordThread()
5603{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005604 if (mFastCapture != 0) {
5605 FastCaptureStateQueue *sq = mFastCapture->sq();
5606 FastCaptureState *state = sq->begin();
5607 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5608 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5609 if (old == -1) {
5610 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5611 }
5612 }
5613 state->mCommand = FastCaptureState::EXIT;
5614 sq->end();
5615 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5616 mFastCapture->join();
5617 mFastCapture.clear();
5618 }
5619 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07005620 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07005621 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08005622}
5623
5624void AudioFlinger::RecordThread::onFirstRef()
5625{
Glenn Kastend7dca052015-03-05 16:05:54 -08005626 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08005627}
5628
Eric Laurent81784c32012-11-19 14:55:58 -08005629bool AudioFlinger::RecordThread::threadLoop()
5630{
Eric Laurent81784c32012-11-19 14:55:58 -08005631 nsecs_t lastWarning = 0;
5632
5633 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08005634
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005635reacquire_wakelock:
5636 sp<RecordTrack> activeTrack;
Glenn Kasten2b806402013-11-20 16:37:38 -08005637 int activeTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005638 {
5639 Mutex::Autolock _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005640 size_t size = mActiveTracks.size();
5641 activeTracksGen = mActiveTracksGen;
5642 if (size > 0) {
5643 // FIXME an arbitrary choice
5644 activeTrack = mActiveTracks[0];
5645 acquireWakeLock_l(activeTrack->uid());
5646 if (size > 1) {
5647 SortedVector<int> tmp;
5648 for (size_t i = 0; i < size; i++) {
5649 tmp.add(mActiveTracks[i]->uid());
5650 }
5651 updateWakeLockUids_l(tmp);
5652 }
5653 } else {
5654 acquireWakeLock_l(-1);
5655 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005656 }
5657
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005658 // used to request a deferred sleep, to be executed later while mutex is unlocked
5659 uint32_t sleepUs = 0;
5660
5661 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005662 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005663 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07005664
Glenn Kasten5edadd42013-08-14 16:30:49 -07005665 // sleep with mutex unlocked
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005666 if (sleepUs > 0) {
Glenn Kastene7754022014-10-31 12:11:26 -07005667 ATRACE_BEGIN("sleep");
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005668 usleep(sleepUs);
Glenn Kastene7754022014-10-31 12:11:26 -07005669 ATRACE_END();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005670 sleepUs = 0;
Glenn Kasten5edadd42013-08-14 16:30:49 -07005671 }
5672
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005673 // activeTracks accumulates a copy of a subset of mActiveTracks
5674 Vector< sp<RecordTrack> > activeTracks;
5675
Glenn Kasten735f45f2014-08-18 15:51:59 -07005676 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005677 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07005678
Glenn Kasten735f45f2014-08-18 15:51:59 -07005679 // reference to a fast track which is about to be removed
5680 sp<RecordTrack> fastTrackToRemove;
5681
Eric Laurent81784c32012-11-19 14:55:58 -08005682 { // scope for mLock
5683 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08005684
Eric Laurent021cf962014-05-13 10:18:14 -07005685 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005686
Eric Laurent000a4192014-01-29 15:17:32 -08005687 // check exitPending here because checkForNewParameters_l() and
5688 // checkForNewParameters_l() can temporarily release mLock
5689 if (exitPending()) {
5690 break;
5691 }
5692
Glenn Kasten2b806402013-11-20 16:37:38 -08005693 // if no active track(s), then standby and release wakelock
5694 size_t size = mActiveTracks.size();
5695 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07005696 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005697 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08005698 releaseWakeLock_l();
5699 ALOGV("RecordThread: loop stopping");
5700 // go to sleep
5701 mWaitWorkCV.wait(mLock);
5702 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005703 goto reacquire_wakelock;
5704 }
5705
Glenn Kasten2b806402013-11-20 16:37:38 -08005706 if (mActiveTracksGen != activeTracksGen) {
5707 activeTracksGen = mActiveTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005708 SortedVector<int> tmp;
Glenn Kasten2b806402013-11-20 16:37:38 -08005709 for (size_t i = 0; i < size; i++) {
5710 tmp.add(mActiveTracks[i]->uid());
5711 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005712 updateWakeLockUids_l(tmp);
Eric Laurent81784c32012-11-19 14:55:58 -08005713 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005714
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005715 bool doBroadcast = false;
5716 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07005717
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005718 activeTrack = mActiveTracks[i];
5719 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07005720 if (activeTrack->isFastTrack()) {
5721 ALOG_ASSERT(fastTrackToRemove == 0);
5722 fastTrackToRemove = activeTrack;
5723 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005724 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08005725 mActiveTracks.remove(activeTrack);
5726 mActiveTracksGen++;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005727 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07005728 continue;
5729 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005730
5731 TrackBase::track_state activeTrackState = activeTrack->mState;
5732 switch (activeTrackState) {
5733
5734 case TrackBase::PAUSING:
5735 mActiveTracks.remove(activeTrack);
5736 mActiveTracksGen++;
5737 doBroadcast = true;
5738 size--;
5739 continue;
5740
5741 case TrackBase::STARTING_1:
5742 sleepUs = 10000;
5743 i++;
5744 continue;
5745
5746 case TrackBase::STARTING_2:
5747 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005748 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07005749 activeTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005750 break;
5751
5752 case TrackBase::ACTIVE:
5753 break;
5754
5755 case TrackBase::IDLE:
5756 i++;
5757 continue;
5758
5759 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08005760 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07005761 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005762
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005763 activeTracks.add(activeTrack);
5764 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07005765
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005766 if (activeTrack->isFastTrack()) {
5767 ALOG_ASSERT(!mFastTrackAvail);
5768 ALOG_ASSERT(fastTrack == 0);
5769 fastTrack = activeTrack;
5770 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005771 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005772 if (doBroadcast) {
5773 mStartStopCond.broadcast();
5774 }
5775
5776 // sleep if there are no active tracks to process
5777 if (activeTracks.size() == 0) {
5778 if (sleepUs == 0) {
5779 sleepUs = kRecordThreadSleepUs;
5780 }
5781 continue;
5782 }
5783 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07005784
Eric Laurent81784c32012-11-19 14:55:58 -08005785 lockEffectChains_l(effectChains);
5786 }
5787
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005788 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07005789
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005790 size_t size = effectChains.size();
5791 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005792 // thread mutex is not locked, but effect chain is locked
5793 effectChains[i]->process_l();
5794 }
5795
Glenn Kasten735f45f2014-08-18 15:51:59 -07005796 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005797 if (mFastCapture != 0) {
5798 FastCaptureStateQueue *sq = mFastCapture->sq();
5799 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07005800 bool didModify = false;
5801 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005802 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
5803 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
5804 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5805 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5806 if (old == -1) {
5807 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5808 }
5809 }
5810 state->mCommand = FastCaptureState::READ_WRITE;
5811#if 0 // FIXME
5812 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08005813 FastThreadDumpState::kSamplingNforLowRamDevice :
5814 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005815#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07005816 didModify = true;
5817 }
5818 audio_track_cblk_t *cblkOld = state->mCblk;
5819 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
5820 if (cblkNew != cblkOld) {
5821 state->mCblk = cblkNew;
5822 // block until acked if removing a fast track
5823 if (cblkOld != NULL) {
5824 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
5825 }
5826 didModify = true;
5827 }
5828 sq->end(didModify);
5829 if (didModify) {
5830 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005831#if 0
5832 if (kUseFastCapture == FastCapture_Dynamic) {
5833 mNormalSource = mPipeSource;
5834 }
5835#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005836 }
5837 }
5838
Glenn Kasten735f45f2014-08-18 15:51:59 -07005839 // now run the fast track destructor with thread mutex unlocked
5840 fastTrackToRemove.clear();
5841
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005842 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
5843 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
5844 // slow, then this RecordThread will overrun by not calling HAL read often enough.
5845 // If destination is non-contiguous, first read past the nominal end of buffer, then
5846 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005847
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005848 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005849 ssize_t framesRead;
5850
5851 // If an NBAIO source is present, use it to read the normal capture's data
5852 if (mPipeSource != 0) {
5853 size_t framesToRead = mBufferSize / mFrameSize;
Andy Hung57446612015-04-19 23:56:46 -07005854 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005855 framesToRead, AudioBufferProvider::kInvalidPTS);
5856 if (framesRead == 0) {
5857 // since pipe is non-blocking, simulate blocking input
5858 sleepUs = (framesToRead * 1000000LL) / mSampleRate;
5859 }
5860 // otherwise use the HAL / AudioStreamIn directly
5861 } else {
5862 ssize_t bytesRead = mInput->stream->read(mInput->stream,
Andy Hung57446612015-04-19 23:56:46 -07005863 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005864 if (bytesRead < 0) {
5865 framesRead = bytesRead;
5866 } else {
5867 framesRead = bytesRead / mFrameSize;
5868 }
5869 }
5870
5871 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
5872 ALOGE("read failed: framesRead=%d", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005873 // Force input into standby so that it tries to recover at next read attempt
5874 inputStandBy();
5875 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005876 }
5877 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005878 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005879 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005880 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005881
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005882 if (mTeeSink != 0) {
Andy Hung57446612015-04-19 23:56:46 -07005883 (void) mTeeSink->write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005884 }
5885 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005886 {
5887 size_t part1 = mRsmpInFramesP2 - rear;
5888 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07005889 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005890 (framesRead - part1) * mFrameSize);
5891 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005892 }
5893 rear = mRsmpInRear += framesRead;
5894
5895 size = activeTracks.size();
5896 // loop over each active track
5897 for (size_t i = 0; i < size; i++) {
5898 activeTrack = activeTracks[i];
5899
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005900 // skip fast tracks, as those are handled directly by FastCapture
5901 if (activeTrack->isFastTrack()) {
5902 continue;
5903 }
5904
Andy Hung73c02e42015-03-29 01:13:58 -07005905 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07005906 // TODO: Update the activeTrack buffer converter in case of reconfigure.
5907
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005908 enum {
5909 OVERRUN_UNKNOWN,
5910 OVERRUN_TRUE,
5911 OVERRUN_FALSE
5912 } overrun = OVERRUN_UNKNOWN;
5913
5914 // loop over getNextBuffer to handle circular sink
5915 for (;;) {
5916
5917 activeTrack->mSink.frameCount = ~0;
5918 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
5919 size_t framesOut = activeTrack->mSink.frameCount;
5920 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
5921
Andy Hung73c02e42015-03-29 01:13:58 -07005922 // check available frames and handle overrun conditions
5923 // if the record track isn't draining fast enough.
5924 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005925 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07005926 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
5927 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005928 overrun = OVERRUN_TRUE;
5929 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005930 if (framesOut == 0 || framesIn == 0) {
5931 break;
5932 }
5933
Andy Hung6770c6f2015-04-07 13:43:36 -07005934 // Don't allow framesOut to be larger than what is possible with resampling
5935 // from framesIn.
5936 // This isn't strictly necessary but helps limit buffer resizing in
5937 // RecordBufferConverter. TODO: remove when no longer needed.
5938 framesOut = min(framesOut,
5939 destinationFramesPossible(
5940 framesIn, mSampleRate, activeTrack->mSampleRate));
Andy Hung97a893e2015-03-29 01:03:07 -07005941 // process frames from the RecordThread buffer provider to the RecordTrack buffer
5942 framesOut = activeTrack->mRecordBufferConverter->convert(
5943 activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005944
5945 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
5946 overrun = OVERRUN_FALSE;
5947 }
5948
5949 if (activeTrack->mFramesToDrop == 0) {
5950 if (framesOut > 0) {
5951 activeTrack->mSink.frameCount = framesOut;
5952 activeTrack->releaseBuffer(&activeTrack->mSink);
5953 }
5954 } else {
5955 // FIXME could do a partial drop of framesOut
5956 if (activeTrack->mFramesToDrop > 0) {
5957 activeTrack->mFramesToDrop -= framesOut;
5958 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005959 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005960 }
5961 } else {
5962 activeTrack->mFramesToDrop += framesOut;
5963 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
5964 activeTrack->mSyncStartEvent->isCancelled()) {
5965 ALOGW("Synced record %s, session %d, trigger session %d",
5966 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
5967 activeTrack->sessionId(),
5968 (activeTrack->mSyncStartEvent != 0) ?
5969 activeTrack->mSyncStartEvent->triggerSession() : 0);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005970 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005971 }
5972 }
5973 }
5974
5975 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005976 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005977 }
5978 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005979
5980 switch (overrun) {
5981 case OVERRUN_TRUE:
5982 // client isn't retrieving buffers fast enough
5983 if (!activeTrack->setOverflow()) {
5984 nsecs_t now = systemTime();
5985 // FIXME should lastWarning per track?
5986 if ((now - lastWarning) > kWarningThrottleNs) {
5987 ALOGW("RecordThread: buffer overflow");
5988 lastWarning = now;
5989 }
5990 }
5991 break;
5992 case OVERRUN_FALSE:
5993 activeTrack->clearOverflow();
5994 break;
5995 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005996 break;
5997 }
5998
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005999 }
6000
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006001unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08006002 // enable changes in effect chain
6003 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006004 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08006005 }
6006
Glenn Kasten93e471f2013-08-19 08:40:07 -07006007 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08006008
6009 {
6010 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07006011 for (size_t i = 0; i < mTracks.size(); i++) {
6012 sp<RecordTrack> track = mTracks[i];
6013 track->invalidate();
6014 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006015 mActiveTracks.clear();
6016 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08006017 mStartStopCond.broadcast();
6018 }
6019
6020 releaseWakeLock();
6021
6022 ALOGV("RecordThread %p exiting", this);
6023 return false;
6024}
6025
Glenn Kasten93e471f2013-08-19 08:40:07 -07006026void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08006027{
6028 if (!mStandby) {
6029 inputStandBy();
6030 mStandby = true;
6031 }
6032}
6033
6034void AudioFlinger::RecordThread::inputStandBy()
6035{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006036 // Idle the fast capture if it's currently running
6037 if (mFastCapture != 0) {
6038 FastCaptureStateQueue *sq = mFastCapture->sq();
6039 FastCaptureState *state = sq->begin();
6040 if (!(state->mCommand & FastCaptureState::IDLE)) {
6041 state->mCommand = FastCaptureState::COLD_IDLE;
6042 state->mColdFutexAddr = &mFastCaptureFutex;
6043 state->mColdGen++;
6044 mFastCaptureFutex = 0;
6045 sq->end();
6046 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
6047 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
6048#if 0
6049 if (kUseFastCapture == FastCapture_Dynamic) {
6050 // FIXME
6051 }
6052#endif
6053#ifdef AUDIO_WATCHDOG
6054 // FIXME
6055#endif
6056 } else {
6057 sq->end(false /*didModify*/);
6058 }
6059 }
Eric Laurent81784c32012-11-19 14:55:58 -08006060 mInput->stream->common.standby(&mInput->stream->common);
6061}
6062
Glenn Kasten05997e22014-03-13 15:08:33 -07006063// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07006064sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08006065 const sp<AudioFlinger::Client>& client,
6066 uint32_t sampleRate,
6067 audio_format_t format,
6068 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08006069 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08006070 int sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07006071 size_t *notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08006072 int uid,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07006073 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08006074 pid_t tid,
6075 status_t *status)
6076{
Glenn Kasten74935e42013-12-19 08:56:45 -08006077 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08006078 sp<RecordTrack> track;
6079 status_t lStatus;
6080
Glenn Kasten90e58b12013-07-31 16:16:02 -07006081 // client expresses a preference for FAST, but we get the final say
6082 if (*flags & IAudioFlinger::TRACK_FAST) {
6083 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07006084 // we formerly checked for a callback handler (non-0 tid),
6085 // but that is no longer required for TRANSFER_OBTAIN mode
6086 //
Glenn Kasten74105912014-07-03 12:28:53 -07006087 // frame count is not specified, or is exactly the pipe depth
6088 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006089 // PCM data
6090 audio_is_linear_pcm(format) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006091 // native format
6092 (format == mFormat) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006093 // native channel mask
6094 (channelMask == mChannelMask) &&
6095 // native hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07006096 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006097 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006098 hasFastCapture() &&
6099 // there are sufficient fast track slots available
6100 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07006101 ) {
Glenn Kasten74105912014-07-03 12:28:53 -07006102 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%u mFrameCount=%u",
Glenn Kasten90e58b12013-07-31 16:16:02 -07006103 frameCount, mFrameCount);
6104 } else {
Glenn Kasten74105912014-07-03 12:28:53 -07006105 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%u mFrameCount=%u mPipeFramesP2=%u "
6106 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006107 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Glenn Kasten74105912014-07-03 12:28:53 -07006108 frameCount, mFrameCount, mPipeFramesP2,
6109 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
6110 hasFastCapture(), tid, mFastTrackAvail);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006111 *flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kasten74105912014-07-03 12:28:53 -07006112 }
6113 }
6114
6115 // compute track buffer size in frames, and suggest the notification frame count
6116 if (*flags & IAudioFlinger::TRACK_FAST) {
6117 // fast track: frame count is exactly the pipe depth
6118 frameCount = mPipeFramesP2;
6119 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
6120 *notificationFrames = mFrameCount;
6121 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006122 // not fast track: max notification period is resampled equivalent of one HAL buffer time
6123 // or 20 ms if there is a fast capture
6124 // TODO This could be a roundupRatio inline, and const
6125 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
6126 * sampleRate + mSampleRate - 1) / mSampleRate;
6127 // minimum number of notification periods is at least kMinNotifications,
6128 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
6129 static const size_t kMinNotifications = 3;
6130 static const uint32_t kMinMs = 30;
6131 // TODO This could be a roundupRatio inline
6132 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
6133 // TODO This could be a roundupRatio inline
6134 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
6135 maxNotificationFrames;
6136 const size_t minFrameCount = maxNotificationFrames *
6137 max(kMinNotifications, minNotificationsByMs);
6138 frameCount = max(frameCount, minFrameCount);
6139 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
6140 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07006141 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07006142 }
Glenn Kasten74935e42013-12-19 08:56:45 -08006143 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07006144
Glenn Kasten15e57982013-09-24 11:52:37 -07006145 lStatus = initCheck();
6146 if (lStatus != NO_ERROR) {
6147 ALOGE("createRecordTrack_l() audio driver not initialized");
6148 goto Exit;
6149 }
Eric Laurent81784c32012-11-19 14:55:58 -08006150
6151 { // scope for mLock
6152 Mutex::Autolock _l(mLock);
6153
6154 track = new RecordTrack(this, client, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07006155 format, channelMask, frameCount, NULL, sessionId, uid,
6156 *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08006157
Glenn Kasten03003332013-08-06 15:40:54 -07006158 lStatus = track->initCheck();
6159 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07006160 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08006161 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08006162 goto Exit;
6163 }
6164 mTracks.add(track);
6165
6166 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6167 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6168 mAudioFlinger->btNrecIsOff();
6169 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6170 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006171
6172 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
6173 pid_t callingPid = IPCThreadState::self()->getCallingPid();
6174 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
6175 // so ask activity manager to do this on our behalf
6176 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
6177 }
Eric Laurent81784c32012-11-19 14:55:58 -08006178 }
Glenn Kasten05997e22014-03-13 15:08:33 -07006179
Eric Laurent81784c32012-11-19 14:55:58 -08006180 lStatus = NO_ERROR;
6181
6182Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07006183 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08006184 return track;
6185}
6186
6187status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
6188 AudioSystem::sync_event_t event,
6189 int triggerSession)
6190{
6191 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
6192 sp<ThreadBase> strongMe = this;
6193 status_t status = NO_ERROR;
6194
6195 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006196 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006197 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006198 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08006199 triggerSession,
6200 recordTrack->sessionId(),
6201 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006202 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08006203 // Sync event can be cancelled by the trigger session if the track is not in a
6204 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006205 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006206 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006207 } else {
6208 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006209 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006210 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08006211 }
6212 }
6213
6214 {
Glenn Kasten47c20702013-08-13 15:37:35 -07006215 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08006216 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006217 if (mActiveTracks.indexOf(recordTrack) >= 0) {
6218 if (recordTrack->mState == TrackBase::PAUSING) {
6219 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006220 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006221 } else {
6222 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08006223 }
6224 return status;
6225 }
6226
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006227 // TODO consider other ways of handling this, such as changing the state to :STARTING and
6228 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
6229 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006230 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08006231 mActiveTracks.add(recordTrack);
6232 mActiveTracksGen++;
Eric Laurent83b88082014-06-20 18:31:16 -07006233 status_t status = NO_ERROR;
6234 if (recordTrack->isExternalTrack()) {
6235 mLock.unlock();
Eric Laurent4dc68062014-07-28 17:26:49 -07006236 status = AudioSystem::startInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006237 mLock.lock();
6238 // FIXME should verify that recordTrack is still in mActiveTracks
6239 if (status != NO_ERROR) {
6240 mActiveTracks.remove(recordTrack);
6241 mActiveTracksGen++;
6242 recordTrack->clearSyncStartEvent();
6243 ALOGV("RecordThread::start error %d", status);
6244 return status;
6245 }
Eric Laurent81784c32012-11-19 14:55:58 -08006246 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006247 // Catch up with current buffer indices if thread is already running.
6248 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
6249 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
6250 // see previously buffered data before it called start(), but with greater risk of overrun.
6251
Andy Hung73c02e42015-03-29 01:13:58 -07006252 recordTrack->mResamplerBufferProvider->reset();
Andy Hung97a893e2015-03-29 01:03:07 -07006253 // clear any converter state as new data will be discontinuous
6254 recordTrack->mRecordBufferConverter->reset();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006255 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08006256 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08006257 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08006258 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006259 ALOGV("Record failed to start");
6260 status = BAD_VALUE;
6261 goto startError;
6262 }
Eric Laurent81784c32012-11-19 14:55:58 -08006263 return status;
6264 }
Glenn Kasten7c027242012-12-26 14:43:16 -08006265
Eric Laurent81784c32012-11-19 14:55:58 -08006266startError:
Eric Laurent83b88082014-06-20 18:31:16 -07006267 if (recordTrack->isExternalTrack()) {
Eric Laurent4dc68062014-07-28 17:26:49 -07006268 AudioSystem::stopInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006269 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006270 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006271 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08006272 return status;
6273}
6274
Eric Laurent81784c32012-11-19 14:55:58 -08006275void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6276{
6277 sp<SyncEvent> strongEvent = event.promote();
6278
6279 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08006280 sp<RefBase> ptr = strongEvent->cookie().promote();
6281 if (ptr != 0) {
6282 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
6283 recordTrack->handleSyncStartEvent(strongEvent);
6284 }
Eric Laurent81784c32012-11-19 14:55:58 -08006285 }
6286}
6287
Glenn Kastena8356f62013-07-25 14:37:52 -07006288bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08006289 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07006290 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006291 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08006292 return false;
6293 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006294 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08006295 recordTrack->mState = TrackBase::PAUSING;
6296 // do not wait for mStartStopCond if exiting
6297 if (exitPending()) {
6298 return true;
6299 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006300 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08006301 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006302 // if we have been restarted, recordTrack is in mActiveTracks here
6303 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006304 ALOGV("Record stopped OK");
6305 return true;
6306 }
6307 return false;
6308}
6309
Glenn Kasten0f11b512014-01-31 16:18:54 -08006310bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08006311{
6312 return false;
6313}
6314
Glenn Kasten0f11b512014-01-31 16:18:54 -08006315status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006316{
6317#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
6318 if (!isValidSyncEvent(event)) {
6319 return BAD_VALUE;
6320 }
6321
6322 int eventSession = event->triggerSession();
6323 status_t ret = NAME_NOT_FOUND;
6324
6325 Mutex::Autolock _l(mLock);
6326
6327 for (size_t i = 0; i < mTracks.size(); i++) {
6328 sp<RecordTrack> track = mTracks[i];
6329 if (eventSession == track->sessionId()) {
6330 (void) track->setSyncEvent(event);
6331 ret = NO_ERROR;
6332 }
6333 }
6334 return ret;
6335#else
6336 return BAD_VALUE;
6337#endif
6338}
6339
6340// destroyTrack_l() must be called with ThreadBase::mLock held
6341void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6342{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006343 track->terminate();
6344 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08006345 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08006346 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006347 removeTrack_l(track);
6348 }
6349}
6350
6351void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6352{
6353 mTracks.remove(track);
6354 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006355 if (track->isFastTrack()) {
6356 ALOG_ASSERT(!mFastTrackAvail);
6357 mFastTrackAvail = true;
6358 }
Eric Laurent81784c32012-11-19 14:55:58 -08006359}
6360
6361void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6362{
6363 dumpInternals(fd, args);
6364 dumpTracks(fd, args);
6365 dumpEffectChains(fd, args);
6366}
6367
6368void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6369{
Elliott Hughes87cebad2014-05-22 10:14:43 -07006370 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08006371
Glenn Kasten44182c22015-03-05 17:12:23 -08006372 dumpBase(fd, args);
6373
6374 if (mActiveTracks.size() == 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006375 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006376 }
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006377 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006378 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08006379
Glenn Kasten2f90c512015-12-02 11:40:09 -08006380 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
6381 // while we are dumping it. It may be inconsistent, but it won't mutate!
6382 // This is a large object so we place it on the heap.
6383 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
6384 const FastCaptureDumpState *copy = new FastCaptureDumpState(mFastCaptureDumpState);
6385 copy->dump(fd);
6386 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08006387}
6388
Glenn Kasten0f11b512014-01-31 16:18:54 -08006389void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006390{
6391 const size_t SIZE = 256;
6392 char buffer[SIZE];
6393 String8 result;
6394
Marco Nelissenb2208842014-02-07 14:00:50 -08006395 size_t numtracks = mTracks.size();
6396 size_t numactive = mActiveTracks.size();
6397 size_t numactiveseen = 0;
Elliott Hughes87cebad2014-05-22 10:14:43 -07006398 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08006399 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006400 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08006401 RecordTrack::appendDumpHeader(result);
6402 for (size_t i = 0; i < numtracks ; ++i) {
6403 sp<RecordTrack> track = mTracks[i];
6404 if (track != 0) {
6405 bool active = mActiveTracks.indexOf(track) >= 0;
6406 if (active) {
6407 numactiveseen++;
6408 }
6409 track->dump(buffer, SIZE, active);
6410 result.append(buffer);
6411 }
Eric Laurent81784c32012-11-19 14:55:58 -08006412 }
Marco Nelissenb2208842014-02-07 14:00:50 -08006413 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006414 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006415 }
6416
Marco Nelissenb2208842014-02-07 14:00:50 -08006417 if (numactiveseen != numactive) {
6418 snprintf(buffer, SIZE, " The following tracks are in the active list but"
6419 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006420 result.append(buffer);
6421 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08006422 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08006423 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08006424 if (mTracks.indexOf(track) < 0) {
6425 track->dump(buffer, SIZE, true);
6426 result.append(buffer);
6427 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006428 }
Eric Laurent81784c32012-11-19 14:55:58 -08006429
6430 }
6431 write(fd, result.string(), result.size());
6432}
6433
Andy Hung73c02e42015-03-29 01:13:58 -07006434
6435void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
6436{
6437 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6438 RecordThread *recordThread = (RecordThread *) threadBase.get();
6439 mRsmpInFront = recordThread->mRsmpInRear;
6440 mRsmpInUnrel = 0;
6441}
6442
6443void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
6444 size_t *framesAvailable, bool *hasOverrun)
6445{
6446 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6447 RecordThread *recordThread = (RecordThread *) threadBase.get();
6448 const int32_t rear = recordThread->mRsmpInRear;
6449 const int32_t front = mRsmpInFront;
6450 const ssize_t filled = rear - front;
6451
6452 size_t framesIn;
6453 bool overrun = false;
6454 if (filled < 0) {
6455 // should not happen, but treat like a massive overrun and re-sync
6456 framesIn = 0;
6457 mRsmpInFront = rear;
6458 overrun = true;
6459 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
6460 framesIn = (size_t) filled;
6461 } else {
6462 // client is not keeping up with server, but give it latest data
6463 framesIn = recordThread->mRsmpInFrames;
6464 mRsmpInFront = /* front = */ rear - framesIn;
6465 overrun = true;
6466 }
6467 if (framesAvailable != NULL) {
6468 *framesAvailable = framesIn;
6469 }
6470 if (hasOverrun != NULL) {
6471 *hasOverrun = overrun;
6472 }
6473}
6474
Eric Laurent81784c32012-11-19 14:55:58 -08006475// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006476status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
6477 AudioBufferProvider::Buffer* buffer, int64_t pts __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006478{
Andy Hung73c02e42015-03-29 01:13:58 -07006479 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006480 if (threadBase == 0) {
6481 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006482 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006483 return NOT_ENOUGH_DATA;
6484 }
6485 RecordThread *recordThread = (RecordThread *) threadBase.get();
6486 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07006487 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07006488 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006489 // FIXME should not be P2 (don't want to increase latency)
6490 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006491 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07006492 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006493 front &= recordThread->mRsmpInFramesP2 - 1;
6494 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07006495 if (part1 > (size_t) filled) {
6496 part1 = filled;
6497 }
6498 size_t ask = buffer->frameCount;
6499 ALOG_ASSERT(ask > 0);
6500 if (part1 > ask) {
6501 part1 = ask;
6502 }
6503 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07006504 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07006505 buffer->raw = NULL;
6506 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07006507 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07006508 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08006509 }
6510
Andy Hung57446612015-04-19 23:56:46 -07006511 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07006512 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07006513 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08006514 return NO_ERROR;
6515}
6516
6517// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006518void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
6519 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006520{
Glenn Kasten85948432013-08-19 12:09:05 -07006521 size_t stepCount = buffer->frameCount;
6522 if (stepCount == 0) {
6523 return;
6524 }
Andy Hung73c02e42015-03-29 01:13:58 -07006525 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
6526 mRsmpInUnrel -= stepCount;
6527 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07006528 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006529 buffer->frameCount = 0;
6530}
6531
Andy Hung97a893e2015-03-29 01:03:07 -07006532AudioFlinger::RecordThread::RecordBufferConverter::RecordBufferConverter(
6533 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6534 uint32_t srcSampleRate,
6535 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6536 uint32_t dstSampleRate) :
6537 mSrcChannelMask(AUDIO_CHANNEL_INVALID), // updateParameters will set following vars
6538 // mSrcFormat
6539 // mSrcSampleRate
6540 // mDstChannelMask
6541 // mDstFormat
6542 // mDstSampleRate
6543 // mSrcChannelCount
6544 // mDstChannelCount
6545 // mDstFrameSize
6546 mBuf(NULL), mBufFrames(0), mBufFrameSize(0),
Andy Hungd330ee42015-04-20 13:23:41 -07006547 mResampler(NULL),
6548 mIsLegacyDownmix(false),
6549 mIsLegacyUpmix(false),
6550 mRequiresFloat(false),
6551 mInputConverterProvider(NULL)
Andy Hung97a893e2015-03-29 01:03:07 -07006552{
6553 (void)updateParameters(srcChannelMask, srcFormat, srcSampleRate,
6554 dstChannelMask, dstFormat, dstSampleRate);
6555}
6556
6557AudioFlinger::RecordThread::RecordBufferConverter::~RecordBufferConverter() {
6558 free(mBuf);
6559 delete mResampler;
Andy Hungd330ee42015-04-20 13:23:41 -07006560 delete mInputConverterProvider;
Andy Hung97a893e2015-03-29 01:03:07 -07006561}
6562
6563size_t AudioFlinger::RecordThread::RecordBufferConverter::convert(void *dst,
6564 AudioBufferProvider *provider, size_t frames)
6565{
Andy Hungd330ee42015-04-20 13:23:41 -07006566 if (mInputConverterProvider != NULL) {
6567 mInputConverterProvider->setBufferProvider(provider);
6568 provider = mInputConverterProvider;
6569 }
6570
6571 if (mResampler == NULL) {
Andy Hung97a893e2015-03-29 01:03:07 -07006572 ALOGVV("NO RESAMPLING sampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6573 mSrcSampleRate, mSrcFormat, mDstFormat);
6574
6575 AudioBufferProvider::Buffer buffer;
6576 for (size_t i = frames; i > 0; ) {
6577 buffer.frameCount = i;
6578 status_t status = provider->getNextBuffer(&buffer, 0);
6579 if (status != OK || buffer.frameCount == 0) {
6580 frames -= i; // cannot fill request.
6581 break;
6582 }
Andy Hungd330ee42015-04-20 13:23:41 -07006583 // format convert to destination buffer
6584 convertNoResampler(dst, buffer.raw, buffer.frameCount);
Andy Hung97a893e2015-03-29 01:03:07 -07006585
6586 dst = (int8_t*)dst + buffer.frameCount * mDstFrameSize;
6587 i -= buffer.frameCount;
6588 provider->releaseBuffer(&buffer);
6589 }
6590 } else {
6591 ALOGVV("RESAMPLING mSrcSampleRate:%u mDstSampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6592 mSrcSampleRate, mDstSampleRate, mSrcFormat, mDstFormat);
6593
Andy Hungd330ee42015-04-20 13:23:41 -07006594 // reallocate buffer if needed
6595 if (mBufFrameSize != 0 && mBufFrames < frames) {
6596 free(mBuf);
6597 mBufFrames = frames;
6598 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
6599 }
Andy Hung97a893e2015-03-29 01:03:07 -07006600 // resampler accumulates, but we only have one source track
Andy Hungd330ee42015-04-20 13:23:41 -07006601 memset(mBuf, 0, frames * mBufFrameSize);
6602 frames = mResampler->resample((int32_t*)mBuf, frames, provider);
6603 // format convert to destination buffer
6604 convertResampler(dst, mBuf, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006605 }
6606 return frames;
6607}
6608
6609status_t AudioFlinger::RecordThread::RecordBufferConverter::updateParameters(
6610 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6611 uint32_t srcSampleRate,
6612 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6613 uint32_t dstSampleRate)
6614{
6615 // quick evaluation if there is any change.
6616 if (mSrcFormat == srcFormat
6617 && mSrcChannelMask == srcChannelMask
6618 && mSrcSampleRate == srcSampleRate
6619 && mDstFormat == dstFormat
6620 && mDstChannelMask == dstChannelMask
6621 && mDstSampleRate == dstSampleRate) {
6622 return NO_ERROR;
6623 }
6624
Andy Hungdb4c0312015-05-06 08:46:52 -07006625 ALOGV("RecordBufferConverter updateParameters srcMask:%#x dstMask:%#x"
6626 " srcFormat:%#x dstFormat:%#x srcRate:%u dstRate:%u",
6627 srcChannelMask, dstChannelMask, srcFormat, dstFormat, srcSampleRate, dstSampleRate);
Andy Hung97a893e2015-03-29 01:03:07 -07006628 const bool valid =
6629 audio_is_input_channel(srcChannelMask)
6630 && audio_is_input_channel(dstChannelMask)
6631 && audio_is_valid_format(srcFormat) && audio_is_linear_pcm(srcFormat)
6632 && audio_is_valid_format(dstFormat) && audio_is_linear_pcm(dstFormat)
6633 && (srcSampleRate <= dstSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX)
6634 ; // no upsampling checks for now
6635 if (!valid) {
6636 return BAD_VALUE;
6637 }
6638
6639 mSrcFormat = srcFormat;
6640 mSrcChannelMask = srcChannelMask;
6641 mSrcSampleRate = srcSampleRate;
6642 mDstFormat = dstFormat;
6643 mDstChannelMask = dstChannelMask;
6644 mDstSampleRate = dstSampleRate;
6645
6646 // compute derived parameters
6647 mSrcChannelCount = audio_channel_count_from_in_mask(srcChannelMask);
6648 mDstChannelCount = audio_channel_count_from_in_mask(dstChannelMask);
6649 mDstFrameSize = mDstChannelCount * audio_bytes_per_sample(mDstFormat);
6650
Andy Hungd330ee42015-04-20 13:23:41 -07006651 // do we need to resample?
6652 delete mResampler;
6653 mResampler = NULL;
6654 if (mSrcSampleRate != mDstSampleRate) {
6655 mResampler = AudioResampler::create(AUDIO_FORMAT_PCM_FLOAT,
6656 mSrcChannelCount, mDstSampleRate);
6657 mResampler->setSampleRate(mSrcSampleRate);
6658 mResampler->setVolume(AudioMixer::UNITY_GAIN_FLOAT, AudioMixer::UNITY_GAIN_FLOAT);
6659 }
6660
6661 // are we running legacy channel conversion modes?
6662 mIsLegacyDownmix = (mSrcChannelMask == AUDIO_CHANNEL_IN_STEREO
6663 || mSrcChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK)
6664 && mDstChannelMask == AUDIO_CHANNEL_IN_MONO;
6665 mIsLegacyUpmix = mSrcChannelMask == AUDIO_CHANNEL_IN_MONO
6666 && (mDstChannelMask == AUDIO_CHANNEL_IN_STEREO
6667 || mDstChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK);
6668
6669 // do we need to process in float?
6670 mRequiresFloat = mResampler != NULL || mIsLegacyDownmix || mIsLegacyUpmix;
6671
6672 // do we need a staging buffer to convert for destination (we can still optimize this)?
6673 // we use mBufFrameSize > 0 to indicate both frame size as well as buffer necessity
6674 if (mResampler != NULL) {
6675 mBufFrameSize = max(mSrcChannelCount, FCC_2)
6676 * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
Andy Hunga97630b2015-07-22 23:27:24 -07006677 } else if (mIsLegacyUpmix || mIsLegacyDownmix) { // legacy modes always float
Andy Hungd330ee42015-04-20 13:23:41 -07006678 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
6679 } else if (mSrcChannelMask != mDstChannelMask && mDstFormat != mSrcFormat) {
Andy Hung97a893e2015-03-29 01:03:07 -07006680 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(mSrcFormat);
6681 } else {
6682 mBufFrameSize = 0;
6683 }
6684 mBufFrames = 0; // force the buffer to be resized.
6685
Andy Hungd330ee42015-04-20 13:23:41 -07006686 // do we need an input converter buffer provider to give us float?
6687 delete mInputConverterProvider;
6688 mInputConverterProvider = NULL;
6689 if (mRequiresFloat && mSrcFormat != AUDIO_FORMAT_PCM_FLOAT) {
6690 mInputConverterProvider = new ReformatBufferProvider(
6691 audio_channel_count_from_in_mask(mSrcChannelMask),
6692 mSrcFormat,
6693 AUDIO_FORMAT_PCM_FLOAT,
6694 256 /* provider buffer frame count */);
6695 }
6696
6697 // do we need a remixer to do channel mask conversion
6698 if (!mIsLegacyDownmix && !mIsLegacyUpmix && mSrcChannelMask != mDstChannelMask) {
6699 (void) memcpy_by_index_array_initialization_from_channel_mask(
6700 mIdxAry, ARRAY_SIZE(mIdxAry), mDstChannelMask, mSrcChannelMask);
Andy Hung97a893e2015-03-29 01:03:07 -07006701 }
6702 return NO_ERROR;
6703}
6704
Andy Hungd330ee42015-04-20 13:23:41 -07006705void AudioFlinger::RecordThread::RecordBufferConverter::convertNoResampler(
6706 void *dst, const void *src, size_t frames)
Andy Hung97a893e2015-03-29 01:03:07 -07006707{
Andy Hungd330ee42015-04-20 13:23:41 -07006708 // src is native type unless there is legacy upmix or downmix, whereupon it is float.
Andy Hung97a893e2015-03-29 01:03:07 -07006709 if (mBufFrameSize != 0 && mBufFrames < frames) {
6710 free(mBuf);
6711 mBufFrames = frames;
6712 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
6713 }
Andy Hungd330ee42015-04-20 13:23:41 -07006714 // do we need to do legacy upmix and downmix?
6715 if (mIsLegacyUpmix || mIsLegacyDownmix) {
Andy Hung97a893e2015-03-29 01:03:07 -07006716 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07006717 if (mIsLegacyUpmix) {
6718 upmix_to_stereo_float_from_mono_float((float *)dstBuf,
6719 (const float *)src, frames);
6720 } else /*mIsLegacyDownmix */ {
6721 downmix_to_mono_float_from_stereo_float((float *)dstBuf,
6722 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006723 }
Andy Hungd330ee42015-04-20 13:23:41 -07006724 if (mBuf != NULL) {
6725 memcpy_by_audio_format(dst, mDstFormat, mBuf, AUDIO_FORMAT_PCM_FLOAT,
6726 frames * mDstChannelCount);
6727 }
6728 return;
6729 }
6730 // do we need to do channel mask conversion?
6731 if (mSrcChannelMask != mDstChannelMask) {
Andy Hung97a893e2015-03-29 01:03:07 -07006732 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07006733 memcpy_by_index_array(dstBuf, mDstChannelCount,
6734 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mSrcFormat), frames);
6735 if (dstBuf == dst) {
6736 return; // format is the same
6737 }
6738 }
6739 // convert to destination buffer
6740 const void *convertBuf = mBuf != NULL ? mBuf : src;
6741 memcpy_by_audio_format(dst, mDstFormat, convertBuf, mSrcFormat,
6742 frames * mDstChannelCount);
6743}
6744
6745void AudioFlinger::RecordThread::RecordBufferConverter::convertResampler(
6746 void *dst, /*not-a-const*/ void *src, size_t frames)
6747{
6748 // src buffer format is ALWAYS float when entering this routine
6749 if (mIsLegacyUpmix) {
6750 ; // mono to stereo already handled by resampler
6751 } else if (mIsLegacyDownmix
6752 || (mSrcChannelMask == mDstChannelMask && mSrcChannelCount == 1)) {
6753 // the resampler outputs stereo for mono input channel (a feature?)
6754 // must convert to mono
6755 downmix_to_mono_float_from_stereo_float((float *)src,
6756 (const float *)src, frames);
6757 } else if (mSrcChannelMask != mDstChannelMask) {
6758 // convert to mono channel again for channel mask conversion (could be skipped
6759 // with further optimization).
Andy Hung97a893e2015-03-29 01:03:07 -07006760 if (mSrcChannelCount == 1) {
Andy Hungd330ee42015-04-20 13:23:41 -07006761 downmix_to_mono_float_from_stereo_float((float *)src,
6762 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006763 }
Andy Hungd330ee42015-04-20 13:23:41 -07006764 // convert to destination format (in place, OK as float is larger than other types)
6765 if (mDstFormat != AUDIO_FORMAT_PCM_FLOAT) {
6766 memcpy_by_audio_format(src, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
6767 frames * mSrcChannelCount);
6768 }
6769 // channel convert and save to dst
6770 memcpy_by_index_array(dst, mDstChannelCount,
6771 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mDstFormat), frames);
6772 return;
Andy Hung97a893e2015-03-29 01:03:07 -07006773 }
Andy Hungd330ee42015-04-20 13:23:41 -07006774 // convert to destination format and save to dst
6775 memcpy_by_audio_format(dst, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
6776 frames * mDstChannelCount);
Andy Hung97a893e2015-03-29 01:03:07 -07006777}
6778
Eric Laurent10351942014-05-08 18:49:52 -07006779bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
6780 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006781{
6782 bool reconfig = false;
6783
Eric Laurent10351942014-05-08 18:49:52 -07006784 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006785
Eric Laurent10351942014-05-08 18:49:52 -07006786 audio_format_t reqFormat = mFormat;
6787 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07006788 // 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 -07006789 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
6790
6791 AudioParameter param = AudioParameter(keyValuePair);
6792 int value;
6793 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
6794 // channel count change can be requested. Do we mandate the first client defines the
6795 // HAL sampling rate and channel count or do we allow changes on the fly?
6796 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6797 samplingRate = value;
6798 reconfig = true;
6799 }
6800 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07006801 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07006802 status = BAD_VALUE;
6803 } else {
6804 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08006805 reconfig = true;
6806 }
Eric Laurent10351942014-05-08 18:49:52 -07006807 }
6808 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
6809 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07006810 if (!audio_is_input_channel(mask) ||
6811 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07006812 status = BAD_VALUE;
6813 } else {
6814 channelMask = mask;
6815 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006816 }
Eric Laurent10351942014-05-08 18:49:52 -07006817 }
6818 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6819 // do not accept frame count changes if tracks are open as the track buffer
6820 // size depends on frame count and correct behavior would not be guaranteed
6821 // if frame count is changed after track creation
6822 if (mActiveTracks.size() > 0) {
6823 status = INVALID_OPERATION;
6824 } else {
6825 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006826 }
Eric Laurent10351942014-05-08 18:49:52 -07006827 }
6828 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6829 // forward device change to effects that have requested to be
6830 // aware of attached audio device.
6831 for (size_t i = 0; i < mEffectChains.size(); i++) {
6832 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08006833 }
Eric Laurent81784c32012-11-19 14:55:58 -08006834
Eric Laurent10351942014-05-08 18:49:52 -07006835 // store input device and output device but do not forward output device to audio HAL.
6836 // Note that status is ignored by the caller for output device
6837 // (see AudioFlinger::setParameters()
6838 if (audio_is_output_devices(value)) {
6839 mOutDevice = value;
6840 status = BAD_VALUE;
6841 } else {
6842 mInDevice = value;
Eric Laurente8726fe2015-06-26 09:39:24 -07006843 if (value != AUDIO_DEVICE_NONE) {
6844 mPrevInDevice = value;
6845 }
Eric Laurent10351942014-05-08 18:49:52 -07006846 // disable AEC and NS if the device is a BT SCO headset supporting those
6847 // pre processings
6848 if (mTracks.size() > 0) {
6849 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6850 mAudioFlinger->btNrecIsOff();
6851 for (size_t i = 0; i < mTracks.size(); i++) {
6852 sp<RecordTrack> track = mTracks[i];
6853 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
6854 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08006855 }
6856 }
6857 }
Eric Laurent10351942014-05-08 18:49:52 -07006858 }
6859 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
6860 mAudioSource != (audio_source_t)value) {
6861 // forward device change to effects that have requested to be
6862 // aware of attached audio device.
6863 for (size_t i = 0; i < mEffectChains.size(); i++) {
6864 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08006865 }
Eric Laurent10351942014-05-08 18:49:52 -07006866 mAudioSource = (audio_source_t)value;
6867 }
Glenn Kastene198c362013-08-13 09:13:36 -07006868
Eric Laurent10351942014-05-08 18:49:52 -07006869 if (status == NO_ERROR) {
6870 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6871 keyValuePair.string());
6872 if (status == INVALID_OPERATION) {
6873 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006874 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6875 keyValuePair.string());
Eric Laurent10351942014-05-08 18:49:52 -07006876 }
6877 if (reconfig) {
6878 if (status == BAD_VALUE &&
Andy Hung97a893e2015-03-29 01:03:07 -07006879 audio_is_linear_pcm(mInput->stream->common.get_format(&mInput->stream->common)) &&
6880 audio_is_linear_pcm(reqFormat) &&
Eric Laurent10351942014-05-08 18:49:52 -07006881 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
Andy Hung97a893e2015-03-29 01:03:07 -07006882 <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate)) &&
Andy Hunge5412692014-05-16 11:25:07 -07006883 audio_channel_count_from_in_mask(
Andy Hungd1abb8f2015-05-05 23:42:34 -07006884 mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07006885 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006886 }
Eric Laurent10351942014-05-08 18:49:52 -07006887 if (status == NO_ERROR) {
6888 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07006889 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08006890 }
6891 }
Eric Laurent81784c32012-11-19 14:55:58 -08006892 }
Eric Laurent10351942014-05-08 18:49:52 -07006893
Eric Laurent81784c32012-11-19 14:55:58 -08006894 return reconfig;
6895}
6896
6897String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6898{
Eric Laurent81784c32012-11-19 14:55:58 -08006899 Mutex::Autolock _l(mLock);
6900 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07006901 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08006902 }
6903
Glenn Kastend8ea6992013-07-16 14:17:15 -07006904 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
6905 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08006906 free(s);
6907 return out_s8;
6908}
6909
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07006910void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07006911 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
6912
6913 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08006914
6915 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07006916 case AUDIO_INPUT_OPENED:
6917 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07006918 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07006919 desc->mChannelMask = mChannelMask;
6920 desc->mSamplingRate = mSampleRate;
6921 desc->mFormat = mFormat;
6922 desc->mFrameCount = mFrameCount;
6923 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006924 break;
6925
Eric Laurent73e26b62015-04-27 16:55:58 -07006926 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08006927 default:
6928 break;
6929 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07006930 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08006931}
6932
Glenn Kastendeca2ae2014-02-07 10:25:56 -08006933void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006934{
Eric Laurent81784c32012-11-19 14:55:58 -08006935 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
6936 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Andy Hunge5412692014-05-16 11:25:07 -07006937 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Andy Hungd330ee42015-04-20 13:23:41 -07006938 if (mChannelCount > FCC_8) {
6939 ALOGE("HAL channel count %d > %d", mChannelCount, FCC_8);
6940 }
Andy Hung463be252014-07-10 16:56:07 -07006941 mHALFormat = mInput->stream->common.get_format(&mInput->stream->common);
6942 mFormat = mHALFormat;
Andy Hungd330ee42015-04-20 13:23:41 -07006943 if (!audio_is_linear_pcm(mFormat)) {
6944 ALOGE("HAL format %#x is not linear pcm", mFormat);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07006945 }
Eric Laurent665470b2014-07-03 16:37:08 -07006946 mFrameSize = audio_stream_in_frame_size(mInput->stream);
Glenn Kasten548efc92012-11-29 08:48:51 -08006947 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
6948 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006949 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08006950 // 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 -07006951 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08006952 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006953 // A larger value should allow more old data to be read after a track calls start(),
6954 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07006955 //
6956 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08006957 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07006958 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07006959 free(mRsmpInBuffer);
Andy Hung0a01c2f2015-09-21 12:44:54 -07006960 mRsmpInBuffer = NULL;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006961
6962 // TODO optimize audio capture buffer sizes ...
6963 // Here we calculate the size of the sliding buffer used as a source
6964 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
6965 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
6966 // be better to have it derived from the pipe depth in the long term.
6967 // The current value is higher than necessary. However it should not add to latency.
6968
Glenn Kasten85948432013-08-19 12:09:05 -07006969 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Andy Hung0a01c2f2015-09-21 12:44:54 -07006970 size_t bufferSize = (mRsmpInFramesP2 + mFrameCount - 1) * mFrameSize;
6971 (void)posix_memalign(&mRsmpInBuffer, 32, bufferSize);
6972 memset(mRsmpInBuffer, 0, bufferSize); // if posix_memalign fails, will segv here.
Eric Laurent81784c32012-11-19 14:55:58 -08006973
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006974 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
6975 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08006976}
6977
Glenn Kasten5f972c02014-01-13 09:59:31 -08006978uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08006979{
6980 Mutex::Autolock _l(mLock);
6981 if (initCheck() != NO_ERROR) {
6982 return 0;
6983 }
6984
6985 return mInput->stream->get_input_frames_lost(mInput->stream);
6986}
6987
6988uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
6989{
6990 Mutex::Autolock _l(mLock);
6991 uint32_t result = 0;
6992 if (getEffectChain_l(sessionId) != 0) {
6993 result = EFFECT_SESSION;
6994 }
6995
6996 for (size_t i = 0; i < mTracks.size(); ++i) {
6997 if (sessionId == mTracks[i]->sessionId()) {
6998 result |= TRACK_SESSION;
6999 break;
7000 }
7001 }
7002
7003 return result;
7004}
7005
7006KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
7007{
7008 KeyedVector<int, bool> ids;
7009 Mutex::Autolock _l(mLock);
7010 for (size_t j = 0; j < mTracks.size(); ++j) {
7011 sp<RecordThread::RecordTrack> track = mTracks[j];
7012 int sessionId = track->sessionId();
7013 if (ids.indexOfKey(sessionId) < 0) {
7014 ids.add(sessionId, true);
7015 }
7016 }
7017 return ids;
7018}
7019
7020AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
7021{
7022 Mutex::Autolock _l(mLock);
7023 AudioStreamIn *input = mInput;
7024 mInput = NULL;
7025 return input;
7026}
7027
7028// this method must always be called either with ThreadBase mLock held or inside the thread loop
7029audio_stream_t* AudioFlinger::RecordThread::stream() const
7030{
7031 if (mInput == NULL) {
7032 return NULL;
7033 }
7034 return &mInput->stream->common;
7035}
7036
7037status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7038{
7039 // only one chain per input thread
7040 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07007041 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08007042 return INVALID_OPERATION;
7043 }
7044 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07007045 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08007046 chain->setInBuffer(NULL);
7047 chain->setOutBuffer(NULL);
7048
7049 checkSuspendOnAddEffectChain_l(chain);
7050
Eric Laurent1b928682014-10-02 19:41:47 -07007051 // make sure enabled pre processing effects state is communicated to the HAL as we
7052 // just moved them to a new input stream.
7053 chain->syncHalEffectsState();
7054
Eric Laurent81784c32012-11-19 14:55:58 -08007055 mEffectChains.add(chain);
7056
7057 return NO_ERROR;
7058}
7059
7060size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7061{
7062 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
7063 ALOGW_IF(mEffectChains.size() != 1,
7064 "removeEffectChain_l() %p invalid chain size %d on thread %p",
7065 chain.get(), mEffectChains.size(), this);
7066 if (mEffectChains.size() == 1) {
7067 mEffectChains.removeAt(0);
7068 }
7069 return 0;
7070}
7071
Eric Laurent1c333e22014-05-20 10:48:17 -07007072status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
7073 audio_patch_handle_t *handle)
7074{
7075 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007076
7077 // store new device and send to effects
7078 mInDevice = patch->sources[0].ext.device.type;
Eric Laurent296fb132015-05-01 11:38:42 -07007079 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07007080 for (size_t i = 0; i < mEffectChains.size(); i++) {
7081 mEffectChains[i]->setDevice_l(mInDevice);
7082 }
7083
7084 // disable AEC and NS if the device is a BT SCO headset supporting those
7085 // pre processings
7086 if (mTracks.size() > 0) {
7087 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7088 mAudioFlinger->btNrecIsOff();
7089 for (size_t i = 0; i < mTracks.size(); i++) {
7090 sp<RecordTrack> track = mTracks[i];
7091 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7092 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
7093 }
7094 }
7095
7096 // store new source and send to effects
7097 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7098 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07007099 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07007100 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07007101 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007102 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007103
Eric Laurent054d9d32015-04-24 08:48:48 -07007104 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007105 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
7106 status = hwDevice->create_audio_patch(hwDevice,
7107 patch->num_sources,
7108 patch->sources,
7109 patch->num_sinks,
7110 patch->sinks,
7111 handle);
7112 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007113 char *address;
7114 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
7115 address = audio_device_address_to_parameter(
7116 patch->sources[0].ext.device.type,
7117 patch->sources[0].ext.device.address);
7118 } else {
7119 address = (char *)calloc(1, 1);
7120 }
7121 AudioParameter param = AudioParameter(String8(address));
7122 free(address);
7123 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING),
7124 (int)patch->sources[0].ext.device.type);
7125 param.addInt(String8(AUDIO_PARAMETER_STREAM_INPUT_SOURCE),
7126 (int)patch->sinks[0].ext.mix.usecase.source);
7127 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7128 param.toString().string());
7129 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07007130 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007131
Eric Laurente8726fe2015-06-26 09:39:24 -07007132 if (mInDevice != mPrevInDevice) {
7133 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
7134 mPrevInDevice = mInDevice;
7135 }
Eric Laurent296fb132015-05-01 11:38:42 -07007136
Eric Laurent1c333e22014-05-20 10:48:17 -07007137 return status;
7138}
7139
7140status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
7141{
7142 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007143
7144 mInDevice = AUDIO_DEVICE_NONE;
7145
Eric Laurent1c333e22014-05-20 10:48:17 -07007146 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
7147 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
7148 status = hwDevice->release_audio_patch(hwDevice, handle);
7149 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007150 AudioParameter param;
7151 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
7152 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7153 param.toString().string());
Eric Laurent1c333e22014-05-20 10:48:17 -07007154 }
7155 return status;
7156}
7157
Eric Laurent83b88082014-06-20 18:31:16 -07007158void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
7159{
7160 Mutex::Autolock _l(mLock);
7161 mTracks.add(record);
7162}
7163
7164void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
7165{
7166 Mutex::Autolock _l(mLock);
7167 destroyTrack_l(record);
7168}
7169
7170void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
7171{
7172 ThreadBase::getAudioPortConfig(config);
7173 config->role = AUDIO_PORT_ROLE_SINK;
7174 config->ext.mix.hw_module = mInput->audioHwDev->handle();
7175 config->ext.mix.usecase.source = mAudioSource;
7176}
Eric Laurent1c333e22014-05-20 10:48:17 -07007177
Glenn Kasten63238ef2015-03-02 15:50:29 -08007178} // namespace android